sansldap package

Submodules

sansldap.asn1 module

class sansldap.asn1.ASN1Header(tag: ASN1Tag, tag_length: int, length: int)

Bases: tuple

A representation of an ASN.1 TLV as a tuple.

Defines the ASN.1 Type Length Value (TLV) values as separate objects for easier parsing. This is returned by ASN1Reader.peek_header().

Parameters:
  • tag – The tag details, including the class and tag number.

  • tag_length – The length of the encoded tag.

  • length – The length of the value the tag represents.

length: int

The length of the ASN.1 value.

tag: ASN1Tag

The ASN.1 tag details for the current entry.

tag_length: int

The length of the tag/length ASN.1 octets.

class sansldap.asn1.ASN1Reader(data)

Bases: object

ASN.1 value reader.

Class used to read ASN.1 data that is passed in. It provides a an easy way to stream through the data as well as peek as the subsequent entries.

Parameters:

data (Union[bytes, bytearray, memoryview]) – The data to read from.

get_remaining_data()

Gets the remaining data in the reader.

Return type:

bytes

peek_header()

Get the next value header.

Gets the header for the next value. This will not read the value so it will still be at the same position once run.

Returns:

The header information including the tag information as well as the length of the next value.

Return type:

ASN1Header

read_boolean(tag=None, header=None, hint=None)

Reads an ASN.1 BOOLEAN value.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the BOOLEAN universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The bool value.

Return type:

bool

read_enumerated(enum_type, tag=None, header=None, hint=None)

Reads an ASN.1 ENUMERATED value.

Parameters:
  • enum_type (Type[TypeVar(T, bound= int)]) – The enum.IntEnum type to cast the integer value to.

  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the ENUMERATED universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The instance of enum_type that the value represents.

Return type:

T

read_integer(tag=None, header=None, hint=None)

Reads an ASN.1 INTEGER value.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the INTEGER universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The int value.

Return type:

int

read_octet_string(tag=None, header=None, hint=None)

Reads an ASN.1 OCTET_STRING value.

As this returns a bytes string, it is useful to extract the raw ASN.1 value as long as the correct tag or header is provided.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the OCTET_STRING universal tag (primitive).

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The octet string bytes.

Return type:

bytes

read_sequence(tag=None, header=None, hint=None)

Reads an ASN.1 SEQUENCE or SEQUENCE_OF value.

The returned reader can be used to then read the values inside the sequence.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the SEQUENCE/SEQUENCE_OF universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The ASN.1 reader object that can be used to read the

sequence elements.

Return type:

ASN1Reader

read_sequence_of(tag=None, header=None, hint=None)

Reads an ASN.1 SEQUENCE or SEQUENCE_OF value.

The returned reader can be used to then read the values inside the sequence.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the SEQUENCE/SEQUENCE_OF universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The ASN.1 reader object that can be used to read the

sequence elements.

Return type:

ASN1Reader

read_set(tag=None, header=None, hint=None)

Reads an ASN.1 SET or SET_OF value.

The returned reader can be used to then read the values inside the set.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the SET/SET_OF universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The ASN.1 reader object that can be used to read the

set elements.

Return type:

ASN1Reader

read_set_of(tag=None, header=None, hint=None)

Reads an ASN.1 SET or SET_OF value.

The returned reader can be used to then read the values inside the set.

Parameters:
  • tag (Optional[ASN1Tag]) – The tag to validate with, defaults to the SET/SET_OF universal tag.

  • header (Optional[ASN1Header]) – Optional header from peek_header() to make the extraction more efficient.

  • hint (Optional[str]) – A hint used in error messages to display what this step was used for.

Returns:

The ASN.1 reader object that can be used to read the

set elements.

Return type:

ASN1Reader

skip_value(header)

Skips the next value.

Skips the next value as indicated by the header.

Parameters:

header (ASN1Header) – The header which contains the metadata of the next value to skip.

Return type:

None

class sansldap.asn1.ASN1Tag(tag_class: TagClass, tag_number: t.Union[int, TypeTagNumber], is_constructed: bool)

Bases: tuple

ASN.1 tag information.

Defines the explicit ASN.1 tag used in a value which includes the tag class, tag number, and whether it is a constructed or primitive value.

Parameters:
  • tag_class – The tag class the value represents.

  • tag_number – The tag number of the value.

  • is_constructed – Whether the value is constructed (True) or primitive (False).

is_constructed: bool

Whether the value is marked as constructed or primitive.

tag_class: TagClass

The tag class.

tag_number: Union[int, TypeTagNumber]

The tag number, will be TypeTagNumber if the tag_class is UNIVERSAL.

classmethod universal_tag(number, is_constructed=False)

Generates a universal tag with the type specified.

Return type:

ASN1Tag

class sansldap.asn1.ASN1Writer(*, tag=None, parent=None)

Bases: object

ASN.1 value writer.

Class used to write ASN.1 data into an internal buffer. This data can then be retrieved using get_data(). It provides a nice helper to easily accumulate multiple values in one object.

Parameters:
  • tag (Optional[ASN1Tag]) – Optional tag to used when in a sequence/set writer.

  • parent (Optional[ASN1Writer]) – The parent writer used when in a sequence/set writer.

get_data()

Gets the data written to the writer.

This is used to get the final ASN.1 value after all the values have been written to it. It cannot be called on a child writer returned by push_sequence or push_set.

Returns:

The data that has been written.

Return type:

bytearray

push_sequence(tag=None)

Get new writer for a SEQUENCE or SEQUENCE_OF value.

Gets a new writer to start writing values inside a sequence or sequence of object. Make sure to wrap the writer in a with statement to ensure the sequence is closed and written back to the parent writer.

Examples

with writer.push_sequence() as seq_writer:
    seq_writer.write_octet_string(b"foo")
Parameters:

tag (Optional[ASN1Tag]) – Optional tag to mark the sequence/sequence_of with.

Returns:

The writer object that can be used to write the sequence elements.

Return type:

ASN1Writer

push_sequence_of(tag=None)

Get new writer for a SEQUENCE or SEQUENCE_OF value.

Gets a new writer to start writing values inside a sequence or sequence of object. Make sure to wrap the writer in a with statement to ensure the sequence is closed and written back to the parent writer.

Examples

with writer.push_sequence() as seq_writer:
    seq_writer.write_octet_string(b"foo")
Parameters:

tag (Optional[ASN1Tag]) – Optional tag to mark the sequence/sequence_of with.

Returns:

The writer object that can be used to write the sequence elements.

Return type:

ASN1Writer

push_set(tag=None)

Get new writer for a SET or SET_OF value.

Gets a new writer to start writing values inside a set or set of object. Make sure to wrap the writer in a with statement to ensure the sequence is closed and written back to the parent writer.

Examples

with writer.push_set() as seq_writer:
    seq_writer.write_octet_string(b"foo")
Parameters:

tag (Optional[ASN1Tag]) – Optional tag to mark the sequence/sequence_of with.

Returns:

The writer object that can be used to write the set elements.

Return type:

ASN1Writer

push_set_of(tag=None)

Get new writer for a SET or SET_OF value.

Gets a new writer to start writing values inside a set or set of object. Make sure to wrap the writer in a with statement to ensure the sequence is closed and written back to the parent writer.

Examples

with writer.push_set() as seq_writer:
    seq_writer.write_octet_string(b"foo")
Parameters:

tag (Optional[ASN1Tag]) – Optional tag to mark the sequence/sequence_of with.

Returns:

The writer object that can be used to write the set elements.

Return type:

ASN1Writer

write_boolean(value, tag=None)

Write an ASN.1 BOOLEAN value.

Writes a boolean value to the current writer.

Parameters:
  • value (bool) – The bool to write.

  • tag (Optional[ASN1Tag]) – Optional tag to use with the value, defaults to the BOOLEAN universal tag.

Return type:

None

write_enumerated(value, tag=None)

Write an ASN.1 ENUMEATES value.

Writes a enumerated value to the current writer.

Parameters:
  • value (int) – The enumerated/int to write.

  • tag (Optional[ASN1Tag]) – Optional tag to use with the value, defaults to the ENUMERATED universal tag.

Return type:

None

write_integer(value, tag=None)

Write an ASN.1 INTEGER value.

Writes an int value to the current writer.

Parameters:
  • value (int) – The int to write.

  • tag (Optional[ASN1Tag]) – Optional tag to use with the value, defaults to the INTEGER universal tag.

Return type:

None

write_octet_string(value, tag=None)

Write an ASN.1 OCTET_STRING value.

Writes a bytes string value to the current writer.

Parameters:
  • value (bytes) – The bool to write.

  • tag (Optional[ASN1Tag]) – Optional tag to use with the value, defaults to the OCTET_STRING universal tag.

Return type:

None

exception sansldap.asn1.NotEnougData

Bases: Exception

There is not enough data available to unpack ASN.1 value

class sansldap.asn1.TagClass(value)

Bases: IntEnum

The ASN.1 tag class types.

APPLICATION = 1
CONTEXT_SPECIFIC = 2
PRIVATE = 3
UNIVERSAL = 0
class sansldap.asn1.TypeTagNumber(value)

Bases: IntEnum

The ASN.1 tag numbers for universal classes.

BIT_STRING = 3
BMP_STRING = 30
BOOLEAN = 1
CHARACTER_STRING = 29
DATE = 31
DATE_TIME = 33
DURATION = 34
EMBEDDED_PDV = 11
END_OF_CONTENT = 0
ENUMERATED = 10
EXTERNAL = 8
GENERALIZED_TIME = 24
GENERAL_STRING = 27
GRAPHIC_STRING = 25
IA5_STRING = 22
INTEGER = 2
NULL = 5
NUMERIC_STRING = 18
OBJECT_DESCRIPTOR = 7
OBJECT_IDENTIFIER = 6
OCTET_STRING = 4
OID_IRL = 35
PRINTABLE_STRING = 19
REAL = 9
RELATIVE_OID = 13
RELATIVE_OID_IRL = 36
RESERVED = 15
SEQUENCE = 16
SEQUENCE_OF = 16
SET = 17
SET_OF = 17
T61_STRING = 20
TIME = 14
TIME_OF_DAY = 32
UNIVERSAL_STRING = 28
UTC_TIME = 23
UTF8_STRING = 12
VIDEOTEX_STRING = 21
VISIBLE_STRING = 26

sansldap.schema module

class sansldap.schema.AttributeTypeDescription(oid, names=<factory>, description=None, obsolete=False, super_type=None, equality=None, ordering=None, substrings=None, syntax=None, syntax_length=None, single_value=False, collective=False, no_user_modification=False, usage=AttributeTypeUsage.USER_APPLICATIONS, extensions=<factory>)

Bases: object

Attribute Type definition.

Object is used to define attribute types inside an LDAP database. This object is defined in RFC 4512 4.1.2. Attribute Types. Typically Microsoft Active Directory only defines the oid, single name entry, syntax, single_value, and no_user_modification elements of the definition.

Parameters:
  • oid (str) – The object identifier for this attribute type.

  • names (List[str]) – The named identifying this attribute type.

  • description (Optional[str]) – A short description of the attribute type.

  • obsolete (bool) – Indicates the attribute type is not active.

  • super_type (Optional[str]) – The OID of the super type of this type.

  • equality (Optional[str]) – The OID of the equality matching rule.

  • ordering (Optional[str]) – The OID of the ordering matching rule.

  • substrings (Optional[str]) – The OID of the substrings matching rule.

  • syntax (Optional[str]) – Identifies the value syntax type.

  • syntax_length (Optional[int]) – Optional upper bound length of the syntax value.

  • single_value (bool) – Indicates that the attribute is restricted to a single value or not.

  • collective (bool) – Indicates the attribute type is collective.

  • no_user_modification (bool) – Indicates the attribute type is not user modifiable.

  • usage (AttributeTypeUsage) – The application of the attribute type. Can be set to userApplications, directoryOperation, distributedOperation, or dSAOperation.

  • extensions (Dict[str, List[str]]) – Optional extensions to the attribute type.

collective: bool = False
description: Optional[str] = None
equality: Optional[str] = None
extensions: Dict[str, List[str]]
classmethod from_string(value)
Return type:

AttributeTypeDescription

names: List[str]
no_user_modification: bool = False
obsolete: bool = False
oid: str
ordering: Optional[str] = None
single_value: bool = False
substrings: Optional[str] = None
super_type: Optional[str] = None
syntax: Optional[str] = None
syntax_length: Optional[int] = None
usage: AttributeTypeUsage = 'userApplications'
class sansldap.schema.AttributeTypeUsage(value)

Bases: str, Enum

An enumeration.

DIRECTORY_OPERATION = 'directoryOperation'
DISTRIBUTED_OPERATION = 'distributedOperation'
DSA_OPERATION = 'dSAOperation'
USER_APPLICATIONS = 'userApplications'
class sansldap.schema.DITContentRuleDescription(oid, names=<factory>, description=None, obsolete=False, aux=<factory>, must=<factory>, may=<factory>, never=<factory>, extensions=<factory>)

Bases: object

DIT Content Rule.

Object is used to define DIT content rules that govern the content of entries of a particular structural object class. This object is defined in RFC 4512 4.1.6. DIT Content Rules.

Parameters:
  • oid (str) – The object identifier for this DIT content rule.

  • names (List[str]) – The named identifying this DIT content rule.

  • description (Optional[str]) – A short description of this DIT content rule.

  • obsolete (bool) – Indicates the DIT content rule is not active.

  • aux (List[str]) – List of auxiliary object class OIDS that entries subject to this DIT content rule may belong to.

  • must (List[str]) – Required attribute types by OID.

  • may (List[str]) – Allowed attribute types by OID.

  • never (List[str]) – Precluded attribute types by OID.

  • extensions (Dict[str, List[str]]) – Optional extensions to the DIT content rule.

aux: List[str]
description: Optional[str] = None
extensions: Dict[str, List[str]]
classmethod from_string(value)
Return type:

DITContentRuleDescription

may: List[str]
must: List[str]
names: List[str]
never: List[str]
obsolete: bool = False
oid: str
class sansldap.schema.ObjectClassDescription(oid, names=<factory>, description=None, obsolete=False, super_types=<factory>, kind=ObjectClassKind.STRUCTURAL, must=<factory>, may=<factory>, extensions=<factory>)

Bases: object

Object Class definition.

Object is used to define object classes inside an LDAP database. This object is defined in RFC 4512 4.1.1. Object Class Definitions.

Parameters:
  • oid (str) – The object identifier for this object class.

  • names (List[str]) – The named identifying this object class.

  • description (Optional[str]) – A short description of the object class.

  • obsolete (bool) – Indicates the object class is not active.

  • super_types (List[str]) – The direct superclasses of this object class.

  • kind (ObjectClassKind) – The kind of object class.

  • must (List[str]) – Required attribute types by OID.

  • may (List[str]) – Allowed attribute types by OID.

  • extensions (Dict[str, List[str]]) – Optional extensions to the object class.

description: Optional[str] = None
extensions: Dict[str, List[str]]
classmethod from_string(value)
Return type:

ObjectClassDescription

kind: ObjectClassKind = 'STRUCTURAL'
may: List[str]
must: List[str]
names: List[str]
obsolete: bool = False
oid: str
super_types: List[str]
class sansldap.schema.ObjectClassKind(value)

Bases: str, Enum

An enumeration.

ABSTRACT = 'ABSTRACT'
AUXILIARY = 'AUXILIARY'
STRUCTURAL = 'STRUCTURAL'

Module contents

class sansldap.AuthenticationCredential(auth_id)

Bases: object

Base class for Bind Request Authentication choices.

This is the base class for bind request authentiction that can be used to provide custom authentication choices used in the sansldap.BindRequest. By default the SimpleCredential and SaslCredential choices are available. Each implementation must provide a value for auth_id, is_primitive as well as implement the pack and unpack methods. If no field is defined for is_primitive it defaults to True.

Example

@dataclasses.dataclass(frozen=True)
class CustomAuth(a.AuthenticationCredential):
    auth_id: int = dataclasses.field(init=False, repr=False, default=1024)

    username: str
    password: str

    def pack(
        self,
        writer: sansldap.asn1.ASN1Writer,
        options: a.AuthenticationOptions,
    ) -> None:
        writer.write_octet_string(
            f"{self.username}:{self.password}".encode(options.string_encoding),
            tag=sansldap.asn1.ASN1Tag(
                sansldap.asn1.TagClass.CONTEXT_SPECIFIC,
                self.auth_id,
                False,
            ),
        )

    @classmethod
    def unpack(
        cls,
        reader: sansldap.asn1.ASN1Reader,
        options: a.AuthenticationOptions,
    ) -> CustomAuth:
        value = reader.read_octet_string(
            tag=sansldap.asn1.ASN1Tag(
                sansldap.asn1.TagClass.CONTEXT_SPECIFIC,
                cls.auth_id,
                False,
            ),
            hint="CustomAuth.value",
        ).decode(options.string_encoding)
        username, _, password = value.partition(":")

        return CustomAuth(username=username, password=password)
Parameters:

auth_id (int) – The ASN.1 choice value for this credential.

Note

A custom authentication credential must be understood by both the client and server.

auth_id: int

The authentication choice value. Reflects the choice tag encoded in the ASN.1 value and should be set with a default value in inheriting classes.

pack(writer, options)

Pack the authentication structure.

Writes the authentication structure into the ASN.1 writer that is then embedded in the sansldap.BindRequest authentication value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data.

  • options (AuthenticationOptions) – Options that can be used to control how the authentication credential is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the authentication bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (AuthenticationOptions) – Options that can be used to control how the authentication credential is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

AuthenticationCredential

class sansldap.AuthenticationOptions(string_encoding='utf-8', choices=<factory>)

Bases: object

Options used for Authentication packing and unpacking.

Custom options used for packing and unpacking authentication objects.

Parameters:
  • string_encoding (str) – The encoding that is used to encode and decode strings. Defaults to utf-8.

  • choices (List[Type[AuthenticationCredential]]) – List of known authentication types.

choices: List[Type[AuthenticationCredential]]

List of known authentication types

string_encoding: str = 'utf-8'

The encoding that is used to encode and decode string.

class sansldap.BindRequest(message_id, controls, version, name, authentication)

Bases: LDAPMessage, Request

The bind request message.

This object is used to exchange authentication and security-related semantics between the client and server. The BindRequest structure is defined in RFC 4511 4.2. Bind Operation.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • version (int) – The version of the LDAP protocol to be used. Currently only version 3 is supported.

  • name (str) – The name of the directory object that the client wishes to bind as. An empty string is used for SASL authentiction or with anonymous binds.

  • authentication (AuthenticationCredential) – The authentication information, currently either a SimpleCredential or SaslCredential is supported.

authentication: AuthenticationCredential
name: str
tag_number: int = 0

The LDAP message protocol op tag.

version: int
class sansldap.BindResponse(message_id, controls, result, server_sasl_creds=None)

Bases: LDAPMessage, Response

The bind response message.

This is the response to a BindRequest. It contains the status of the client’s bind operation and potentially a SASL response token. The BindResponse structure is defined in RFC 4511 4.2.2. Bind Response.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • result (LDAPResult) – The LDAP response.

  • server_sasl_creds (Optional[bytes]) – Contains the SASL challenge/response.

result: LDAPResult
server_sasl_creds: Optional[bytes] = None
tag_number: int = 1

The LDAP message protocol op tag.

class sansldap.ControlOptions(string_encoding='utf-8', choices=<factory>)

Bases: object

Options used for Control packing and unpacking.

Custom options used for packing and unpacking control objects.

Parameters:
  • string_encoding (str) – The encoding that is used to encode and decode strings. Defaults to utf-8.

  • choices (List[Type[LDAPControl]]) – List of known controls.

choices: List[Type[LDAPControl]]
string_encoding: str = 'utf-8'
class sansldap.DereferencingPolicy(value)

Bases: IntEnum

Control alias dereferencing during a search.

ALWAYS = 3

Dererence aliases both in searching and in locating the base object of the search.

FINDING_BASE_OBJ = 2

Dereference aliases in locating the base object of the search, but not when searching subordinates of the base object.

IN_SEARCHING = 1

While searching subordinates of the base object, dereference any alias within the search scope.

NEVER = 0

Do not reference aliases in search or in locating the base object the search.

class sansldap.ExtendedOperations(value)

Bases: str, Enum

Known LDAP Extended Operation Names.

LDAP_NOTICE_OF_DISCONNECTION = '1.3.6.1.4.1.1466.20036'
LDAP_START_TLS = '1.3.6.1.4.1.1466.20037'
class sansldap.ExtendedRequest(message_id, controls, name, value)

Bases: LDAPMessage, Request

The extended request message.

An extended operation is a custom operation not strictly defined in the LDAP RFC. It is used to extend the existing set of operations with custom ones that could be known to the client and server. For example the StartTLS protocol uses an extended operation to start embedding the transport with TLS. The ExtendedRequest structure is defined in RFC 4511 4.12. Extended Operation.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • name (str) – The extended operation OID string.

  • value (Optional[bytes]) – The extended operation value as a byte string. Can be None if the operation does not require a value.

name: str
tag_number: int = 23

The LDAP message protocol op tag.

value: Optional[bytes]
class sansldap.ExtendedResponse(message_id, controls, result, name, value)

Bases: LDAPMessage, Response

The extended response message.

The response to an extended request and contains the result of the operation as well as extra data associated with the operation. The ExtendedResponse structure is defined in RFC 4511 4.12. Extended Operation.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • result (LDAPResult) – The result of the operation.

  • name (Optional[str]) – The operation OID string that was performced. This is optionally returned by the server.

  • value (Optional[bytes]) – The operation data is specific to the operation performed. This is optionally returned by the server.

name: Optional[str]
result: LDAPResult
tag_number: int = 24

The LDAP message protocol op tag.

value: Optional[bytes]
class sansldap.FilterAnd(filters)

Bases: LDAPFilter

LDAP Filter Any.

An LDAP filter that is used to combine multiple filters together using the AND logic operation. All filters specified must be true for this filter to be true in a search operation. An AND LDAP filter string look like (&(condition=1)(condition=2)...)

Parameters:

filters (List[LDAPFilter]) – The filters to use in the AND operation.

filter_id: int = 0

The ASN.1 choice value for this filter.

filters: List[LDAPFilter]
pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

class sansldap.FilterApproxMatch(attribute, value)

Bases: LDAPFilter

LDAP Filter Approx Match.

An LDAP filter that is used to check if the value for the attribute specified matches a locally-defined approximate matching algorithm. An approx match LDAP filter looks like (attribute~=condition).

Parameters:
  • attribute (str) – The attribute to match against.

  • value (bytes) – The value to use as the approximate matching comparison.

attribute: str
filter_id: int = 8

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

value: bytes
class sansldap.FilterEquality(attribute, value)

Bases: LDAPFilter

LDAP Filter Equality.

An LDAP filter that is used to check if the attribtue specified is set to the value specified. An equality LDAP filter string looks like (attribute=1).

Parameters:
  • attribute (str) – The attribute to match against.

  • value (bytes) – The value of the attribute to check.

attribute: str
filter_id: int = 3

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

value: bytes
class sansldap.FilterExtensibleMatch(rule, attribute, value, dn_attributes)

Bases: LDAPFilter

LDAP Filter Extensible Match.

An LDAP filter that is used to as a more powerful way to check an attribute value. It can have custom rules and logic that is known to the server for the check. An extensible amtch LDAP filter looks like (attribute:=John), (attribute:dn:=Jordan), or (attribute:1.2.3:=John). If no rule is specified then attribute must be set.

Parameters:
  • rule (Optional[str]) – The rule name or OID string that should be used for the match or None if attribute is set to follow the normal rules.

  • attribute (Optional[str]) – The attribute to match against if this should only be checked against a single value. Can be None to search all attributes if rule is set.

  • value (bytes) – The value to compare.

  • dn_attributes (bool) – Use the attributes that compose the entries DN in the check.

attribute: Optional[str]
dn_attributes: bool
filter_id: int = 9

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

rule: Optional[str]
classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

value: bytes
class sansldap.FilterGreaterOrEqual(attribute, value)

Bases: LDAPFilter

LDAP Filter Greater Than.

An LDAP filter that is used to great if the value is greater than or equal to the value specified. A greater than or equal LDAP filter looks like (attribute>=1).

Parameters:
  • attribute (str) – The attribute to match against.

  • value (bytes) – The value that must be greater or equal to the actual value.

attribute: str
filter_id: int = 5

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

value: bytes
class sansldap.FilterLessOrEqual(attribute, value)

Bases: LDAPFilter

LDAP Filter Less Than.

An LDAP filter that is used to great if the value is less than or equal to the value specified. A less than or equal LDAP filter looks like (attribute<=1).

Parameters:
  • attribute (str) – The attribute to match against.

  • value (bytes) – The value that must be lesser or equal to the actual value.

attribute: str
filter_id: int = 6

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

value: bytes
class sansldap.FilterNot(filter)

Bases: LDAPFilter

LDAP Filter Not.

An LDAP filter that is used to inverse the logic of the filter present. For example if the filter condition is false, then the NOT filter will make it true and vice versa. A NOT LDAP filter string looks like (!(attribute=1)).

Parameters:

filter (LDAPFilter) – The filter to inverse.

filter: LDAPFilter
filter_id: int = 2

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

class sansldap.FilterOptions(string_encoding='utf-8', choices=<factory>)

Bases: object

Options used for Filter packing and unpacking.

Custom options used for packing and unpacking filter objects.

Parameters:
  • string_encoding (str) – The encoding that is used to encode and decode strings. Defaults to utf-8.

  • choices (List[Type[LDAPFilter]]) – List of known filter types.

choices: List[Type[LDAPFilter]]
string_encoding: str = 'utf-8'
class sansldap.FilterOr(filters)

Bases: LDAPFilter

LDAP Filter Or.

An LDAP filter that is used to combine multiple filters together using the OR logic operation. Only one of the filters specified must be true for this filter to be true in a search operation. An OR LDAP filter string looks like (|(condition=1)(condition=2)...)

Parameters:

filters (List[LDAPFilter]) – The filters to use in the OR operation.

filter_id: int = 1

The ASN.1 choice value for this filter.

filters: List[LDAPFilter]
pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

class sansldap.FilterPresent(attribute)

Bases: LDAPFilter

LDAP Filter Present.

An LDAP filter that is used to great if the attribute is present (has a value) in the entity being checked. A present LDAP filter looks like (attribute=*).

Parameters:

attribute (str) – The attribute to check if present.

attribute: str
filter_id: int = 7

The ASN.1 choice value for this filter.

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

class sansldap.FilterSubstrings(attribute, initial, any, final)

Bases: LDAPFilter

LDAP Filter Substrings.

An LDAP filter that is used to check substrings inside an attribute value. It can contain an initial and final string that must match the start and end of the value respectively. It can also contain any values in the middle of the value as denoted by the any argument. A substrings LDAP filter looks like (attribute=initial*any 1*any 2*final).

Parameters:
  • attribute (str) – The attribute to match against.

  • initial (Optional[bytes]) – The value must start with this value if present.

  • any (List[bytes]) – Values inside the whole value that are checked to be in the value.

  • final (Optional[bytes]) – The value must end with this value if present.

any: List[bytes]
attribute: str
filter_id: int = 4

The ASN.1 choice value for this filter.

final: Optional[bytes]
initial: Optional[bytes]
pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

class sansldap.LDAPClient

Bases: LDAPSession

LDAP Client session.

The LDAP client session class that is used to send client LDAP messages.

bind(dn, authentication, controls=None)

Send a BIND request.

Creates a bind request with the authentication payload specified. This can be used to bind with a custom set of credentials that have been registered with LDAPSession.register_auth_credential(). it is recommended to use bind_simple() or bind_sasl() instead of this function.

Parameters:
Returns:

The message id associated with the request.

Return type:

int

bind_sasl(mechanism, dn=None, cred=None, controls=None)

Send a SASL BIND request.

Creates a SASL bind request using the mechanism and credential specified. A SASL bind operation may require multiple requests for the bind to be completed. It is up to the caller to process any server SASL credential responses in the BindResponse and then create a new SASL BindRequest with the new credential vaue.

Common mechanisms are EXTERNAL, GSSAPI, GSS-SPNEGO. DIGEST-MD5.

The EXTERNAL SASL mech is used for TLS Client Authentication. No cred is used as it relies on the certificate to be presented during the TLS handshake performed prior.

The GSSAPI SASL mech is used for Kerberos authentication. It will send the Kerberos token as the first step in cred, then negotiate the SASL security factors for signing and encryption in the subsequent credential.

The GSS-SPNEGO SASL mech is used for Negotiate authentication. It will send the Negotiate (Kerberos with NTLM fallback) cred and subsequent tokens during the authentication phase.

The DIGEST-MD5 SASL mech is used for authentication using the RFC 2831 spec.

Using an empty string for mechanism can be used to cancel an existing SASL bind request that is currently in operation.

Note

You can only run a bind if there are no outstanding requests on the session. Once a bind has started, no other requests can be started until the bind is complete.

Parameters:
  • mechanism (str) – The SASL mechanism to authenticate with.

  • dn (Optional[str]) – The user to bind as, this is typically not set for SASL as the cred contains the user information.

  • cred (Optional[bytes]) – The SASL bytes to authenticate with.

  • controls (Optional[List[LDAPControl]]) – Optional client controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

bind_simple(dn=None, password=None, controls=None)

Send a Simple BIND request.

Creates a SIMPLE bind request to perform an anonymous, unauthenticate, or authenticated bind. The format of dn depends on the LDAP server implementation. For example MS AD supports the sAMAccountName value while OpenLDAP would require the distinguished name of the user to bind as.

Note

You can only run a bind if there are no outstanding requests on the session. Once a bind has started, no other requests can be started until the bind is complete.

Parameters:
  • dn (Optional[str]) – The name of the Directory object that the client wishes to bind as. Set to None or an empty string to perform an anonymous bind.

  • password (Optional[str]) – The password to bind with, set to None or an empty string to perform an unauthenticated bind.

  • controls (Optional[List[LDAPControl]]) – Optional client controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

extended_request(name, value=None, controls=None)

Send an Extended request.

Creates an extended request to perform custom operations on the server. An extended request must be supported by both the client and server.

Parameters:
  • name (str) – The extended request OID string.

  • value (Optional[bytes]) – The value for the request, can be None if the request does not hae a value.

  • controls (Optional[List[LDAPControl]]) – Optional client controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

receive(data)

Receive data to process.

Receives the data from the peer and unpack the messages found into LDAPMessages. Any complete LDAP messages received will be returned and any remaining data will be stored in an internal buffer.A ProtocolError indicates something fatal has occurred when trying to parse the incoming data and the connection is no longer in a valid state. The caller SHOULD send the notice of disconnection payload available in data_to_send() and MUST close the underlying connection.

Note

A ProtocolError is not raised when receiving a valid LDAP response with a result code that is not SUCCESS. Only critical errors where the session is no longer viable will raise this error.

Parameters:

data (Union[bytes, bytearray, memoryview]) – The data to process.

Returns:

A list of messages that have been unpacked.

Return type:

t.List[LDAPMessage]

Raises:

ProtocolError – A protocol violation occurred and the connection is no longer valid.

search_request(base_object=None, scope=SearchScope.SUBTREE, dereferencing_policy=DereferencingPolicy.NEVER, size_limit=0, time_limit=0, types_only=False, filter=None, attributes=None, controls=None)

Send a Search Request.

Creates a search request. This request can result in 3 different responses from the server; SearchResultEntry, SearchResultReference, and SearchResultDone. The operation is not considered to be complete until the SearchResultDone response has been received from the server.

While a limit can be placed for the size and time, these will be ignored by the server if their configured limits is less than what is requested.

The following are special attributes that can be requested:

*: Requests all attributes in addition to the explicitly defined

ones.

1.1: No attributes are to be returned. Is ignored if there are any

other attributes specified.

Note

If using a custom filter, ensure it has been registered with register_filter().

Parameters:
  • base_object (Optional[str]) – The name of the base object entry, or None/empty string for root, which the search is to be performed.

  • scope (Union[int, SearchScope]) – The scope of the search. See SearchScope for more details. Defaults to SUBTREE.

  • dereferencing_policy (Union[int, DereferencingPolicy]) – Indicates how alias entries are to be dereferenced, see DereferencingPolicy for more details. Defaults to NEVER.

  • size_limit (int) – The maximum number of entries to be returned. A value of 0 has no restrictions.

  • time_limit (int) – The maximum time, in seconds, allowed for the operation. A value of 0 has no time restrictions.

  • types_only (bool) – Only return ttribute names and no values in the search result.

  • filter (Optional[LDAPFilter]) – The LDAP filter to search by. See LDAPFilter for more information.

  • attributes (Optional[List[str]]) – A list of attributes to be returned from each entry that match the search filter. The default requests the return of all user attributes.

  • controls (Optional[List[LDAPControl]]) – Optional client controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

class sansldap.LDAPControl(control_type, critical, value)

Bases: object

LDAP Control.

An extended control used in an LDAPMessage. This can be sent by the client, known as client controls, or by the server, server controls. Each control is identified by an OID string that is meant to be unique and known by both the client and server. It can be marked as critical which means the peer should fail the operation if it does not know the control type specified. The Control structure is defined in RFC 4511 4.1.11. Controls.

An unpacked control object is guaranteed to have the control_type, critical, and value bytes set. Some controls are known by this library and will unpack to objects containing the unpacks value. For example when unpacking a PagedResultControl control, the value will contain the raw bytes but the size and cookie attributes will also be present. In the future more controls will be added.

A custom implementation must inherit this class and provide a value for control_type as well as implement the get_value and unpack methods.

Example

@dataclasses.dataclass(frozen=True)
class CustomControl(LDAPControl):
    control_type: str = dataclasses.field(init=False, repr=False, default="1.2.3.4")
    value: t.Optional[bytes] = dataclasses.field(init=False, repr=False, default=None)

    size: int

    def get_value(
        self,
        options: ControlOptions,
    ) -> t.Optional[bytes]:
        return self.size.to_bytes(4)

    @classmethod
    def unpack(
        cls,
        control_type: str,
        critical: bool,
        value: t.Optional[bytes],
        options: ControlOptions,
    ) -> CustomControl:
        size = struct.unpack("<I", (value or b""))[0]

        return CustomControl(critical=critical, size=size)
Parameters:
  • control_type (str) – The control OID string.

  • critical (bool) – Whether the control is marked as critical or not.

  • value (Optional[bytes]) – The raw control value, if any.

control_type: str
critical: bool
get_value(options)
Return type:

Optional[bytes]

pack(writer, options)
Return type:

None

classmethod unpack(control_type, critical, value, options)
Return type:

LDAPControl

value: Optional[bytes]
exception sansldap.LDAPError

Bases: Exception

Base LDAP error class.

class sansldap.LDAPFilter(filter_id)

Bases: object

Base class for all LDAP filters.

This is the base class in which all LDAP filters derive and can be used to implement custom filters outside of the set provided in the LDAP RFC. Currently the following filter types are known and implemented:

A custom implementation must inherit this class and provide a value for filter_id as well as implement the pack and unpack methods. These methods use the ASN1Writer and ASN1Reader classes respectively to make it easier to deal with ASN.1 structured data and more efficiently stream the data as needed.

Example

@dataclasses.dataclass(frozen=True)
class CustomFilter(LDAPFilter):
    filter_id: int = dataclasses.field(init=False, repr=False, default=1024)

    value: str

    def pack(
        self,
        writer: sansldap.asn1.ASN1Writer,
        options: FilterOptions,
    ) -> None:
        writer.write_octet_string(
            self.value.encode(options.string_encoding),
            tag=sansldap.asn1.ASN1Tag(
                sansldap.asn1.TagClass.CONTEXT_SPECIFIC,
                self.filter_id,
                False,
            ),
        )

    @classmethod
    def unpack(
        cls,
        reader: sansldap.asn1.ASN1Reader,
        options: FilterOptions,
    ) -> CustomFilter:
        value = reader.read_octet_string(
            sansldap.asn1.ASN1Tag(
                sansldap.asn1.TagClass.CONTEXT_SPECIFIC,
                cls.filter_id,
                False,
            ),
        ).decode("utf-8")
        return CustomFilter(value=value)

Note

A custom filter must be understood by both the client and server.

filter_id: int

The ASN.1 choice value for this filter.

classmethod from_string(filter)

Convert an LDAP filter string to a filter object.

Converts the string provided into an LDAPFilter object based on the standard LDAPFilter string rules. This only supports the LDAP filters as defined in RFC 4511.

Parameters:

filter (str) – The LDAP filter string to convert.

Returns:

The converted filter.

Return type:

LDAPFilter

pack(writer, options)

Pack the filter structure.

Writes the filter structure into the ASN.1 writer that is then embedded in the SearchRequest filter value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data

  • options (FilterOptions) – Options that can be used to control how the filter is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the filter bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (FilterOptions) – Options that can be used to control how the filter is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

LDAPFilter

class sansldap.LDAPMessage(message_id, controls)

Bases: object

The base LDAP Message object.

This is the base object used for all LDAP messages. The base message structure is defined in RFC 4511 4.1.1. Message Envelope.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • tag_number – The protocolOp choice for this message type. This is defined on each LDAPMessage sub class.

controls: List[LDAPControl]
message_id: int
pack(options)

Packs the current message.

Packs the current message and returns the bytes string that can be exchanged with the peer.

Returns:

The ASN.1 BER encoded message.

Return type:

bytes

tag_number: int = 0
class sansldap.LDAPResult(result_code, matched_dn, diagnostics_message, referrals=None)

Bases: object

The LDAPResult message.

This is the base object that contains the various response results from a server. The LDAPResult structure is defined in RFC 4511 4.1.9. Result Message.

Parameters:
  • result_code (LDAPResultCode) – The result status of the operation.

  • matched_dn (str) – The subject to the name of the last entry used in finding the target of base object. Can be an empty string if not relevant.

  • diagnostics_message (str) – A string containing textual diagnostic messages. This is not standardized and should not be parsed, used for display purposes.

  • referrals (Optional[List[str]]) – Used when the result_code is REFERRAL, contains the references to one or more servers/services that may be accessed by LDAP.

diagnostics_message: str
matched_dn: str
referrals: Optional[List[str]] = None
result_code: LDAPResultCode
class sansldap.LDAPResultCode(value)

Bases: IntEnum

The known LDAP result codes.

ADMIN_LIMIT_EXCEEDED = 11
AFFECTS_MULTIPLE_DSAS = 71
ALIAS_DEREFERENCING_PROBLEM = 36
ALIAS_PROBLEM = 33
ATTRIBUTE_OR_VALUE_EXISTS = 20
AUTH_METHOD_NOT_SUPPORTED = 7
BUSY = 51
COMPARE_FALSE = 5
COMPARE_TRUE = 6
CONFIDENTIALITY_REQUIRED = 13
CONSTRAINT_VIOLATION = 19
ENTRY_ALREADY_EXISTS = 68
INAPPROPRIATE_AUTHENTICATION = 48
INAPPROPRIATE_MATCHING = 18
INSUFFICIENT_ACCESS_RIGHTS = 50
INVALID_ATTRIBUTE_SYNTAX = 21
INVALID_CREDENTIALS = 49
INVALID_DN_SYNTAX = 34
LOOP_DETECT = 54
NAMING_VIOLATION = 64
NOT_ALLOWED_ON_NON_LEAF = 66
NOT_ALLOWED_ON_RDN = 67
NO_SUCH_ATTRIBUTE = 16
NO_SUCH_OBJECT = 32
OBJECT_CLASS_MODS_PROHIBITED = 69
OBJECT_CLASS_VIOLATION = 65
OPERATIONS_ERROR = 1
OTHER = 80
PROTOCOL_ERROR = 2
REFERRAL = 10
SASL_BIND_IN_PROGRESS = 14
SIZE_LIMIT_EXCEEDED = 4
STRONG_AUTH_REQUIRED = 8
SUCCESS = 0
TIME_LIMIT_EXCEEDED = 3
UNAVAILABLE = 52
UNAVAILABLE_CRITICAL_EXTENSION = 12
UNDEFINED_ATTRIBUTE_TYPE = 17
UNWILLING_TO_PERFORM = 53
class sansldap.LDAPServer

Bases: LDAPSession

LDAP Server session.

The LDAP server session class that is used to send server LDAP messages.

bind_response(message_id, sasl_creds=None, result_code=LDAPResultCode.SUCCESS, matched_dn=None, diagnostics_message=None, controls=None)

Send a Bind Response.

Responds to a bind request. The state will be changed to OPENED unless the result code is SASL_BIND_IN_PROGRESS.

Parameters:
  • message_id (int) – The message id this is responding to.

  • sasl_creds (Optional[bytes]) – The SASL response credential needed for the client to complete the SASL authentication process.

  • result_code (LDAPResultCode) – The result code. The default is SUCCESS which means the bind was successful.

  • matched_dn (Optional[str]) – The subject the result is for. This is used for diagnostic purposes by the client when receiving an unsuccesful response.

  • diagnostics_message (Optional[str]) – A string containing a textual diagnostic message. This is not standardized and should not be parsed. It is used for display purposes only on the client.

  • controls (Optional[List[LDAPControl]]) – Optional server controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

extended_response(message_id, name=None, value=None, result_code=LDAPResultCode.SUCCESS, matched_dn=None, diagnostics_message=None, controls=None)

Send an Extended Response.

Responds to an extended request. The name and value are dependent on the extended request values. It is up to the caller to determine whether they need to be set on the response.

Parameters:
  • message_id (int) – The message id this is responding to.

  • name (Optional[str]) – The extended response OID string.

  • value (Optional[bytes]) – The extended response value.

  • result_code (LDAPResultCode) – The result code. The default is SUCCESS which means the bind was successful.

  • matched_dn (Optional[str]) – The subject the result is for. This is used for diagnostic purposes by the client when receiving an unsuccesful response.

  • diagnostics_message (Optional[str]) – A string containing a textual diagnostic message. This is not standardized and should not be parsed. It is used for display purposes only on the client.

  • controls (Optional[List[LDAPControl]]) – Optional server controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

receive(data)

Receive data to process.

Receives the data from the peer and unpack the messages found into LDAPMessages. Any complete LDAP messages received will be returned and any remaining data will be stored in an internal buffer.A ProtocolError indicates something fatal has occurred when trying to parse the incoming data and the connection is no longer in a valid state. The caller SHOULD send the notice of disconnection payload available in data_to_send() and MUST close the underlying connection.

Note

A ProtocolError is not raised when receiving a valid LDAP response with a result code that is not SUCCESS. Only critical errors where the session is no longer viable will raise this error.

Parameters:

data (Union[bytes, bytearray, memoryview]) – The data to process.

Returns:

A list of messages that have been unpacked.

Return type:

t.List[LDAPMessage]

Raises:

ProtocolError – A protocol violation occurred and the connection is no longer valid.

search_result_done(message_id, result_code=LDAPResultCode.SUCCESS, matched_dn=None, diagnostics_message=None, controls=None)

Finish a Search Operation.

This is the final search operation response that indicates to the client that the search is done and to expect no more responses for that operation.

Parameters:
  • message_id (int) – The message id this is responding to.

  • result_code (LDAPResultCode) – The result code. The default is SUCCESS which means the bind was successful.

  • matched_dn (Optional[str]) – The subject the result is for. This is used for diagnostic purposes by the client when receiving an unsuccesful response.

  • diagnostics_message (Optional[str]) – A string containing a textual diagnostic message. This is not standardized and should not be parsed. It is used for display purposes only on the client.

  • controls (Optional[List[LDAPControl]]) – Optional server controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

search_result_entry(message_id, object_name, attributes, controls=None)

Send a Search Result Entry Response.

Responds to a search request with an entry result. This contains the search results for the object specified. A search result can have more than 1 result entry depending on what is found. The search result is finalised when search_result_done() is called.

Parameters:
  • message_id (int) – The message id this is responding to.

  • object_name (str) – The object the entry is associated with.

  • attributes (List[PartialAttribute]) – List of attributes and their values.

  • controls (Optional[List[LDAPControl]]) – Optional server controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

search_result_reference(message_id, uris, controls=None)

Send a Search Result Reference.

Responds to a search request with a reference result. This is a result that indicates the server is unable, or unwilling, to search one or more non-local entries. The message contains reference(s) to one or more set of servers for the client to continue the operation.

Parameters:
  • message_id (int) – The message id this is responding to.

  • uris (List[str]) – The references for the client.

  • controls (Optional[List[LDAPControl]]) – Optional server controls to send with the request.

Returns:

The message id associated with the request.

Return type:

int

class sansldap.LDAPSession

Bases: object

LDAP Session.

The base class for a client and server LDAP session. It contains the common code needed to exchange LDAP messages.

state

The current session state.

version

The LDAP protocol version, currently this is only set to 3.

data_to_send(amount=None)

Get data to send to the peer.

Gets the data available in the outgoing buffer to send to the peer. If amount is not specified then the whole outgoing buffer is returned. Otherwise only the data up to the amount specified is returned.

Parameters:

amount (Optional[int]) – The length of the output to return, otherwise all data will be returned if None.

Returns:

The data to send to the peer.

Return type:

bytes

receive(data)

Receive data to process.

Receives the data from the peer and unpack the messages found into LDAPMessages. Any complete LDAP messages received will be returned and any remaining data will be stored in an internal buffer.A ProtocolError indicates something fatal has occurred when trying to parse the incoming data and the connection is no longer in a valid state. The caller SHOULD send the notice of disconnection payload available in data_to_send() and MUST close the underlying connection.

Note

A ProtocolError is not raised when receiving a valid LDAP response with a result code that is not SUCCESS. Only critical errors where the session is no longer viable will raise this error.

Parameters:

data (Union[bytes, bytearray, memoryview]) – The data to process.

Returns:

A list of messages that have been unpacked.

Return type:

t.List[LDAPMessage]

Raises:

ProtocolError – A protocol violation occurred and the connection is no longer valid.

register_auth_credential(auth)

Register a custom authentication credential.

Registers a custom AuthenticationCredential class that can be used for a bind.

Parameters:

auth (Type[AuthenticationCredential]) – The custom authentication credential type to register.

Return type:

None

register_control(control)

Register a custom LDAP control.

Registers a custom LDAPControl class that can be used for controls in a request/response.

Parameters:

control (Type[LDAPControl]) – The custom LDAP control type to register.

Return type:

None

register_filter(filter)

Register a custom LDAP filter

Registers a custom LDAPFilter class that can be used for a SearchRequest.

Parameters:

filter (Type[LDAPFilter]) – The custom LDAP filter type to register.

Return type:

None

unbind()

Send an unbind request.

Sends the UnbindRequest message to the peer. This will mark the state as closed and no more operations can be issued after calling this function. The caller should also close the TCP connection once sending the UnbindRequest payload. No response is expected for this request.

Return type:

None

class sansldap.PagedResultControl(critical, size, cookie)

Bases: _KnownControl

Control for Simple Paged Results.

An LDAP control used to perform simple paging of search results. It is sent by the client to control the rate at which an LDAP server returns the results of an LDAP search operation.

Parameters:
  • critical (bool) – Whether the control must be known by the server or not.

  • size (int) – The desired page size, this must be less than the size_limit set in a SearchRequest message.

  • cookie (bytes) – An opaque set of bytes used to identify the search operation as denoted by the server response.

control_type: str = '1.2.840.113556.1.4.319'
cookie: bytes
get_value(options)
Return type:

Optional[bytes]

size: int
classmethod unpack(control_type, critical, value, options)
Return type:

PagedResultControl

class sansldap.PartialAttribute(name, values)

Bases: object

The PartialAttribute object.

This is the object that contains the attribute description/name and values. The set of attribute values is unordered and implementations MUST NOT rely upon the ordering being repeatable. The PartialAttribute structure is defined in RFC 4511 4.1.7. Attribute and PartialAttribute.

Parameters:
  • name (str) – The attribute name.

  • values (List[bytes]) – The attribute values, this list may be empty if no values are set.

name: str
values: List[bytes]
exception sansldap.ProtocolError(msg, request=None, response=None)

Bases: LDAPError

Generic LDAP protocol errors.

An exception used to signal a fatal error during the LDAP session. It can be caused by trying to parse an invalid input message, from a Notice of Disconnection error from the server, or from an UnbindRequest. The caller should send the response data, if present, to the peer and then close the underlying connection upon receiving this error.

Parameters:
  • request (Optional[LDAPMessage]) – The incoming message that caused the protocol error, or None if the incoming data could not be unpacked.

  • response (Optional[bytes]) – Optional message to send to the peer to notify of it being disconnected.

class sansldap.SaslCredential(mechanism, credentials)

Bases: AuthenticationCredential

The SASL Credential.

This object is used to store the SASL credential for a BindRequest. It contains the SASL mechanism used and the credential byte string for that credential. The SaslCredentials structure is defined in RFC 4511 4.2. Bind Operation.

Parameters:
  • mechanism (str) – The SASL mechanism.

  • credentials (Optional[bytes]) – The SASL credential bytes to exchange, if any.

auth_id: int = 3

The authentication choice.

credentials: Optional[bytes]

The optional SASL credential bytes

is_primitive: bool = False

The authentication choice value is not primitive.

mechanism: str

The SASL mechanism.

pack(writer, options)

Pack the authentication structure.

Writes the authentication structure into the ASN.1 writer that is then embedded in the sansldap.BindRequest authentication value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data.

  • options (AuthenticationOptions) – Options that can be used to control how the authentication credential is packed.

Return type:

None

classmethod unpack(reader, options)

Unpacks the authentication bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (AuthenticationOptions) – Options that can be used to control how the authentication credential is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

AuthenticationCredential

class sansldap.SearchRequest(message_id, controls, base_object, scope, deref_aliases, size_limit, time_limit, types_only, filter, attributes)

Bases: LDAPMessage, Request

The search request message.

This object is used to start a search operation with the parameters requested. The SearchRequest structure is defined in RFC 4511 4.5.1. Search Request.

The LDAP filter is a special object that derives from LDAPFilter and is not the LDAP filter string most implementations use. See that class docstring for more information on how to build the LDAPFilter object.

The following are special attributes that can be requested:

*: Requests all attributes in addition to the explicitly defined

ones.

1.1: No attributes are to be returned. Is ignored if there are any

other attributes specified.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • base_object (str) – The name of the base object entry (or empty string for root) which the search is to be performed.

  • scope (SearchScope) – The scope of the search. See SearchScope for more details.

  • deref_aliases (DereferencingPolicy) – Indicates how alias entries are to be dereferenced, see DereferencingPolicy for more details.

  • size_limit (int) – Retricts the maximum number of entries to be returned. A value of 0 indicates no client requested size limit is in place. The server may also enforce a maximum number of entries to return.

  • time_limit (int) – The time limit, in seconds, allowed for a search. A value of 0 indicates no client requested time limit is in place. The server may enforce its own time limit for a search.

  • types_only (bool) – Set to True to only return attribute names and no values in the search result.

  • filter (LDAPFilter) – The LDAP filter to search by. See LDAPFilter for more information.

  • attributes (List[str]) – A list of attributes to be returned from each entry that matches the search filter. An empty list requests the return of all user attributes.

attributes: List[str]
base_object: str
deref_aliases: DereferencingPolicy
filter: LDAPFilter
scope: SearchScope
size_limit: int
tag_number: int = 3

The LDAP message protocol op tag.

time_limit: int
types_only: bool
class sansldap.SearchResultDone(message_id, controls, result)

Bases: LDAPMessage, Response

The search result done message.

This object is used as a response to a search request and marks the end of any results for a search operation. The SearchResultDone structure is defined in RFC 4511 4.5.2. Search Result.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • result (LDAPResult) – The LDAP result of the search operation.

result: LDAPResult
tag_number: int = 5

The LDAP message protocol op tag.

class sansldap.SearchResultEntry(message_id, controls, object_name, attributes)

Bases: LDAPMessage, Response

The search result entry message.

This object is used as a response to a search request. The SearchResultEntry structure is defined in RFC 4511 4.5.2. Search Result.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • object_name (str) – The object the result is associated with.

  • attributes (List[PartialAttribute]) – A list of attributes and their values.

attributes: List[PartialAttribute]
object_name: str
tag_number: int = 4

The LDAP message protocol op tag.

class sansldap.SearchResultReference(message_id, controls, uris)

Bases: LDAPMessage, Response

The search result reference message.

Sent by the server in a search request operation when it is unable, or unwilling, to search one or more non-local entries. The result reference contains reference(s) to one or more set of server for continuing the operation. The SearchResultReference structure is defined in RFC 4511 4.5.2. Search Result.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

  • uris (List[str]) – The URIs of servers that can be used to continue the search. The URI may be an ldap:// URI but the syntax is not part of this library to interpret.

tag_number: int = 19

The LDAP message protocol op tag.

uris: List[str]
class sansldap.SearchScope(value)

Bases: IntEnum

Specifies the scope of the search to perform.

BASE = 0

The scope is constrained to the entry named by base_object

ONE_LEVEL = 1

The scope is constrained to the immediate subordinates of base_object.

SUBTREE = 2

The scope is constrained to base_object and all its subordinates.

class sansldap.SessionState(value)

Bases: Enum

The state of the LDAP session.

A new LDAPSession will start with the BEFORE_OPEN state and can send any message to the peer.

The BINDING state occurs when the client sends a BindRequest or the server receives that request. Only a BindRequest or BindResponse can be sent when BINDING. Once the client receives or the server sends a successful BindResponse the state is changed to OPENED.

The OPENED state either occurs after a successful bind operation occurs or when the first message is sent by the client or received by the server that is not a BindRequest/BindResponse.

The CLOSED state occurs when an UnbindRequest is sent/received, an invalid payload is received, or a Notice of Disconnection is send/received. Once in this state the session can no longer be used.

BEFORE_OPEN = 1

The session has not been opened and no messages were created or received.

BINDING = 2

The session is currently going through a binding operation.

CLOSED = 4

The session has been closed either from an Unbind or ProtocolError.

OPENED = 3

The session has been opened and a message sent or received.

class sansldap.ShowDeactivatedLinkControl(critical)

Bases: _KnownControl

LDAP Show Deactivated Control

Microsoft specific control that is used to specify that link attributes that refer to deleted objects are visible to the search operation. This control has no value set.

control_type: str = '1.2.840.113556.1.4.2065'
classmethod unpack(control_type, critical, value, options)
Return type:

ShowDeactivatedLinkControl

class sansldap.ShowDeletedControl(critical)

Bases: _KnownControl

LDAP Show Deleted Control.

Microsoft specific control that is used search tombstoned or deleted object during a search operation. This control has no value set.

control_type: str = '1.2.840.113556.1.4.417'
classmethod unpack(control_type, critical, value, options)
Return type:

ShowDeletedControl

class sansldap.SimpleCredential(password)

Bases: AuthenticationCredential

The Simple Credential.

This object is used to encode the simple password for a BindRequest.

Parameters:

password (str) – The password to authenticate with or an empty string for an identity only, or anonymous, bind operation.

auth_id: int = 0

The authentication choice value. Reflects the choice tag encoded in the ASN.1 value and should be set with a default value in inheriting classes.

pack(writer, options)

Pack the authentication structure.

Writes the authentication structure into the ASN.1 writer that is then embedded in the sansldap.BindRequest authentication value. The tagged choice should also be included in the written value.

Parameters:
  • writer (ASN1Writer) – The writer used to write ASN.1 data.

  • options (AuthenticationOptions) – Options that can be used to control how the authentication credential is packed.

Return type:

None

password: str
classmethod unpack(reader, options)

Unpacks the authentication bytes.

Unpacks the raw bytes into the Python object.

Parameters:
  • reader (ASN1Reader) – The reader used to read the ASN.1 data.

  • options (AuthenticationOptions) – Options that can be used to control how the authentication credential is unpacked.

Returns:

An instance of the object that has been unpacked.

Return type:

AuthenticationCredential

class sansldap.UnbindRequest(message_id, controls)

Bases: LDAPMessage, Request

The unbind request message.

A message used to signal the LDAP session is to be terminated. There is no response as the client or server will terminate the connection after sending. The UnbindRequest structure is defined in RFC 4511 4.3. Unbind Operation.

Parameters:
  • message_id (int) – The unique identifier for the request.

  • controls (List[LDAPControl]) – A list of controls associated with the message.

controls: List[LDAPControl]
message_id: int
tag_number: int = 2

The LDAP message protocol op tag.