Scroll to navigation

Net::LDAP(3) User Contributed Perl Documentation Net::LDAP(3)

NAME

Net::LDAP - Lightweight Directory Access Protocol

SYNOPSIS

 use Net::LDAP;
 $ldap = Net::LDAP->new( 'ldap.example.com' )  or  die "$@";
 $mesg = $ldap->bind;                         # anonymous bind
 $mesg->code  and  die $mesg->error;          # check for errors
 $srch = $ldap->search( base   => "c=US",     # perform a search
                        filter => "(&(sn=Barr)(o=Texas Instruments))"
                      );
 $srch->code  and  die $srch->error;          # check for errors
 foreach $entry ($srch->entries) { $entry->dump; }
 $mesg = $ldap->unbind;                       # take down session
 $ldap = Net::LDAP->new( 'ldaps://ldap.example.com' )  or  die "$@";
 # simple bind with DN and password
 $mesg = $ldap->bind( 'cn=root, o=University of Michigan, c=us',
                      password => 'secret'
                    );
 $mesg->code  and  die $mesg->error;          # check for errors
 $result = $ldap->add( 'cn=Barbara Jensen, o=University of Michigan, c=US',
                       attrs => [
                         cn          => ['Barbara Jensen', 'Barbs Jensen'],
                         sn          => 'Jensen',
                         mail        => 'b.jensen@umich.edu',
                         objectclass => ['top', 'person',
                                         'organizationalPerson',
                                         'inetOrgPerson' ],
                       ]
                     );
 $result->code  and  warn "failed to add entry: ", $result->error;
 $mesg = $ldap->unbind;                       # take down session

DESCRIPTION

Net::LDAP is a collection of modules that implements a LDAP services API for Perl programs. The module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries.

This document assumes that the reader has some knowledge of the LDAP protocol.

CONSTRUCTOR

Creates a new Net::LDAP object and opens a connection to the named host.

"HOST" may be a host name or an IP address. TCP port may be specified after the host name followed by a colon (such as localhost:10389). The default TCP port for LDAP is 389.

You can also specify a URI, such as 'ldaps://127.0.0.1:666' or 'ldapi://%2fvar%2flib%2fldap_sock'. Note that '%2f's in the LDAPI socket path will be translated into '/'. This is to support LDAP query options like base, search etc. although the query part of the URI will be ignored in this context. If port was not specified in the URI, the default is either 389 or 636 for 'LDAP' and 'LDAPS' schemes respectively.

"HOST" may also be a reference to an array of hosts, host-port pairs or URIs to try. Each will be tried in order until a connection is made. Only when all have failed will the result of "undef" be returned.

Port to connect to on the remote server. May be overridden by "HOST".
Connection scheme to use when not using an URI as "HOST". (Default: ldap)
If given, set the socket's SO_KEEPALIVE option depending on the Boolean value of the option. (Default: use system default)

Failures in changing the socket's SO_KEEPALIVE option are ignored.

Timeout passed to IO::Socket when connecting the remote server. (Default: 120)
Will be passed to IO::Socket as the "MultiHomed" parameter when connecting to the remote server
Will be passed to IO::Socket as the "LocalAddr" parameter, which sets the client's IP address (as opposed to the server's IP address.)
Set the debug level. See the debug method for details.
Perform all operations asynchronously.
In synchronous mode, change what happens when an error is detected.
'die'
Net::LDAP will croak whenever an error is detected.
'warn'
Net::LDAP will warn whenever an error is detected.
'undef'
Net::LDAP will warn whenever an error is detected and "-w" is in effect. The method that was called will return "undef".

Note this value is the string 'undef', not the "undef" value.

sub { ... }
The given sub will be called in a scalar context with a single argument, the result message. The value returned will be the return value for the method that was called.
Set the protocol version being used (default is LDAPv3). This is useful if you want to talk to an old server and therefore have to use LDAPv2.
Use REGEX to denote the names of attributes that are to be considered binary in search results.

When this option is given, Net::LDAP converts all values of attributes not matching this REGEX into Perl UTF-8 strings so that the regular Perl operators (pattern matching, ...) can operate as one expects even on strings with international characters.

If this option is not given, attribute values are treated as byte strings.

Example: raw => qr/(?i:^jpegPhoto|;binary)/

Try to connect to the server using the specified IP protocol only, i.e. either IPv4 or IPv6. If the protocol selected is not supported, connecting will fail.

The default is to use any of the two protocols.

Example

  $ldap = Net::LDAP->new( 'remote.host', async => 1 );

LDAPS connections have some extra valid options, see the start_tls method for details. Note the default port for LDAPS is 636, and the default value for 'sslversion' is the value used as default by IO::Socket::SSL.

For LDAPI connections, HOST is actually the location of a UNIX domain socket to connect to. The default location is '/var/run/ldapi'.

METHODS

Each of the following methods take as arguments some number of fixed parameters followed by options, these options are passed in a named fashion, for example

  $mesg = $ldap->bind( "cn=me,o=example", password => "mypasswd");

The return value from these methods is an object derived from the Net::LDAP::Message class. The methods of this class allow you to examine the status of the request.

Abandon a previously issued request. "ID" may be a number or an object which is a sub-class of Net::LDAP::Message, returned from a previous method call.
See "CONTROLS" below
See "CALLBACKS" below

Example

  $res = $ldap->search( @search_args );
  $mesg = $ldap->abandon( $res ); # This could be written as $res->abandon
Add a new entry to the directory. "DN" can be either a Net::LDAP::Entry object or a string.
"VALUE" should be a string if only a single value is wanted, or a reference to an array of strings if multiple values are wanted.

This argument is not used if "DN" is a Net::LDAP::Entry object.

See "CONTROLS" below
See "CALLBACKS" below

Example

  # $entry is an object of class Net::LDAP::Entry
  $mesg = $ldap->add( $entry );
  $mesg = $ldap->add( $dn,
                      attrs => [
                        name  => 'Graham Barr',
                        attr  => 'value1',
                        attr  => 'value2',
                        multi => [qw(value1 value2)]
                      ]
                    );
Bind (log in) to the server. "DN" is the DN to bind with. An anonymous bind may be done by calling bind without any arguments.
See "CONTROLS" below
See "CALLBACKS" below
Bind without any password. The value passed with this option is ignored.
Bind with the given password.
Bind using a SASL mechanism. The argument given should be a sub-class of Authen::SASL or an Authen::SASL client connection by calling "client_new" on an Authen::SASL object.

If passed an Authen::SASL object then "client_new" will be called to create a client connection object. The hostname passed by "Net::LDAP" to "client_new" can be set using the "sasl_host" option below. If this is not correct for your environment, consider calling "client_new" yourself and passing the client connection object as "SASLOBJ".

When binding using SASL, allow the hostname used in the SASL communication to differ from the hostname connected to.

If "SASLHOST" evaluates to TRUE, then it is used as the SASL hostname.

If it evaluates to FALSE, then the value is determined by calling "peerhost" on the socket. In older versions of Net::LDAP this was the standard behaviour, but it turned out to cause more trouble than it fixed.

When the option is not given, the SASL host name used defaults to the host name / IP address taken from the "HOST" parameter when connecting.

Example

  $mesg = $ldap->bind; # Anonymous bind
  $mesg = $ldap->bind( $dn, password => $password );
  # $sasl is an object of class Authen::SASL
  $mesg = $ldap->bind( $dn, sasl => $sasl, version => 3 );
Compare values in an attribute in the entry given by "DN" on the server. "DN" may be a string or a Net::LDAP::Entry object.
The name of the attribute to compare.
The value to compare with.
See "CONTROLS" below.
See "CALLBACKS" below.

Example

  $mesg = $ldap->compare( $dn,
                          attr  => 'cn',
                          value => 'Graham Barr'
                        );
Delete the entry given by "DN" from the server. "DN" may be a string or a Net::LDAP::Entry object.
See "CONTROLS" below.
See "CALLBACKS" below.

Example

 $mesg = $ldap->delete( $dn );
Rename the entry given by "DN" on the server. "DN" may be a string or a Net::LDAP::Entry object.
This value should be a new RDN to assign to "DN".
This option should be passed if the existing RDN is to be deleted.
If given this value should be the DN of the new superior for "DN".
See "CONTROLS" below.
See "CALLBACKS" below.

Example

 $mesg = $ldap->moddn( $dn, newrdn => 'cn=Graham Barr' );
Modify the contents of the entry given by "DN" on the server. "DN" may be a string or a Net::LDAP::Entry object.
Add more attributes or values to the entry. "VALUE" should be a string if only a single value is wanted in the attribute, or a reference to an array of strings if multiple values are wanted.

  $mesg = $ldap->modify( $dn,
    add => {
      description => 'List of members',    # Add description attribute
      member      => [
        'cn=member1,ou=people,dc=example,dc=com',    # Add to attribute
        'cn=member2,ou=people,dc=example,dc=com',
      ]
    }
  );
    
Delete complete attributes from the entry.

  $mesg = $ldap->modify( $dn,
    delete => ['member','description'] # Delete attributes
  );
    
Delete individual values from an attribute. "VALUE" should be a string if only a single value is being deleted from the attribute, or a reference to an array of strings if multiple values are being deleted.

If "VALUE" is a reference to an empty array or all existing values of the attribute are being deleted, then the attribute will be deleted from the entry.

  $mesg = $ldap->modify( $dn,
    delete => {
      description => 'List of members',
      member      => [
        'cn=member1,ou=people,dc=example,dc=com',    # Remove members
        'cn=member2,ou=people,dc=example,dc=com',
      ],
      seeAlso => [],   # Remove attribute
    }
  );
    
Replace any existing values in each given attribute with "VALUE". "VALUE" should be a string if only a single value is wanted in the attribute, or a reference to an array of strings if multiple values are wanted. A reference to an empty array will remove the entire attribute. If the attribute does not already exist in the entry, it will be created.

  $mesg = $ldap->modify( $dn,
    replace => {
      description => 'New List of members', # Change the description
      member      => [ # Replace whole list with these
        'cn=member1,ou=people,dc=example,dc=com',
        'cn=member2,ou=people,dc=example,dc=com',
      ],
      seeAlso => [],   # Remove attribute
    }
  );
    
Atomically increment the existing value in each given attribute by the provided "VALUE". The attributes need to have integer syntax, or be otherwise "incrementable". Note this will only work if the server advertises support for LDAP_FEATURE_MODIFY_INCREMENT. Use "supported_feature" in Net::LDAP::RootDSE to check this.

  $mesg = $ldap->modify( $dn,
    increment => {
      uidNumber => 1 # increment uidNumber by 1
    }
  );
    
This is an alternative to add, delete, replace and increment where the whole operation can be given in a single argument. "OP" should be add, delete, replace or increment. "VALUE" should be either a string or a reference to an array of strings, as before.

Use this form if you want to control the order in which the operations will be performed.

  $mesg = $ldap->modify( $dn,
    changes => [
      add => [
        description => 'A description',
        member      => $newMember,
      ],
      delete => [
        seeAlso => [],
      ],
      add => [
        anotherAttribute => $value,
      ],
    ]
  );
    
See "CONTROLS" below.
See "CALLBACKS" below.

Example

 $mesg = $ldap->modify( $dn, add => { sn => 'Barr' } );
 $mesg = $ldap->modify( $dn, delete => [qw(faxNumber)] );
 $mesg = $ldap->modify( $dn, delete => { 'telephoneNumber' => '911' } );
 $mesg = $ldap->modify( $dn, replace => { 'mail' => 'gbarr@pobox.com' } );
 $mesg = $ldap->modify( $dn,
                        changes => [
                            # add sn=Barr
                          add     => [ sn => 'Barr' ],
                            # delete all fax numbers
                          delete  => [ faxNumber => []],
                            # delete phone number 911
                          delete  => [ telephoneNumber => ['911']],
                            # change email address
                          replace => [ mail => 'gbarr@pobox.com']
                        ]
                      );
search ( OPTIONS )
Search the directory using a given filter. This can be used to read attributes from a single entry, from entries immediately below a particular entry, or a whole subtree of entries.

The result is an object of class Net::LDAP::Search.

base => DN
The DN that is the base object entry relative to which the search is to be performed.
By default the search is performed on the whole tree below the specified base object. This maybe changed by specifying a "scope" parameter with one of the following values:
Search only the base object.
Search the entries immediately below the base object.
Search the whole tree below (and including) the base object. This is the default.
Search the whole subtree below the base object, excluding the base object itself.

Note: children scope requires LDAPv3 subordinate feature extension.

By default aliases are dereferenced to locate the base object for the search, but not when searching subordinates of the base object. This may be changed by specifying a "deref" parameter with one of the following values:
Do not dereference aliases in searching or in locating the base object of the search.
Dereference aliases in subordinates of the base object in searching, but not in locating the base object of the search.
Dereference aliases in locating the base object of the search, but not when searching subordinates of the base object. This is the default.
Dereference aliases both in searching and in locating the base object of the search.
A sizelimit that restricts the maximum number of entries to be returned as a result of the search. A value of 0, and the default, means that no restriction is requested. Servers may enforce a maximum number of entries to return.
A timelimit that restricts the maximum time (in seconds) allowed for a search. A value of 0 (the default), means that no timelimit will be requested.
Only attribute types (no values) should be returned. Normally attribute types and values are returned.
A filter that defines the conditions an entry in the directory must meet in order for it to be returned by the search. This may be a string or a Net::LDAP::Filter object. Values inside filters may need to be escaped to avoid security problems; see Net::LDAP::Filter for a definition of the filter format, including the escaping rules.
A list of attributes to be returned for each entry that matches the search filter.

If not specified, then the server will return the attributes that are specified as accessible by default given your bind credentials.

Certain additional attributes such as "createTimestamp" and other operational attributes may also be available for the asking:

  $mesg = $ldap->search( ... ,
                         attrs => ['createTimestamp']
                       );
    

To retrieve the default attributes and additional ones, use '*'.

  $mesg = $ldap->search( ... ,
                         attrs => ['*', 'createTimestamp']
                       );
    

To retrieve no attributes (the server only returns the DNs of matching entries), use '1.1':

  $mesg = $ldap->search( ... ,
                         attrs => ['1.1']
                       );
    
See "CONTROLS" below.
See "CALLBACKS" below.
Use REGEX to denote the names of attributes that are to be considered binary in search results.

When this option is given, Net::LDAP converts all values of attributes not matching this REGEX into Perl UTF-8 strings so that the regular Perl operators (pattern matching, ...) can operate as one expects even on strings with international characters.

If this option is not given, attribute values are treated as byte strings.

The value provided here overwrites the value inherited from the constructor.

Example: raw => qr/(?i:^jpegPhoto|;binary)/

Example

 $mesg = $ldap->search(
                        base   => $base_dn,
                        scope  => 'sub',
                        filter => '(|(objectclass=rfc822mailgroup)(sn=jones))'
                      );
 Net::LDAP::LDIF->new( \*STDOUT,"w" )->write( $mesg->entries );
Calling this method will convert the existing connection to using Transport Layer Security (TLS), which provides an encrypted connection. This is only possible if the connection uses LDAPv3, and requires that the server advertises support for LDAP_EXTENSION_START_TLS. Use "supported_extension" in Net::LDAP::RootDSE to check this.
How to verify the server's certificate:
The server may provide a certificate but it will not be checked - this may mean you are be connected to the wrong server
Verify only when the server offers a certificate
The server must provide a certificate, and it must be valid.

If you set verify to optional or require, you must also set either cafile or capath. The most secure option is require.

This defines the version of the SSL/TLS protocol to use. Default is to use the value that IO::Socket::SSL uses as default.

See "SSL_version" in IO::Socket::SSL for more details.

Allow changing the server name to use in certificate hostname verification in case the target hostname does not match the LDAP server's certificate. If not given it defaults to the name of the HOST connected to.

See "SSL_verifycn_name" in IO::Socket::SSL for more details.

Specify which subset of cipher suites are permissible for this connection, using the standard OpenSSL string format. The default behavior is to keep the decision on the underlying cryptographic library.
If you want to use the client to offer a certificate to the server for SSL authentication (which is not the same as for the LDAP Bind operation) then set clientcert to the user's certificate file, and clientkey to the user's private key file. These files must be in PEM format.

If the private key is encrypted (highly recommended) then keydecrypt should be a subroutine that returns the decrypting key. For example:

 $ldap = Net::LDAP->new( 'myhost.example.com', version => 3 );
 $mesg = $ldap->start_tls(
                           verify => 'require',
                           clientcert => 'mycert.pem',
                           clientkey => 'mykey.pem',
                           keydecrypt => sub { 'secret'; },
                           capath => '/usr/local/cacerts/'
                         );
    
When verifying the server's certificate, either set capath to the pathname of the directory containing CA certificates, or set cafile to the filename containing the certificate of the CA who signed the server's certificate. These certificates must all be in PEM format.

The directory in 'capath' must contain certificates named using the hash value of the certificates' subject names. To generate these names, use OpenSSL like this in Unix:

    ln -s cacert.pem `openssl x509 -hash -noout < cacert.pem`.0
    

(assuming that the certificate of the CA is in cacert.pem.)

If capath has been configured, then it will also be searched for certificate revocation lists (CRLs) when verifying the server's certificate. The CRLs' names must follow the form hash.rnum where hash is the hash over the issuer's DN and num is a number starting with 0.

See "SSL_check_crl" in IO::Socket::SSL for further information.

The unbind method does not take any parameters and will unbind you from the server. Some servers may allow you to re-bind or perform other operations after unbinding. If you wish to switch to another set of credentials while continuing to use the same connection, re-binding with another DN and password, without unbind-ing, will generally work.

Example

 $mesg = $ldap->unbind;
    
Convenience alias for "unbind()", named after the clean-up method of Net::LDAP::LDIF.

The following methods are for convenience, and do not return "Net::LDAP::Message" objects.

If "VALUE" is given the async mode will be set. The previous value will be returned. The value is true if LDAP operations are being performed asynchronously.
Returns an X509_Certificate object containing the server's certificate. See the IO::Socket::SSL documentation for information about this class.

For example, to get the subject name (in a peculiar OpenSSL-specific format, different from RFC 1779 and RFC 4514) from the server's certificate, do this:

    print "Subject DN: " . $ldaps->certificate->subject_name . "\n";
    
Returns the cipher mode being used by the connection, in the string format used by OpenSSL.
If "VALUE" is given the debug bit-value will be set. The previous value will be returned. Debug output will be sent to "STDERR". The bits of this value are:

 1   Show outgoing packets (using asn_hexdump).
 2   Show incoming packets (using asn_hexdump).
 4   Show outgoing packets (using asn_dump).
 8   Show incoming packets (using asn_dump).
    

The default value is 0.

Disconnect from the server
The root_dse method retrieves cached information from the server's rootDSE.
A reference to a list of attributes to be returned. If not specified, then the following attributes will be requested

  subschemaSubentry
  namingContexts
  altServer
  supportedExtension
  supportedFeatures
  supportedControl
  supportedSASLMechanisms
  supportedLDAPVersion
    

The result is an object of class Net::LDAP::RootDSE.

Example

 my $root = $ldap->root_dse;
 # get naming Context
 $root->get_value( 'namingContexts', asref => 1 );
 # get supported LDAP versions
 $root->supported_version;

As the root DSE may change in certain circumstances - for instance when you change the connection using start_tls - you should always use the root_dse method to return the most up-to-date copy of the root DSE.

Read schema information from the server.

The result is an object of class Net::LDAP::Schema. Read this documentation for further information about methods that can be performed with this object.

If a DN is supplied, it will become the base object entry from which the search for schema information will be conducted. If no DN is supplied the base object entry will be determined from the rootDSE entry.

Example

 my $schema = $ldap->schema;
 # get objectClasses
 @ocs = $schema->all_objectclasses;
 # Get the attributes
 @atts = $schema->all_attributes;
Returns the "Authen::SASL" object associated with the LDAP object, or "undef" if there isn't.
Returns the underlying socket object being used.

The exact object type returned depends on whether SASL layers are established. Without SASL layers the result is always an "IO::Socket" object; with SASL layers the outcome depends on the options given:

This option is only relevant if SASL layers are established.

If it it missing or if is set to a TRUE value, then the SASL layer handle is returned. Depending on the SASL library used, the object returned is not necessarily an "IO::Socket" object.

If it exists, but is set to a value evaluating to FALSE, then the base "IO::Socket" object underneath the SASL layer is returned.

Returns the host to which the connection was established. For LDAPI connections the socket path is returned.
Returns the port connected to or "undef" in case of LDAPI connections.
Returns the URI connected to.

As the value returned is that element of the constructor's HOST argument with which the connection was established this may or may not be a legal URI.

Returns the scheme of the connection. One of ldap, ldaps or ldapi.
Wait for a given "MESG" request to be completed by the server. If no "MESG" is given, then wait for all outstanding requests to be completed.

Returns an error code defined in Net::LDAP::Constant.

Process any messages that the server has sent, but do not block. If "MESG" is specified then return as soon as "MESG" has been processed.

Returns an error code defined in Net::LDAP::Constant.

Returns the version of the LDAP protocol that is being used.

CONTROLS

Many of the methods described above accept a control option. This allows the user to pass controls to the server as described in LDAPv3.

A control is a reference to a HASH and should contain the three elements below. If any of the controls are blessed then the method "to_asn" will be called which should return a reference to a HASH containing the three elements described below.

For most purposes Net::LDAP::Control objects are the easiest way to generate controls.

This element must be present and is the name of the type of control being requested.
critical is optional and should be a Boolean value, if it is not specified then it is assumed to be false.
If the control being requested requires a value then this element should hold the value for the server.

CALLBACKS

Most of the above commands accept a callback option. This option should be a reference to a subroutine. This subroutine will be called for each packet received from the server as a response to the request sent.

When the subroutine is called the first argument will be the Net::LDAP::Message object which was returned from the method.

If the request is a search then multiple packets can be received from the server. Each entry is received as a separate packet. For each of these the subroutine will be called with a Net::LDAP::Entry object as the second argument.

During a search the server may also send a list of references. When such a list is received then the subroutine will be called with a Net::LDAP::Reference object as the second argument.

LDAP ERROR CODES

Net::LDAP also exports constants for the error codes that can be received from the server, see Net::LDAP::Constant.

SEE ALSO

Net::LDAP::Constant, Net::LDAP::Control, Net::LDAP::Entry, Net::LDAP::Filter, Net::LDAP::Message, Net::LDAP::Reference, Net::LDAP::Search, Net::LDAP::RFC

The homepage for the perl-ldap modules can be found at http://ldap.perl.org/.

ACKNOWLEDGEMENTS

This document is based on a document originally written by Russell Fulton <r.fulton@auckland.ac.nz>.

Chris Ridd <chris.ridd@isode.com> for the many hours spent testing and contribution of the ldap* command line utilities.

MAILING LIST

A discussion mailing list is hosted by the Perl Foundation at <perl-ldap@perl.org> No subscription is necessary!

BUGS

We hope you do not find any, but if you do please report them to the mailing list.

If you have a patch, please send it as an attachment to the mailing list.

AUTHOR

Graham Barr <gbarr@pobox.com>

COPYRIGHT

Copyright (c) 1997-2004 Graham Barr. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

2018-09-06 perl v5.26.3