laurelin.ldap package

Module contents

Imports and defines the core of the public API

laurelin.ldap.get_attribute_type(ident)[source]

Get an instance of AttributeType associated with either a name or OID.

Parameters:ident (str) – Either the numeric OID of the desired attribute type spec or any one of its specified names
Returns:The AttributeType containing a parsed specification
Return type:AttributeType
class laurelin.ldap.AttributeType(spec)[source]

Bases: object

Parses an LDAP attribute type specification and implements supertype inheritance.

Each instantiation registers the names and OIDs specified so that the spec can be accessed using get_attribute_type().

See the laurelin.ldap.schema module source for example usages.

Parameters:

spec (str) – The LDAP specification for an Attribute Type.

Raises:

LDAPSchemaError: * if the specification is invalid * if the OID has already been defined * if one of the names has already been defined

Variables:
  • oid (str) – The OID of the attribute type
  • names (tuple(str)) – A tuple containing all possible names for the attribute type
  • supertype (str) – The specified supertype. If the spec does not define optional properties, they will pass through into the supertype.
  • equality_oid (str) – The OID of the equality matching rule
  • syntax_oid (str) – The OID of the syntax matching rule
  • syntax_length (int) – The suggested maximum length of a value
  • obsolete (bool) – The type has been flagged as obsolete. Will cause a warning from the SchemaValidator if an obsolete attribute type is used.
  • single_value (bool) – The attribute may only have one value.
  • collective (bool) – The attribute has been marked collective.
  • no_user_mod (bool) – The attribute may not be modified by users (e.g., for operational attributes). Will cause a validation failure from the SchemaValidator if a write operation is attempted on attribute types with this property set to True.
  • usage (str) – A string describing the attribute’s usage. May be one of userApplications, directoryOperation, distributedOperation, or dSAOperation.
equality

Gets the EqualityMatchingRule for this attribute type.

index(value_list, assertion_value)[source]

Finds the index of a value in a list of attribute values. Raises a ValueError if the value is not found in the list. Assumes values in value_list are already validated.

Parameters:
  • value_list (list[str]) – The list of attribute values. Assumes values are already validated.
  • assertion_value (str) – The value to look for in value_list.
Returns:

The index of assertion_value in value_list.

Return type:

int

Raises:
  • ValueError – if assertion_value is not found or if value_list is empty.
  • InvalidSyntaxError – if assertion_value does not meet the syntax requirements of this attribute type
register()[source]
syntax

Gets the SyntaxRule for this attribute type.

validate(value)[source]

Validate a value according to the attribute type’s syntax rule.

Parameters:value (str) – The potential attribute value
Returns:A truthy value.
Raises:InvalidSyntaxError – if the value is invalid.
class laurelin.ldap.LDAP(server=None, base_dn=None, reuse_connection=None, connect_timeout=None, search_timeout=None, deref_aliases=None, strict_modify=None, ssl_verify=None, ssl_ca_file=None, ssl_ca_path=None, ssl_ca_data=None, fetch_result_refs=None, default_sasl_mech=None, sasl_fatal_downgrade_check=None, default_criticality=None, follow_referrals=None, validators=None, warn_empty_list=None, error_empty_list=None, ignore_empty_list=None, filter_syntax=None, built_in_extensions_only=None)[source]

Bases: laurelin.ldap.extensible.ldap_extensions.LDAPExtensions

Provides the connection to the LDAP DB. All constructor parameters have a matching global default as a class property on LDAP

Parameters:
  • server (str or LDAPSocket) – URI string to connect to or an LDAPSocket to reuse
  • base_dn (str) – The DN of the base object
  • reuse_connection (bool) – Allows the socket connection to be reused and reuse an existing socket if possible.
  • connect_timeout (int) – Number of seconds to wait for connection to be accepted.
  • search_timeout (int) – Number of seconds to wait for a search to complete. Partial results will be returned when the timeout is reached. Can be overridden on a per-search basis by setting the search_timeout keyword on LDAP.search().
  • deref_aliases (DerefAliases) – One of the DerefAliases constants. Instructs the server how to handle alias objects in search results. Can be overridden on a per-search basis by setting the deref_aliases keyword on LDAP.search().
  • strict_modify (bool) – Use the strict modify strategy. If set to True, guarantees that another search will not take place before a modify operation. May potentially produce more server errors.
  • ssl_verify (bool) – Validate the certificate and hostname on an SSL/TLS connection
  • ssl_ca_file (str) – Path to PEM-formatted concatenated CA certficates file
  • ssl_ca_path (str) – Path to directory with CA certs under hashed file names. See https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_load_verify_locations.html for more information about the format of this directory.
  • ssl_ca_data (str or bytes) – An ASCII string of one or more PEM-encoded certs or a bytes object containing DER-encoded certificates.
  • fetch_result_refs (bool) – Fetch searchResultRef responses in search results. Can be overridden on a per-search basis by setting the fetch_result_refs keyword on LDAP.search().
  • default_sasl_mech (str) – Name of the default SASL mechanism. Bind will fail if the server does not support the mechanism. (Examples: DIGEST-MD5, GSSAPI)
  • sasl_fatal_downgrade_check (bool) – Set to False to make potential downgrade attack check non-fatal.
  • default_criticality (bool) – Set to True to make controls critical by default, set to False to make non-critical
  • follow_referrals (bool) – Automatically follow referral results
  • validators (list[Validator]) – A list of Validator instances to apply to this connection.
  • warn_empty_list (bool) – Default False. Set to True to emit a warning when an empty value list is passed to LDAP.modify(), LDAP.replace_attrs(), or LDAP.delete_attrs() or their LDAPObject counterparts.
  • error_empty_list (bool) – Default False. Set to True to raise an exception when an empty value list is passed to LDAP.modify(), LDAP.replace_attrs(), or LDAP.delete_attrs() or their LDAPObject counterparts.
  • ignore_empty_list (bool) – Default False. Set to True to ignore empty value lists passed to LDAP.modify(), LDAP.replace_attrs(), or LDAP.delete_attrs() or their LDAPObject counterparts. This will be default True in a future release.
  • filter_syntax (FilterSyntax) – The default search filter syntax selection. Must be one of the FilterSyntax constants. Can be overridden on a per-search basis by setting the filter_syntax keyword on LDAP.search(). Defaults to FilterSyntax.STANDARD for RFC4515-compliant filter string syntax.
  • built_in_extensions_only (bool) – Set to True to raise an error when attempting to use a 3rd-party extension

The class can be used as a context manager, which will automatically unbind and close the connection when the context manager exits.

Example:

with LDAP() as ldap:
    raise Exception()
# ldap is closed and unbound

with LDAP() as ldap:
    print('hello')
# ldap is closed and unbound
DEFAULT_BASE_DN = None
DEFAULT_BUILT_IN_EXTENSIONS_ONLY = False
DEFAULT_CONNECT_TIMEOUT = 5
DEFAULT_CRITICALITY = False
DEFAULT_DEREF_ALIASES = DerefAliases.ALWAYS
DEFAULT_ERROR_EMPTY_LIST = False
DEFAULT_FETCH_RESULT_REFS = True
DEFAULT_FILTER = '(objectClass=*)'
DEFAULT_FILTER_SYNTAX = FilterSyntax.UNIFIED
DEFAULT_FOLLOW_REFERRALS = True
DEFAULT_IGNORE_EMPTY_LIST = True
DEFAULT_REUSE_CONNECTION = True
DEFAULT_SASL_FATAL_DOWNGRADE_CHECK = True
DEFAULT_SASL_MECH = None
DEFAULT_SEARCH_TIMEOUT = 0
DEFAULT_SERVER = 'ldap://localhost'
DEFAULT_SSL_CA_DATA = None
DEFAULT_SSL_CA_FILE = None
DEFAULT_SSL_CA_PATH = None
DEFAULT_SSL_VERIFY = True
DEFAULT_STRICT_MODIFY = False
DEFAULT_VALIDATORS = None
DEFAULT_WARN_EMPTY_LIST = False
DELETE_ALL = <delete all values>

Use with modify replace/delete in place of an attribute list to delete all values for the attribute

LOG_FORMAT = '[%(asctime)s] %(name)s %(levelname)s : %(message)s'
NO_ATTRS = '1.1'
OID_OBJ_CLASS_ATTR = '1.3.6.1.4.1.4203.1.5.2'
OID_STARTTLS = '1.3.6.1.4.1.1466.20037'
OID_WHOAMI = '1.3.6.1.4.1.4203.1.11.3'
add(dn, attrs_dict, **kwds)[source]

Add new object and return corresponding LDAPObject on success.

Parameters:
  • dn (str) – The new object’s DN
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The new attributes for the object
Returns:

The new object

Return type:

LDAPObject

Raises:

Additional keyword arguments are handled as Controls and then passed through into LDAP.obj().

add_attrs(dn, attrs_dict, current=None, **ctrl_kwds)[source]

Add new attribute values to existing object.

Parameters:
  • dn (str) – The DN of the object to modify
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The new attributes to add to the object
  • current (LDAPObject or None) – The current known state of the object. Used for ensuring we don’t send duplicate attributes to the server and for validation.
Returns:

A response object

Return type:

LDAPResponse

Additional keyword arguments are handled as Controls.

static add_extension(modname)

Import an extension and prepare it for binding under its internally-defined name to LDAP and/or LDAPObject depending which extension classes are defined. This is only needed for extensions not yet patched into AVAILABLE_EXTENSIONS.

Parameters:modname (str) – The string module name containing an extension, can be any importable module, e.g. “laurelin.extensions.netgroups”
Return type:None
add_if_not_exists(dn, attrs_dict)[source]

Add object if it doesn’t exist

  • Gets and returns the object at DN if it exists, otherwise create the object using the attrs dictionary
  • Always returns an LDAPObject corresponding to the final state of the DB
Parameters:
  • dn (str) – The object DN
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The attributes to use if adding the object
Returns:

The new or existing object

Return type:

LDAPObject

add_or_mod_add_if_exists(dn, attrs_dict)[source]

Add object if it doesn’t exist, otherwise add_attrs

  • If the object at DN exists, perform an add modification using the attrs dictionary. Otherwise, create the object using the attrs dictionary.
  • This ensures that, for the attributes mentioned in attrs, AT LEAST those values will exist on the given DN, regardless of prior state of the DB.
  • Always returns an LDAPObject corresponding to the final state of the DB
Parameters:
  • dn (str) – The object DN
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The objects minimum attributes
Returns:

The new or modified object

Return type:

LDAPObject

add_or_mod_replace_if_exists(dn, attrs_dict)[source]

Add object if it doesn’t exist, otherwise replace_attrs

  • If the object at DN exists, perform a replace modification using the attrs dictionary Otherwise, create the object using the attrs dictionary
  • This ensures that, for the attributes mentioned in attrs, ONLY those values will exist on the given DN regardless of prior state of the DB.
  • Always returns an LDAPObject corresponding to the final state of the DB
Parameters:
  • dn (str) – The object DN
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The objects new required attributes
Returns:

The new or modified object

Return type:

LDAPObject

close(force=False)

Send an unbind request and close the socket.

Parameters:force (bool) – Unbind and close the socket even if other objects still hold a reference to it.
Raises:ConnectionUnbound – if the connection has already been unbound
compare(dn, attr, value, **ctrl_kwds)[source]

Ask the server if a particular DN has a matching attribute value. The comparison will take place following the schema-defined matching rules and syntax rules.

Parameters:
  • dn (str) – The DN of the object
  • attr (str) – The attribute name
  • value (str) – The assertion value
Returns:

A response object, bool() evaluating to the result of the comparison

Return type:

CompareResponse

Raises:
  • ConnectionUnbound – if the connection has been unbound
  • LDAPError – if we got a result other than compareTrue or compareFalse

Additional keyword arguments are handled as Controls.

static default_warnings()[source]

Always take the default action for warnings

delete(dn, **ctrl_kwds)[source]

Delete an object.

Parameters:dn (str) – The DN of the object to delete
Returns:A response object
Return type:LDAPResponse
Raises:ConnectionUnbound – if the connection has been unbound

Additional keyword arguments are handled as Controls.

delete_attrs(dn, attrs_dict, current=None, **ctrl_kwds)[source]

Delete specific attribute values from attrs_dict.

Specifying a 0-length entry will delete all values.

Parameters:
  • dn (str) – The DN of the object to modify
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The attributes to remove from the object. Specify an empty list for a value to delete all values.
  • current (LDAPObject or None) – The current known state of the object. Used to ensure we don’t request that the server delete attribute values that don’t exist and for validation.
Returns:

A response object

Return type:

LDAPResponse

Additional keyword arguments are handled as Controls.

disable_validation(disabled_validators=None)[source]

Returns a context manager which temporarily disables validation. If any server errors are generated, they will still be propagated.

Example:

from laurelin.ldap import LDAP
from laurelin.ldap.exceptions import LDAPValidationError
from laurelin.ldap.schema import SchemaValidator

with LDAP(validators=[SchemaValidator()]) as ldap:
    # make validated queries
    ldap.base.add_child('cn=foo', {<valid object>})

    try:
        ldap.base.add_child('cn=bar', {<invalid object>})
    except LDAPValidationError:
        pass

    with ldap.disable_validation(['SchemaValidator']):
        # make queries without validation
        ldap.base.add_child('cn=bar', {<invalid object>})
        # NOTE: if the object is actually invalid, a server error may still occur

    # carry on with validation restored...
Parameters:disabled_validators – Optional, a list of string class names or Validator classes to disable. By default all validators will be disabled.
Returns:A context manager which temporarily disables validation
Return type:DisabledValidationContext
static disable_warnings()[source]

Prevent all LDAP warnings from being shown - default action for others

static enable_logging(level=10)[source]

Enable logging output to stderr

exists(dn)[source]

Simply check if a DN exists.

Parameters:dn (str) – The DN to check
Returns:True if the object exists, False if not
Return type:bool
get(dn, attrs=None, **kwds)[source]

Get a specific object by DN.

Performs a search with Scope.BASE and ensures we get exactly one result.

Parameters:
  • dn (str) – The DN of the object to query
  • attrs (list[str] or None) – Optional. A list of attribute names to get, defaults to all user attributes
Returns:

The LDAP object

Return type:

LDAPObject

Raises:

Additional keyword arguments are passed through into LDAP.search().

get_sasl_mechs()[source]

Query root DSE for supported SASL mechanisms.

Returns:The list of server-supported mechanism names.
Return type:list[str]
static log_warnings()[source]

Log all LDAP warnings rather than showing them - default action for others

mod_dn(dn, new_rdn, clean_attr=True, new_parent=None, **ctrl_kwds)[source]

Change the DN and possibly the location of an object in the tree. Exposes all options of the protocol-level rfc4511.ModifyDNRequest

Parameters:
  • dn (str) – The current DN of the object
  • new_rdn (str) – The new RDN of the object, e.g. cn=foo
  • clean_attr (bool) – Remove the old RDN attribute from the object when changing
  • new_parent (str or None) – The DN of the new parent object, or None to leave the location unchanged
Returns:

A response object

Return type:

LDAPResponse

Raises:

ConnectionUnbound – if the connection has been unbound

Additional keyword arguments are handled as Controls.

modify(dn, modlist, current=None, **ctrl_kwds)[source]

Perform a series of modify operations on an object atomically

Parameters:
  • dn (str) – The DN of the object to modify
  • modlist (list[Mod]) – A list of Mod instances, e.g. [Mod(Mod.ADD, ‘someAttr’, [‘value1’, ‘value2’])]
  • current (LDAPObject or None) – The current known state of the object for use in validation
Returns:

A response object

Return type:

LDAPResponse

Raises:

Additional keyword arguments are handled as Controls.

move(dn, new_dn, clean_attr=True, **ctrl_kwds)[source]

Specify a new absolute DN for an object.

Parameters:
  • dn (str) – The current DN of the object
  • new_dn (str) – The new absolute DN of the object, e.g. cn=foo,dc=example,dc=org
  • clean_attr (bool) – Remove the old RDN attribute from the object when changing
Returns:

A response object

Return type:

LDAPResponse

Additional keyword arguments are handled as Controls.

obj(dn, attrs_dict=None, tag=None, **kwds)[source]

Factory for LDAPObjects bound to this connection.

Note that this does not query the server. Use LDAP.get() to query the server for a particular DN.

Parameters:
  • dn (str) – The DN of the object.
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict or None) – Optional. The object’s attributes and values.
  • tag (str or None) – Optional. The tag for this object. Tagged objects can be retrieved with LDAP.tag().
Returns:

The new object bound to this connection.

Return type:

LDAPObject

Raises:

TagError – if the tag parameter is already defined

Additional keywords are passed through into the LDAPObject constructor.

process_ldif(ldif_str)[source]

Process a basic LDIF

TODO: full RFC 2849 implementation. Missing:

  • attribute options
Parameters:

ldif_str (str) – An RFC 2849 complying LDIF string

Returns:

A list with elements corresponding to the return of each described operation

Return type:

list[LDAPResponse or LDAPObject]

Raises:
  • ValueError – if the LDIF is malformed
  • LDAPError – if an unimplemented feature is used
  • LDAPSupportError – if a version other than 1 is specified or a critical control is undefined
recheck_sasl_mechs()[source]

Query the root DSE again after performing a SASL bind to check for a downgrade attack.

Raises:LDAPError – If the downgrade attack check fails and sasl_fatal_downgrade_check has not been set to False.
refresh_root_dse()[source]

Update the local copy of the root DSE, containing metadata about the directory server. The root DSE is an LDAPObject stored on the root_dse attribute.

rename(dn, new_rdn, clean_attr=True, **ctrl_kwds)[source]

Specify a new RDN for an object without changing its location in the tree.

Parameters:
  • dn (str) – The current DN of the object
  • new_rdn (str) – The new RDN of the object, e.g. cn=foo
  • clean_attr (bool) – Remove the old RDN attribute from the object when changing
Returns:

A response object

Return type:

LDAPResponse

Additional keyword arguments are handled as Controls.

replace_attrs(dn, attrs_dict, current=None, **ctrl_kwds)[source]

Replace all values on given attributes with the passed values

  • Attributes not mentioned in attrsDict are not touched
  • Attributes will be created if they do not exist
  • Specifying a 0-length entry will delete all values for that attribute
Parameters:
  • dn (str) – The DN of the object to modify
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The new attributes to set on the object
  • current (LDAPObject or None) – The current known state of the object for use in validation
Returns:

A response object

Return type:

LDAPResponse

Additional keyword arguments are handled as Controls.

sasl_bind(mech=None, **props)[source]

Perform a SASL bind operation.

Keywords are first taken as Controls. Required keyword args are dependent on the mechanism chosen.

Parameters:

mech (str) – The SASL mechanism name to use or None to negotiate best mutually supported mechanism.

Returns:

A response object

Return type:

LDAPResponse

Raises:
search(base_dn, scope=Scope.SUB, filter=None, attrs=None, search_timeout=None, limit=0, deref_aliases=None, attrs_only=False, fetch_result_refs=None, follow_referrals=None, filter_syntax=None, **kwds)[source]

Sends search and return an iterator over results.

Parameters:
  • base_dn (str) – The DN of the base object of the search
  • scope (Scope) – One of the Scope constants, default Scope.SUB. Controls the maximum depth of the search.
  • filter (str) – A filter string. Objects must match the filter to be included in results. Default includes all objects and can be overridden globally by defining LDAP.DEFAULT_FILTER.
  • attrs (list[str]) – A list of attribute names to include for each object. Default includes all user attributes. Use [‘*’, ‘+’] to get all user and all operational attributes.
  • search_timeout (int) – The number of seconds the server should spend performing the search. Partial results will be returned if the server times out. The default can be set per connection by passing the search_timeout keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_SEARCH_TIMEOUT.
  • limit (int) – The maximum number of objects to return.
  • deref_aliases (DerefAliases) – One of the DerefAliases constants. This instructs the server what to do when it encounters an alias object. The default can be set per connection by passing the deref_aliases keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_DEREF_ALIASES.
  • attrs_only (bool) – Default False. Set to True to only obtain attribute names and not any attribute values.
  • fetch_result_refs (bool) – When the server returns a result which is a reference to an object on another server, automatically attempt to fetch the remote object and include it in the iterated results. The default can be set per connection by passing the fetch_result_refs keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_FETCH_RESULT_REFS.
  • follow_referrals (bool) – When the server knows that the base object is present on another server, follow the referral and perform the search on the other server. The default can be set per connection by passing the follow_referrals keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_FOLLOW_REFERRALS.
  • filter_syntax (FilterSyntax) – Select which filter syntax to use to parse the filter. The default can be set per connection by passing the default_filter_syntax keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_FILTER_SYNTAX.
Returns:

An iterator over the results of the search. May yield LDAPObject or possibly SearchReferenceHandle if fetch_result_refs is False.

Additional keywords are handled as Controls first and then passed through into LDAP.obj().

This method may also be used as a context manager. If all results have not been read, the operation will automatically be abandoned when the context manager exits. You can also raise Abandon to abandon all results immediately and cleanly exit the context manager. You can also call SearchResultHandle.abandon() to abandon results.

Example:

# Dump the whole tree
with LDAP() as ldap:
    with ldap.base.search() as search:
        for result in search:
            print(result.format_ldif())
send_extended_request(oid, value=None, **kwds)[source]

Send an extended request, returns instance of ExtendedResponseHandle

This is mainly meant to be called by other built-in methods and client extensions. Requires handling of raw pyasn1 protocol objects.

Parameters:
  • oid (str) – The OID of the extension. Must be declared as supported by the server in the root DSE.
  • value (str or bytes or None) – The request value (optional)
Returns:

An iterator yielding tuples of the form (rfc4511.IntermediateResponse, rfc4511.Controls) or (rfc4511.ExtendedResponse, rfc4511.Controls).

Return type:

ExtendedResponseHandle

Raises:
  • LDAPSupportError – if the OID is not listed in the supportedExtension attribute of the root DSE
  • TypeError – if the value parameter is not a valid type

Additional keyword arguments are handled as Controls and then passed through into the ExtendedResponseHandle constructor.

simple_bind(username='', password='', **ctrl_kwds)[source]

Performs a simple bind operation

Leave arguments as their default (empty strings) to attempt an anonymous simple bind

Additional keywords are used as Controls.

Parameters:
  • username (str) – Bind DN/username or empty string for anonymous
  • password (str) – Password to bind with or empty string for anonymous
Returns:

A response object

Return type:

LDAPResponse

Raises:
start_tls(verify=None, ca_file=None, ca_path=None, ca_data=None)[source]

Perform the StartTLS extended operation. This will instruct the server to begin encrypting this socket connection with TLS/SSL.

Parameters:
  • verify (bool) – Set to False to disable verification of the remote certificate. You can set the default per-connection by passing the ssl_verify keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_SSL_VERIFY.
  • ca_file (str) – Path to PEM-formatted concatenated CA certficates file. You can set the default per-connection by passing the ssl_ca_file keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_SSL_CA_FILE.
  • ca_path (str) – Path to directory with CA certs under hashed file names. See https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_load_verify_locations.html for more information about the format of this directory. You can set the default per-connection by passing the ssl_ca_path keyword to the LDAP constructor, or set the global default by defining LDAP.DEFAULT_SSL_CA_PATH.
  • ca_data (str or bytes) – An ASCII string of one or more PEM-encoded certs or a bytes object containing DER-encoded certificates. You can set the default per-connection by passing the ssl_ca_data keyword to the LDAP constructor, or set the global default by defining LDAP_DEFAULT_SSL_CA_DATA.
Return type:

None

tag(tag)[source]

Get a tagged object.

Parameters:tag (str) – The tag name to retrieve
Returns:The object created with the given tag
Return type:LDAPObject
Raises:TagError – if the given tag is not defined
unbind(force=False)[source]

Send an unbind request and close the socket.

Parameters:force (bool) – Unbind and close the socket even if other objects still hold a reference to it.
Raises:ConnectionUnbound – if the connection has already been unbound
validate_modify(dn, modlist, current=None)[source]

Run all configured validators for the given modify operation

Parameters:
  • dn (str) – The DN of the object being modified
  • modlist (list[Mod]) – The sequence of changes to be performed
  • current (LDAPObject) – The current known state of the object
Return type:

None

Raises:

LDAPValidationError – if any validator fails the operation

validate_object(obj, write=True)[source]

Run all configured validators for the given object.

Parameters:
  • obj (LDAPObject) – The object to validate
  • write (bool) – True if this is for a write operation (e.g. an add)
Return type:

None

Raises:

LDAPValidationError – if any validator fails the object

who_am_i(**ctrl_kwds)[source]

Perform the “Who Am I?” extended operation. This will confirm the identity that the connection is bound to.

Returns:A string describing the bound identity. One common form is “dn:cn=foo,dc=example,dc=org” but this will vary by server configuration and bind type/parameters.
Return type:str

Additional keyword arguments are handled as Controls.

class laurelin.ldap.LDAPURI(uri)[source]

Bases: object

Represents a parsed LDAP URI as specified in RFC4516

Supported extensions:

  • “StartTLS”
Variables:
  • scheme (str) – urlparse standard
  • netloc (str) – urlparse standard
  • host_uri (str) – scheme://netloc for use with LDAPSocket
  • dn (str) – Distinguished name
  • attrs (list[str]) – list
  • scope (Scope) – one of the Scope constants
  • filter (str) – The filter string
  • starttls (bool) – True if StartTLS was requested
DEFAULT_ATTRS = ['*']
DEFAULT_FILTER = '(objectClass=*)'
DEFAULT_SCOPE = Scope.BASE
DEFAULT_STARTTLS = False
search(**kwds)[source]

Perform the search operation described by the parsed URI

First opens a new connection with connection reuse disabled, then performs the search, and unbinds the connection. Server must allow anonymous read.

Additional keyword arguments are passed through into LDAP.search().

class laurelin.ldap.Scope[source]

Bases: object

Scope constants. These instruct the server how far to take a search, relative to the base object

BASE = Scope.BASE

Only search the base object

ONE = Scope.ONE

Search the base object and its immediate children

ONELEVEL = Scope.ONE
SUB = Scope.SUB

Search the base object and all of its dscendants

SUBTREE = Scope.SUB
static constant(c)[source]

translate constants to RFC4516 URL scope string

static string(str)[source]

translate RFC4516 URL scope strings to constant

class laurelin.ldap.DerefAliases[source]

Bases: object

DerefAliases constants. These instruct the server when to automatically resolve an alias object, rather than return the alias object itself

ALWAYS = DerefAliases.ALWAYS

dereferences both the search base object and results

BASE = DerefAliases.BASE

dereferences the search base object, but not search results

NEVER = DerefAliases.NEVER

always return the alias object

SEARCH = DerefAliases.SEARCH

dereferences search results, but not the base object itself

class laurelin.ldap.FilterSyntax[source]

Bases: object

Filter syntax selection constants. Used to determine which filter syntax to use when parsing a search filter.

SIMPLE = FilterSyntax.SIMPLE
STANDARD = FilterSyntax.STANDARD
UNIFIED = FilterSyntax.UNIFIED
static string(str)[source]

Convert filter syntax string to constant

class laurelin.ldap.Control[source]

Bases: object

Request controls are exposed by allowing an additional keyword argument on a set of methods. The prepare() method takes the value passed in as a keyword argument and returns an rfc4511.Control.

Response controls are returned by setting an additional attribute on whichever object is returned by the called method. The raw response controlValue is passed to the handle() method, and any appropriate value may be returned.

Leave the RESPONSE_OID and response_attr attributes as a False value if there is no response control specified.

REQUEST_OID = ''

Request OID of the control

RESPONSE_OID = ''

Response OID of the control (may be equal to REQUEST_OID; may be left empty)

handle(ctrl_value)[source]

Accepts raw response ctrl_value and may return any useful value.

There is no need to call this base function when overriding.

Parameters:ctrl_value (str) – The string response control value received from the server.
Returns:The string ctrl_value unchanged by default. May be overridden to return any relevant value/type/structure.
keyword = ''

keyword argument name

method = ()

name(s) of the method which this control is used with

prepare(ctrl_value, criticality)[source]

Accepts string controlValue and returns an rfc4511.Control instance

When overriding this function, you must always call and return this base function.

Parameters:
  • ctrl_value (str or bytes) – The string request control value to send to the server
  • criticality (bool) – True if the control has criticality. This is indicated by wrapping the keyword argument in critical or optional, and by the default_criticality keyword passed to the LDAP constructor, and global default LDAP.DEFAULT_CRITICALITY.
Returns:

The protocol-level control object ready for transmission to the server

Return type:

rfc4511.Control

classmethod register()[source]
response_attr = ''

Name of the attribute where return of handle() will be stored

class laurelin.ldap.critical(value)[source]

Bases: object

used to mark controls with criticality

class laurelin.ldap.optional(value)[source]

Bases: object

used to mark controls as not having criticality

exception laurelin.ldap.LDAPError[source]

Bases: Exception

Base class for all exceptions raised by laurelin

exception laurelin.ldap.NoSearchResults[source]

Bases: laurelin.ldap.exceptions.UnexpectedSearchResults

Got no search results when one or more was required

exception laurelin.ldap.Abandon[source]

Bases: Exception

Can be raised to cleanly exit a context manager and abandon unread results

laurelin.ldap.add_extension(modname)[source]

Import an extension and prepare it for binding under its internally-defined name to LDAP and/or LDAPObject depending which extension classes are defined. This is only needed for extensions not yet patched into AVAILABLE_EXTENSIONS.

Parameters:modname (str) – The string module name containing an extension, can be any importable module, e.g. “laurelin.extensions.netgroups”
Return type:None
class laurelin.ldap.BaseLaurelinExtension(modname=None)[source]

Bases: laurelin.ldap.extensible.registration.LaurelinRegistrar, laurelin.ldap.extensible.registration.LaurelinTransiter

Base class for basic extension class. Can house schema and controls definitions.

INSTANCE = None
NAME = '__undefined__'
class laurelin.ldap.BaseLaurelinSchema[source]

Bases: laurelin.ldap.extensible.registration.LaurelinTransiter

Optional base class for a class defining schema elements - only subclassing LaurelinTransiter is required

class laurelin.ldap.BaseLaurelinControls[source]

Bases: laurelin.ldap.extensible.registration.LaurelinTransiter

Optional base class for a class defining controls - only subclassing LaurelinTransiter is required

class laurelin.ldap.BaseLaurelinLDAPExtension(parent)[source]

Bases: object

Base class for extensions to the LDAP class

class laurelin.ldap.BaseLaurelinLDAPObjectExtension(parent)[source]

Bases: object

Base class for extensions to the LDAPObject class

class laurelin.ldap.LaurelinTransiter[source]

Bases: object

Base class for classes in extensions defining schema elements or controls

class laurelin.ldap.LaurelinRegistrar(modname=None)[source]

Bases: object

The require() method on this class registers all schema and controls in a module.

If this class is subclassed in an extension module (such as with LaurelinExtension), there is no need to pass an argument to the constructor. However, for extensions with many schema elements or controls, it may be desirable to break up these objects into multiple submodules that are imported on end-user request.

In such a setup, an instance of LaurelinRegistrar would need to be created and exposed to the end-user for each submodule so that they can call .require() on it. This constructor would need to be passed __name__.

Note that if this is applied to a package, require() will function on all imported submodules of the package.

require()[source]

Register schema elements and controls defined in any LaurelinTransiter subclass in the same module as the calling class. If the calling class is defined in an __init__.py, also register schema/controls for submodules that have been imported.

laurelin.ldap.escape(text)

Escape special characters

class laurelin.ldap.LDAPObject(dn, attrs_dict=None, ldap_conn=None, relative_search_scope=Scope.SUB, rdn_attr=None)[source]

Bases: laurelin.ldap.attrsdict.AttrsDict, laurelin.ldap.extensible.ldapobject_extensions.LDAPObjectExtensions

Represents a single object with optional server affinity.

Many methods will raise an exception if used without a server connection. To instantiate an LDAPObject bound to a server connection, use LDAP.obj().

Attributes and values are stored using the mapping interface inherited from AttrsDict, where dict keys are case-insensitive attribute names, and dict values are a list of attribute values.

Value lists are automatically wrapped in AttrValueList. This allows the use of any schema-defined matching and syntax rules for the attribute type in list operations.

Parameters:
  • dn (str) – The DN of the object
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict or None) – The object’s attributes
  • ldap_conn (LDAP or None) – The optional LDAP connection to use
  • relative_search_scope (Scope) – One of the Scope constants, this is the default scope used when using this object’s LDAPObject.search() method. New objects created below this one will inherit this attribute by default. This attribute also defines the behavior of LDAPObject.find().
  • rdn_attr (str or None) – The default attribute name used in RDN’s for descendents of this object. If specified, this allows you to only specify the value for methods that have an rdn argument. You can always specify a full attr=value for rdn arguments as well to override this behavior. New objects created below this one will inherit this attribute by default.
add_attrs(attrs_dict, **ctrl_kwds)[source]

Add new attribute values to this object.

Parameters:attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The new attributes to add to the object
Return type:None

Additional keywords are passed through into LDAPObject.modify().

add_child(rdn, attrs_dict, **kwds)[source]

Create a new object below this one.

Parameters:
  • rdn (str) – The RDN, or RDN value if rdn_attr is defined for this object
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict or None) – The attributes for the object
Returns:

The new object

Return type:

LDAPObject

Additional keyword arguments are passed through into LDAP.add()

compare(attr, value)[source]

Ask the server if this object has a matching attribute value. The comparison will take place following the schema-defined matching rules and syntax rules.

Parameters:
  • attr (str) – The attribute name
  • value (str) – The assertion value
Returns:

A response object, bool() evaluating to the result of the comparison

Return type:

CompareResponse

Raises:

RuntimeError – if this object is not bound to an LDAP connection

delete(**ctrl_kwds)[source]

Delete the entire object from the server, and render this instance useless.

Additional keywords are passed through into LDAP.delete().

Return type:None
Raises:RuntimeError – if this object is not bound to an LDAP connection
delete_attrs(attrs_dict, **ctrl_kwds)[source]

Delete specifc attribute values given in attrs_dict. Specifying a zero-length list for any attribute will delete all values for that attribute.

Parameters:attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The attributes to delete from the object
Return type:None

Additional keywords are passed through into LDAPObject.modify().

delete_child(rdn, **ctrl_kwds)[source]

Delete a child object below this one.

Parameters:rdn (str) – The RDN, or RDN value if rdn_attr is defined for this object
Returns:The LDAPResponse from the delete operation
Return type:LDAPResponse

Additional keyword arguments are treated as controls.

find(rdn, attrs=None, **kwds)[source]

Obtain a single object below this one with the most efficient means possible.

The strategy used is based on the relative_search_scope property of this object.

  • If it is Scope.BASE, this method will always raise an LDAPError.
  • If it is Scope.ONE, then the absolute DN for the child object will be constructed, and a Scope.BASE search will be performed to get the object.
  • If it is Scope.SUB, then a subtree search will be performed below this object, using the RDN as a search filter.

Additional keywords are passed through into LDAPObject.search().

Parameters:
  • rdn (str) – The RDN, or RDN value if rdn_attr is defined for this object
  • attrs (list[str]) – Optional. The list of attribute names to obtain.
Returns:

The LDAP object

Return type:

LDAPObject

Raises:
format_ldif()[source]

Format the object as an LDIF string.

Returns:The object encoded as an LDIF.
Return type:str
get_child(rdn, attrs=None, **kwds)[source]

Query the server for a child object.

Parameters:
  • rdn (str) – The RDN, or RDN value if rdn_attr is defined for this object
  • attrs (list[str] or None) – The list of attributes to query
Returns:

The object populated with data from the server

Return type:

LDAPObject

Raises:

RuntimeError – if this object is not bound to an LDAP connection

Additional keywords are passed through into LDAP.search() and LDAPObject

has_object_class(object_class)[source]

A convenience method which checks if this object has a particular objectClass. May query the server for the objectClass attribute if it is not yet known.

Parameters:object_class – The objectClass to check for.
Returns:True if the objectClass is present, False otherwise
Return type:bool
mod_dn(new_rdn, clean_attr=True, new_parent=None, **ctrl_kwds)[source]

Change the object DN, and possibly its location in the tree.

Parameters:
  • new_rdn (str) – The new RDN of the object
  • clean_attr (bool) – Optional, default True. Remove the attribute associated with the RDN when changing it.
  • new_parent (str) – Optional. The absolute DN of the object’s new parent.
Return type:

None

Raises:

RuntimeError – if this object is not bound to an LDAP connection

Additional keywords are passed through into LDAP.mod_dn().

mod_transaction()[source]

Begin a modify transaction on this object. Important: This IS NOT an RFC 5805 transaction.

Return type:ModTransactionObject
modify(modlist, **ctrl_kwds)[source]

Perform a series of modify operations on this object atomically.

Parameters:modlist (list[Mod]) – A list of Mod instances, e.g. [Mod(Mod.ADD, ‘someAttr’, [‘value1’, ‘value2’])]
Return type:None
Raises:RuntimeError – if this object is not bound to an LDAP connection

Additional keywords are passed through into LDAP.modify().

move(new_dn, clean_attr=True, **ctrl_kwds)[source]

Specify the complete new absolute DN for this object.

Parameters:
  • new_dn (str) – The new absolute DN for the object
  • clean_attr (bool) – Optional, default True. Remove the attribute associated with the RDN when changing it.
Return type:

None

Additional keywords are passed through into LDAPObject.mod_dn().

obj(rdn, attrs_dict=None, tag=None, **kwds)[source]

Create a new object below this one.

Parameters:
  • rdn (str) – The RDN, or RDN value if rdn_attr is defined for this object
  • attrs_dict (dict(str, list[str or bytes]) or AttrsDict or None) – The attributes for the object
  • tag (str or None) – Optional tag for the object
Returns:

The new object

Return type:

LDAPObject

Raises:

LDAPError – if a tag is specified but this object is not bound to an LDAP connection

Additional keywords are passed through into LDAP.obj(). or the LDAPObject constructor.

rdn(rdn)[source]

Return an absolute DN from an RDN or RDN value

Parameters:rdn (str) – The RDN, or RDN value if rdn_attr is defined for this object
Returns:The absolute DN
Return type:str
refresh(attrs=None)[source]

Query the server to update the attributes on this object.

Parameters:attrs (list[str]) – Optional. A list of attribute names to query. If not specified, will query the server for all user attributes.
Return type:None
Raises:RuntimeError – if this object is not bound to an LDAP connection
refresh_all()[source]

Query the server to update all user and operational attributes on this object.

Return type:None
Raises:RuntimeError – if this object is not bound to an LDAP connection
refresh_missing(attrs)[source]

Potentially query the server for any listed attributes that are not yet defined on this object. If no listed attributes aren’t defined, the query will not be performed. If a subset of the list is undefined, only those attributes will be queried.

Parameters:attrs (list[str]) – A list of attribute names to check, and possibly query for.
Return type:None
rename(new_rdn, clean_attr=True, **ctrl_kwds)[source]

Change the object’s RDN without changing it’s location in the tree.

Parameters:
  • new_rdn (str) – The new RDN of the object
  • clean_attr (bool) – Optional, default True. Remove the attribute associated with the RDN when changing it.
Return type:

None

Additional keywords are passed through into LDAPObject.mod_dn().

replace_attrs(attrs_dict, **ctrl_kwds)[source]

Replace all values on the given attributes with the passed values.

Parameters:attrs_dict (dict(str, list[str or bytes]) or AttrsDict) – The new attributes to set on the object
Return type:None

Additional keywords are passed through into LDAPObject.modify().

search(filter=None, attrs=None, **kwds)[source]

Perform a search below this object.

Parameters:
  • filter (str) – Optional. The filter string to use to filter returned objects.
  • attrs (list[str]) – Optional. The list of attribute names to retrieve.
Returns:

An iterator over LDAPObject and possibly SearchReferenceHandle. See LDAP.search() for more details.

Return type:

SearchResultHandle

Additional keywords are passed through into LDAP.search().

validate()[source]

Validate the object, assuming all attributes are present locally

validate_modify(modlist)[source]

Validate a modification list.

Parameters:modlist (list[Mod]) – The list of modify operations to validate.
class laurelin.ldap.Mod(op, attr, vals)[source]

Bases: object

Describes a single modify operation

ADD = Mod.ADD
DELETE = Mod.DELETE
REPLACE = Mod.REPLACE
static op_to_string(op)[source]

Convert one of the Mod constants to a string, e.g. “ADD”, “REPLACE”, “DELETE”.

static string(op)[source]

Translte LDIF changetype strings to constant. e.g. “replace” -> Mod.REPLACE

laurelin.ldap.get_object_class(ident)[source]

Get an instance of ObjectClass associated with either a name or an OID

Parameters:ident (str) – Either the numeric OID of the desired object class spec or one of its specified names
Returns:The ObjectClass associated with the name/OID
Return type:ObjectClass
class laurelin.ldap.ObjectClass(spec)[source]

Bases: object

Parses an LDAP object class specification and implements superclass inheritance.

Each instantiation registers the names and OID specified so that they can later be access with get_object_class().

See the laurelin.ldap.schema module source for example usages.

Parameters:

spec (str) – The LDAP specification for an object class

Raises:

LDAPSchemaError

  • if the schema is syntactically invalid
  • if the OID specified has already been registered
  • if one of the names specified has already been registered

Variables:
  • oid (str) – The specified OID
  • names (tuple(str)) – All specified names
  • superclasses (list[str]) – The list of all specified superclass names/OIDs.
  • kind (str) – One of ABSTRACT, STRUCTURAL, or AUXILIARY
  • obsolete (bool) – True if the objectClass has been marked obsolete.
  • my_must (list[str]) – The list of required attribute types for this class
  • my_may (list[str]) – The list of allowed attribute types for this class
allowed_attr(name)[source]

Check if the given attribute type name is allowed.

Parameters:name – The name of the attribute type to check
Returns:True if the given attribute type is allowed.
Return type:bool
may

Obtains all allowed attribute types after ascending the superclass specifications

must

Obtains all required attribute types after ascending the superclass specifications

register()[source]
required_attr(name)[source]

Check if the given attribute type name is required.

Parameters:name – The name of the attribute type to check
Returns:True if the given attribute type is required.
Return type:bool
class laurelin.ldap.ExtensibleObjectClass(spec)[source]

Bases: laurelin.ldap.objectclass.ObjectClass

The extensibleObject auxiliary objectClass allows entries that belong to it to hold any user attribute.

allowed_attr(name)[source]

Check if the given attribute type name is allowed.

Parameters:name – The name of the attribute type to check
Returns:True if the given attribute type is allowed.
Return type:bool
class laurelin.ldap.SyntaxRule[source]

Bases: object

Base class for all syntax rules

DESC = ''

Short text description of the rule. Must be defined by subclasses.

OID = ''

The globally unique numeric OID of the syntax rule. Referenced in attribute type and matching rule specs. Must be defined by subclasses.

classmethod register()[source]
validate(s)[source]

Validate a string. Must be implemented by subclasses.

Parameters:s – Candidate string
Returns:Any useful value for the rule
Raises:InvalidSyntaxError – if the string is invalid
class laurelin.ldap.RegexSyntaxRule[source]

Bases: laurelin.ldap.rules.SyntaxRule

For validating rules based on a regular expression. Most syntax rules can inherit from this.

regex = ''

The regular expression defining the rule. Subclasses must define this attribute.

validate(s)[source]

Validate a string against the regular expression.

Parameters:s – Candidate string
Returns:The regex match object
Return type:MatchObject
Raises:InvalidSyntaxError – if the string does not match
class laurelin.ldap.MatchingRule[source]

Bases: object

Base class for all matching rules

NAME = ''

Globally unique name for the matching rule. Most attribute type specs will reference rules using the name, but they can also use the OID. This must be defined by subclasses.

OID = ''

Globally unique numeric OID for the matching rule. This must be defined by subclasses.

SYNTAX = ''

The numeric OID for the syntax rule that assertion values must comply with. Subclasses must define this.

do_match(attribute_value, assertion_value)[source]

Perform the match operation

match(attribute_value, assertion_value)[source]

Prepare values and perform the match operation. Assumes values have already been validated.

prep_methods = ()

A tuple of callables used to prepare attribute and asserion values. Subclasses may optionally define this.

prepare(value)[source]

Prepare a string for matching

classmethod register()[source]
validate(value)[source]

Perform validation according to the matching rule’s syntax

class laurelin.ldap.EqualityMatchingRule[source]

Bases: laurelin.ldap.rules.MatchingRule

Base class for all EQUALITY matching rules

do_match(attribute_value, assertion_value)[source]

Perform equality matching

class laurelin.ldap.Validator[source]

Bases: object

Abstract base class for a validator. All validators must inherit from here and ensure the public interface is fully implemented.

validate_modify(dn, modlist, current)[source]

Validate a modify operation.

By default, validate all attributes for writing.

Parameters:
  • dn (str) – The DN of the object being modified
  • modlist (list[Mod]) – The list of modify operations to be performed this transaction
  • current (LDAPObject or None) – The known state of the object prior to modification
Returns:

None

Raises:

LDAPValidationError – if any modify operation is invalid

validate_object(obj, write=True)[source]

Validate an object when all attributes are present.

By default, validate all attributes on the object.

Parameters:
  • obj (LDAPObject) – An LDAP object with all attributes defined
  • write (bool) – True if we are validating a write operation to the database
Returns:

None

Raises:

LDAPValidationError – if the object is invalid in any way

class laurelin.ldap.SchemaValidator[source]

Bases: laurelin.ldap.validation.Validator

Ensures parameters conform to the available defined schema

validate_object(obj, write=True)[source]

Validates an object when all attributes are present

  • Requires the objectClass attribute
  • Checks that all attributes required by the objectClass are defined
  • Checks that all attributes are allowed by the objectClass
  • Performs validation against the attribute type spec for all attributes
laurelin.ldap.dc(domain)[source]

Convert a DNS dotted domain name to a DN with domain components

laurelin.ldap.domain(dc)[source]

Convert a DN with domain components to a DNS dotted domain name