ldap

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 22 Imported by: 1

README

ldap-verify

This is a fork of go-ldap/ldap plus a draft PR branch to add context, a couple more context-aware methods added, and a ton ripped out so no one else starts to depend on this.

The only intent is to be able to connect and test the most basic bind with a context, it's not adequate for a full authentication library or general ldap use.

Documentation

Overview

Package ldap provides basic LDAP v3 functionality.

Index

Constants

View Source
const (
	// MessageQuit causes the processMessages loop to exit
	MessageQuit = 0
	// MessageRequest sends a request to the server
	MessageRequest = 1
	// MessageResponse receives a response from the server
	MessageResponse = 2
	// MessageFinish indicates the client considers a particular message ID to be finished
	MessageFinish = 3
	// MessageTimeout indicates the client-specified timeout for a particular message ID has been reached
	MessageTimeout = 4
)
View Source
const (
	// DefaultLdapPort default ldap port for pure TCP connection
	DefaultLdapPort = "389"
	// DefaultLdapsPort default ldap port for SSL connection
	DefaultLdapsPort = "636"
)
View Source
const (
	// ControlTypePaging - https://www.ietf.org/rfc/rfc2696.txt
	ControlTypePaging = "1.2.840.113556.1.4.319"
	// ControlTypeBeheraPasswordPolicy - https://tools.ietf.org/html/draft-behera-ldap-password-policy-10
	ControlTypeBeheraPasswordPolicy = "1.3.6.1.4.1.42.2.27.8.5.1"
	// ControlTypeVChuPasswordMustChange - https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00
	ControlTypeVChuPasswordMustChange = "2.16.840.1.113730.3.4.4"
	// ControlTypeVChuPasswordWarning - https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00
	ControlTypeVChuPasswordWarning = "2.16.840.1.113730.3.4.5"
	// ControlTypeManageDsaIT - https://tools.ietf.org/html/rfc3296
	ControlTypeManageDsaIT = "2.16.840.1.113730.3.4.2"
	// ControlTypeWhoAmI - https://tools.ietf.org/html/rfc4532
	ControlTypeWhoAmI = "1.3.6.1.4.1.4203.1.11.3"
	// ControlTypeSubTreeDelete - https://datatracker.ietf.org/doc/html/draft-armijo-ldap-treedelete-02
	ControlTypeSubtreeDelete = "1.2.840.113556.1.4.805"

	// ControlTypeMicrosoftNotification - https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx
	ControlTypeMicrosoftNotification = "1.2.840.113556.1.4.528"
	// ControlTypeMicrosoftShowDeleted - https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx
	ControlTypeMicrosoftShowDeleted = "1.2.840.113556.1.4.417"
	// ControlTypeMicrosoftServerLinkTTL - https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f4f523a8-abc0-4b3a-a471-6b2fef135481?redirectedfrom=MSDN
	ControlTypeMicrosoftServerLinkTTL = "1.2.840.113556.1.4.2309"
)
View Source
const (
	LDAPResultSuccess                            = 0
	LDAPResultOperationsError                    = 1
	LDAPResultProtocolError                      = 2
	LDAPResultTimeLimitExceeded                  = 3
	LDAPResultSizeLimitExceeded                  = 4
	LDAPResultCompareFalse                       = 5
	LDAPResultCompareTrue                        = 6
	LDAPResultAuthMethodNotSupported             = 7
	LDAPResultStrongAuthRequired                 = 8
	LDAPResultReferral                           = 10
	LDAPResultAdminLimitExceeded                 = 11
	LDAPResultUnavailableCriticalExtension       = 12
	LDAPResultConfidentialityRequired            = 13
	LDAPResultSaslBindInProgress                 = 14
	LDAPResultNoSuchAttribute                    = 16
	LDAPResultUndefinedAttributeType             = 17
	LDAPResultInappropriateMatching              = 18
	LDAPResultConstraintViolation                = 19
	LDAPResultAttributeOrValueExists             = 20
	LDAPResultInvalidAttributeSyntax             = 21
	LDAPResultNoSuchObject                       = 32
	LDAPResultAliasProblem                       = 33
	LDAPResultInvalidDNSyntax                    = 34
	LDAPResultIsLeaf                             = 35
	LDAPResultAliasDereferencingProblem          = 36
	LDAPResultInappropriateAuthentication        = 48
	LDAPResultInvalidCredentials                 = 49
	LDAPResultInsufficientAccessRights           = 50
	LDAPResultBusy                               = 51
	LDAPResultUnavailable                        = 52
	LDAPResultUnwillingToPerform                 = 53
	LDAPResultLoopDetect                         = 54
	LDAPResultSortControlMissing                 = 60
	LDAPResultOffsetRangeError                   = 61
	LDAPResultNamingViolation                    = 64
	LDAPResultObjectClassViolation               = 65
	LDAPResultNotAllowedOnNonLeaf                = 66
	LDAPResultNotAllowedOnRDN                    = 67
	LDAPResultEntryAlreadyExists                 = 68
	LDAPResultObjectClassModsProhibited          = 69
	LDAPResultResultsTooLarge                    = 70
	LDAPResultAffectsMultipleDSAs                = 71
	LDAPResultVirtualListViewErrorOrControlError = 76
	LDAPResultOther                              = 80
	LDAPResultServerDown                         = 81
	LDAPResultLocalError                         = 82
	LDAPResultEncodingError                      = 83
	LDAPResultDecodingError                      = 84
	LDAPResultTimeout                            = 85
	LDAPResultAuthUnknown                        = 86
	LDAPResultFilterError                        = 87
	LDAPResultUserCanceled                       = 88
	LDAPResultParamError                         = 89
	LDAPResultNoMemory                           = 90
	LDAPResultConnectError                       = 91
	LDAPResultNotSupported                       = 92
	LDAPResultControlNotFound                    = 93
	LDAPResultNoResultsReturned                  = 94
	LDAPResultMoreResultsToReturn                = 95
	LDAPResultClientLoop                         = 96
	LDAPResultReferralLimitExceeded              = 97
	LDAPResultInvalidResponse                    = 100
	LDAPResultAmbiguousResponse                  = 101
	LDAPResultTLSNotSupported                    = 112
	LDAPResultIntermediateResponse               = 113
	LDAPResultUnknownType                        = 114
	LDAPResultCanceled                           = 118
	LDAPResultNoSuchOperation                    = 119
	LDAPResultTooLate                            = 120
	LDAPResultCannotCancel                       = 121
	LDAPResultAssertionFailed                    = 122
	LDAPResultAuthorizationDenied                = 123
	LDAPResultSyncRefreshRequired                = 4096

	ErrorNetwork            = 200
	ErrorFilterCompile      = 201
	ErrorFilterDecompile    = 202
	ErrorDebugging          = 203
	ErrorUnexpectedMessage  = 204
	ErrorUnexpectedResponse = 205
	ErrorEmptyPassword      = 206
)

LDAP Result Codes

View Source
const (
	ApplicationBindRequest           = 0
	ApplicationBindResponse          = 1
	ApplicationUnbindRequest         = 2
	ApplicationSearchRequest         = 3
	ApplicationSearchResultEntry     = 4
	ApplicationSearchResultDone      = 5
	ApplicationModifyRequest         = 6
	ApplicationModifyResponse        = 7
	ApplicationAddRequest            = 8
	ApplicationAddResponse           = 9
	ApplicationDelRequest            = 10
	ApplicationDelResponse           = 11
	ApplicationModifyDNRequest       = 12
	ApplicationModifyDNResponse      = 13
	ApplicationCompareRequest        = 14
	ApplicationCompareResponse       = 15
	ApplicationAbandonRequest        = 16
	ApplicationSearchResultReference = 19
	ApplicationExtendedRequest       = 23
	ApplicationExtendedResponse      = 24
)

LDAP Application Codes

View Source
const (
	BeheraPasswordExpired             = 0
	BeheraAccountLocked               = 1
	BeheraChangeAfterReset            = 2
	BeheraPasswordModNotAllowed       = 3
	BeheraMustSupplyOldPassword       = 4
	BeheraInsufficientPasswordQuality = 5
	BeheraPasswordTooShort            = 6
	BeheraPasswordTooYoung            = 7
	BeheraPasswordInHistory           = 8
)

Ldap Behera Password Policy Draft 10 (https://tools.ietf.org/html/draft-behera-ldap-password-policy-10)

Variables

View Source
var ApplicationMap = map[uint8]string{
	ApplicationBindRequest:           "Bind Request",
	ApplicationBindResponse:          "Bind Response",
	ApplicationUnbindRequest:         "Unbind Request",
	ApplicationSearchRequest:         "Search Request",
	ApplicationSearchResultEntry:     "Search Result Entry",
	ApplicationSearchResultDone:      "Search Result Done",
	ApplicationModifyRequest:         "Modify Request",
	ApplicationModifyResponse:        "Modify Response",
	ApplicationAddRequest:            "Add Request",
	ApplicationAddResponse:           "Add Response",
	ApplicationDelRequest:            "Del Request",
	ApplicationDelResponse:           "Del Response",
	ApplicationModifyDNRequest:       "Modify DN Request",
	ApplicationModifyDNResponse:      "Modify DN Response",
	ApplicationCompareRequest:        "Compare Request",
	ApplicationCompareResponse:       "Compare Response",
	ApplicationAbandonRequest:        "Abandon Request",
	ApplicationSearchResultReference: "Search Result Reference",
	ApplicationExtendedRequest:       "Extended Request",
	ApplicationExtendedResponse:      "Extended Response",
}

ApplicationMap contains human readable descriptions of LDAP Application Codes

View Source
var BeheraPasswordPolicyErrorMap = map[int8]string{
	BeheraPasswordExpired:             "Password expired",
	BeheraAccountLocked:               "Account locked",
	BeheraChangeAfterReset:            "Password must be changed",
	BeheraPasswordModNotAllowed:       "Policy prevents password modification",
	BeheraMustSupplyOldPassword:       "Policy requires old password in order to change password",
	BeheraInsufficientPasswordQuality: "Password fails quality checks",
	BeheraPasswordTooShort:            "Password is too short for policy",
	BeheraPasswordTooYoung:            "Password has been changed too recently",
	BeheraPasswordInHistory:           "New password is in list of old passwords",
}

BeheraPasswordPolicyErrorMap contains human readable descriptions of Behera Password Policy error codes

View Source
var ControlTypeMap = map[string]string{
	ControlTypePaging:                 "Paging",
	ControlTypeBeheraPasswordPolicy:   "Password Policy - Behera Draft",
	ControlTypeManageDsaIT:            "Manage DSA IT",
	ControlTypeSubtreeDelete:          "Subtree Delete Control",
	ControlTypeMicrosoftNotification:  "Change Notification - Microsoft",
	ControlTypeMicrosoftShowDeleted:   "Show Deleted Objects - Microsoft",
	ControlTypeMicrosoftServerLinkTTL: "Return TTL-DNs for link values with associated expiry times - Microsoft",
}

ControlTypeMap maps controls to text descriptions

View Source
var DefaultTimeout = 60 * time.Second

DefaultTimeout is a package-level variable that sets the timeout value used for the Dial and DialTLS methods.

WARNING: since this is a package-level variable, setting this value from multiple places will probably result in undesired behaviour.

View Source
var ErrConnUnbound = NewError(ErrorNetwork, errors.New("ldap: connection is closed"))
View Source
var (
	ErrNilConnection = errors.New("ldap: conn is nil, expected net.Conn")
)
View Source
var LDAPResultCodeMap = map[uint16]string{
	LDAPResultSuccess:                            "Success",
	LDAPResultOperationsError:                    "Operations Error",
	LDAPResultProtocolError:                      "Protocol Error",
	LDAPResultTimeLimitExceeded:                  "Time Limit Exceeded",
	LDAPResultSizeLimitExceeded:                  "Size Limit Exceeded",
	LDAPResultCompareFalse:                       "Compare False",
	LDAPResultCompareTrue:                        "Compare True",
	LDAPResultAuthMethodNotSupported:             "Auth Method Not Supported",
	LDAPResultStrongAuthRequired:                 "Strong Auth Required",
	LDAPResultReferral:                           "Referral",
	LDAPResultAdminLimitExceeded:                 "Admin Limit Exceeded",
	LDAPResultUnavailableCriticalExtension:       "Unavailable Critical Extension",
	LDAPResultConfidentialityRequired:            "Confidentiality Required",
	LDAPResultSaslBindInProgress:                 "Sasl Bind In Progress",
	LDAPResultNoSuchAttribute:                    "No Such Attribute",
	LDAPResultUndefinedAttributeType:             "Undefined Attribute Type",
	LDAPResultInappropriateMatching:              "Inappropriate Matching",
	LDAPResultConstraintViolation:                "Constraint Violation",
	LDAPResultAttributeOrValueExists:             "Attribute Or Value Exists",
	LDAPResultInvalidAttributeSyntax:             "Invalid Attribute Syntax",
	LDAPResultNoSuchObject:                       "No Such Object",
	LDAPResultAliasProblem:                       "Alias Problem",
	LDAPResultInvalidDNSyntax:                    "Invalid DN Syntax",
	LDAPResultIsLeaf:                             "Is Leaf",
	LDAPResultAliasDereferencingProblem:          "Alias Dereferencing Problem",
	LDAPResultInappropriateAuthentication:        "Inappropriate Authentication",
	LDAPResultInvalidCredentials:                 "Invalid Credentials",
	LDAPResultInsufficientAccessRights:           "Insufficient Access Rights",
	LDAPResultBusy:                               "Busy",
	LDAPResultUnavailable:                        "Unavailable",
	LDAPResultUnwillingToPerform:                 "Unwilling To Perform",
	LDAPResultLoopDetect:                         "Loop Detect",
	LDAPResultSortControlMissing:                 "Sort Control Missing",
	LDAPResultOffsetRangeError:                   "Result Offset Range Error",
	LDAPResultNamingViolation:                    "Naming Violation",
	LDAPResultObjectClassViolation:               "Object Class Violation",
	LDAPResultResultsTooLarge:                    "Results Too Large",
	LDAPResultNotAllowedOnNonLeaf:                "Not Allowed On Non Leaf",
	LDAPResultNotAllowedOnRDN:                    "Not Allowed On RDN",
	LDAPResultEntryAlreadyExists:                 "Entry Already Exists",
	LDAPResultObjectClassModsProhibited:          "Object Class Mods Prohibited",
	LDAPResultAffectsMultipleDSAs:                "Affects Multiple DSAs",
	LDAPResultVirtualListViewErrorOrControlError: "Failed because of a problem related to the virtual list view",
	LDAPResultOther:                              "Other",
	LDAPResultServerDown:                         "Cannot establish a connection",
	LDAPResultLocalError:                         "An error occurred",
	LDAPResultEncodingError:                      "LDAP encountered an error while encoding",
	LDAPResultDecodingError:                      "LDAP encountered an error while decoding",
	LDAPResultTimeout:                            "LDAP timeout while waiting for a response from the server",
	LDAPResultAuthUnknown:                        "The auth method requested in a bind request is unknown",
	LDAPResultFilterError:                        "An error occurred while encoding the given search filter",
	LDAPResultUserCanceled:                       "The user canceled the operation",
	LDAPResultParamError:                         "An invalid parameter was specified",
	LDAPResultNoMemory:                           "Out of memory error",
	LDAPResultConnectError:                       "A connection to the server could not be established",
	LDAPResultNotSupported:                       "An attempt has been made to use a feature not supported LDAP",
	LDAPResultControlNotFound:                    "The controls required to perform the requested operation were not found",
	LDAPResultNoResultsReturned:                  "No results were returned from the server",
	LDAPResultMoreResultsToReturn:                "There are more results in the chain of results",
	LDAPResultClientLoop:                         "A loop has been detected. For example when following referrals",
	LDAPResultReferralLimitExceeded:              "The referral hop limit has been exceeded",
	LDAPResultCanceled:                           "Operation was canceled",
	LDAPResultNoSuchOperation:                    "Server has no knowledge of the operation requested for cancellation",
	LDAPResultTooLate:                            "Too late to cancel the outstanding operation",
	LDAPResultCannotCancel:                       "The identified operation does not support cancellation or the cancel operation cannot be performed",
	LDAPResultAssertionFailed:                    "An assertion control given in the LDAP operation evaluated to false causing the operation to not be performed",
	LDAPResultSyncRefreshRequired:                "Refresh Required",
	LDAPResultInvalidResponse:                    "Invalid Response",
	LDAPResultAmbiguousResponse:                  "Ambiguous Response",
	LDAPResultTLSNotSupported:                    "Tls Not Supported",
	LDAPResultIntermediateResponse:               "Intermediate Response",
	LDAPResultUnknownType:                        "Unknown Type",
	LDAPResultAuthorizationDenied:                "Authorization Denied",

	ErrorNetwork:            "Network Error",
	ErrorFilterCompile:      "Filter Compile Error",
	ErrorFilterDecompile:    "Filter Decompile Error",
	ErrorDebugging:          "Debugging Error",
	ErrorUnexpectedMessage:  "Unexpected Message",
	ErrorUnexpectedResponse: "Unexpected Response",
	ErrorEmptyPassword:      "Empty password not allowed by the client",
}

LDAPResultCodeMap contains string descriptions for LDAP error codes

Functions

func DebugBinaryFile

func DebugBinaryFile(fileName string) error

DebugBinaryFile reads and prints packets from the given filename

func EscapeDN

func EscapeDN(dn string) string

EscapeDN escapes distinguished names as described in RFC4514. Characters in the set `"+,;<>\` are escaped by prepending a backslash, which is also done for trailing spaces or a leading `#`. Null bytes are replaced with `\00`.

func EscapeFilter

func EscapeFilter(filter string) string

EscapeFilter escapes from the provided LDAP filter string the special characters in the set `()*\` and those out of the range 0 < c < 0x80, as defined in RFC4515.

func GetLDAPError

func GetLDAPError(packet *ber.Packet) error

GetLDAPError creates an Error out of a BER packet representing a LDAPResult The return is an error object. It can be casted to a Error structure. This function returns nil if resultCode in the LDAPResult sequence is success(0).

func IsErrorAnyOf

func IsErrorAnyOf(err error, codes ...uint16) bool

IsErrorAnyOf returns true if the given error is an LDAP error with any one of the given result codes

func IsErrorWithCode

func IsErrorWithCode(err error, desiredResultCode uint16) bool

IsErrorWithCode returns true if the given error is an LDAP error with the given result code

func Logger

func Logger(l *log.Logger)

Logger allows clients to override the default logger

func NewError

func NewError(resultCode uint16, err error) error

NewError creates an LDAP error with the given code and underlying error

Types

type AttributeTypeAndValue

type AttributeTypeAndValue struct {
	// Type is the attribute type
	Type string
	// Value is the attribute value
	Value string
}

AttributeTypeAndValue represents an attributeTypeAndValue from https://tools.ietf.org/html/rfc4514

func (*AttributeTypeAndValue) Equal

Equal returns true if the AttributeTypeAndValue is equivalent to the specified AttributeTypeAndValue Case of the attribute type is not significant

func (*AttributeTypeAndValue) EqualFold

func (a *AttributeTypeAndValue) EqualFold(other *AttributeTypeAndValue) bool

EqualFold returns true if the AttributeTypeAndValue is equivalent to the specified AttributeTypeAndValue Case of the attribute type and value is not significant

func (*AttributeTypeAndValue) String

func (a *AttributeTypeAndValue) String() string

String returns a normalized string representation of this attribute type and value pair which is the a lowercased join of the Type and Value with a "=".

type Client

type Client interface {
	Start()
	StartTLS(*tls.Config) error
	Close()
	IsClosing() bool
	SetTimeout(time.Duration)
	TLSConnectionState() (tls.ConnectionState, bool)

	Bind(username, password string) error
	BindContext(ctx context.Context, username, password string) error
	SimpleBind(*SimpleBindRequest) (*SimpleBindResult, error)
	SimpleBindContext(ctx context.Context, req *SimpleBindRequest) (*SimpleBindResult, error)
	Unbind() error
}

Client knows how to interact with an LDAP server

type Conn

type Conn struct {
	Debug debugging
	// contains filtered or unexported fields
}

Conn represents an LDAP Connection

func Dial

func Dial(network, addr string) (*Conn, error)

Dial connects to the given address on the given network using net.Dial and then returns a new Conn for the connection. @deprecated Use DialURL instead.

func DialTLS

func DialTLS(network, addr string, config *tls.Config) (*Conn, error)

DialTLS connects to the given address on the given network using tls.Dial and then returns a new Conn for the connection. @deprecated Use DialURL instead.

func DialURL

func DialURL(addr string, opts ...DialOpt) (*Conn, error)

DialURL connects to the given ldap URL. The following schemas are supported: ldap://, ldaps://, ldapi://, and cldap:// (RFC1798, deprecated but used by Active Directory). On success a new Conn for the connection is returned.

func NewConn

func NewConn(conn net.Conn, isTLS bool) *Conn

NewConn returns a new Conn using conn for network I/O.

func (*Conn) Bind

func (l *Conn) Bind(username, password string) error

Bind performs a bind with the given username and password.

It does not allow unauthenticated bind (i.e. empty password). Use the UnauthenticatedBind method for that.

func (*Conn) BindContext

func (l *Conn) BindContext(ctx context.Context, username, password string) error

func (*Conn) Close

func (l *Conn) Close()

Close closes the connection.

func (*Conn) DigestMD5Bind

func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*DigestMD5BindResult, error)

DigestMD5Bind performs the digest-md5 bind operation defined in the given request

func (*Conn) ExternalBind

func (l *Conn) ExternalBind() error

ExternalBind performs SASL/EXTERNAL authentication.

Use ldap.DialURL("ldapi://") to connect to the Unix socket before ExternalBind.

See https://tools.ietf.org/html/rfc4422#appendix-A

func (*Conn) GSSAPIBind

func (l *Conn) GSSAPIBind(client GSSAPIClient, servicePrincipal, authzid string) error

GSSAPIBind performs the GSSAPI SASL bind using the provided GSSAPI client.

func (*Conn) GSSAPIBindRequest

func (l *Conn) GSSAPIBindRequest(client GSSAPIClient, req *GSSAPIBindRequest) error

GSSAPIBindRequest performs the GSSAPI SASL bind using the provided GSSAPI client.

func (*Conn) IsClosing

func (l *Conn) IsClosing() bool

IsClosing returns whether or not we're currently closing.

func (*Conn) MD5Bind

func (l *Conn) MD5Bind(host, username, password string) error

MD5Bind performs a digest-md5 bind with the given host, username and password.

func (*Conn) NTLMBind

func (l *Conn) NTLMBind(domain, username, password string) error

NTLMBind performs an NTLMSSP Bind with the given domain, username and password

func (*Conn) NTLMBindWithHash

func (l *Conn) NTLMBindWithHash(domain, username, hash string) error

NTLMBindWithHash performs an NTLM Bind with an NTLM hash instead of plaintext password (pass-the-hash)

func (*Conn) NTLMChallengeBind

func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindResult, error)

NTLMChallengeBind performs the NTLMSSP bind operation defined in the given request

func (*Conn) NTLMUnauthenticatedBind

func (l *Conn) NTLMUnauthenticatedBind(domain, username string) error

NTLMUnauthenticatedBind performs an bind with an empty password.

A username is required. The anonymous bind is not (yet) supported by the go-ntlmssp library (https://github.com/Azure/go-ntlmssp/blob/819c794454d067543bc61d29f61fef4b3c3df62c/authenticate_message.go#L87)

See https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/b38c36ed-2804-4868-a9ff-8dd3182128e4 part 3.2.5.1.2

func (*Conn) SetTimeout

func (l *Conn) SetTimeout(timeout time.Duration)

SetTimeout sets the time after a request is sent that a MessageTimeout triggers @deprecated Use context.Context parameters instead.

func (*Conn) SimpleBind

func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error)

SimpleBind performs the simple bind operation defined in the given request

func (*Conn) SimpleBindContext

func (l *Conn) SimpleBindContext(ctx context.Context, simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error)

func (*Conn) Start

func (l *Conn) Start()

StartContext initializes goroutines to read responses and process messages.

func (*Conn) StartContext

func (l *Conn) StartContext(ctx context.Context)

StartContext initializes goroutines to read responses and process messages. They will be terminated if the context is cancelled.

func (*Conn) StartTLS

func (l *Conn) StartTLS(config *tls.Config) error

StartTLS sends the command to start a TLS session and then creates a new TLS Client

func (*Conn) TLSConnectionState

func (l *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool)

TLSConnectionState returns the client's TLS connection state. The return values are their zero values if StartTLS did not succeed.

func (*Conn) UnauthenticatedBind

func (l *Conn) UnauthenticatedBind(username string) error

UnauthenticatedBind performs an unauthenticated bind.

A username may be provided for trace (e.g. logging) purpose only, but it is normally not authenticated or otherwise validated by the LDAP server.

See https://tools.ietf.org/html/rfc4513#section-5.1.2 . See https://tools.ietf.org/html/rfc4513#section-6.3.1 .

func (*Conn) Unbind

func (l *Conn) Unbind() error

Unbind will perform an unbind request. The Unbind operation should be thought of as the "quit" operation. See https://datatracker.ietf.org/doc/html/rfc4511#section-4.3

func (*Conn) WhoAmI

func (l *Conn) WhoAmI(controls []Control) (*WhoAmIResult, error)

WhoAmI returns the authzId the server thinks we are, you may pass controls like a Proxied Authorization control

type Control

type Control interface {
	// GetControlType returns the OID
	GetControlType() string
	// Encode returns the ber packet representation
	Encode() *ber.Packet
	// String returns a human-readable description
	String() string
}

Control defines an interface controls provide to encode and describe themselves

func DecodeControl

func DecodeControl(packet *ber.Packet) (Control, error)

DecodeControl returns a control read from the given packet, or nil if no recognized control can be made

func FindControl

func FindControl(controls []Control, controlType string) Control

FindControl returns the first control of the given type in the list, or nil

type ControlBeheraPasswordPolicy

type ControlBeheraPasswordPolicy struct {
	// Expire contains the number of seconds before a password will expire
	Expire int64
	// Grace indicates the remaining number of times a user will be allowed to authenticate with an expired password
	Grace int64
	// Error indicates the error code
	Error int8
	// ErrorString is a human readable error
	ErrorString string
}

ControlBeheraPasswordPolicy implements the control described in https://tools.ietf.org/html/draft-behera-ldap-password-policy-10

func NewControlBeheraPasswordPolicy

func NewControlBeheraPasswordPolicy() *ControlBeheraPasswordPolicy

NewControlBeheraPasswordPolicy returns a ControlBeheraPasswordPolicy

func (*ControlBeheraPasswordPolicy) Encode

func (c *ControlBeheraPasswordPolicy) Encode() *ber.Packet

Encode returns the ber packet representation

func (*ControlBeheraPasswordPolicy) GetControlType

func (c *ControlBeheraPasswordPolicy) GetControlType() string

GetControlType returns the OID

func (*ControlBeheraPasswordPolicy) String

func (c *ControlBeheraPasswordPolicy) String() string

String returns a human-readable description

type ControlManageDsaIT

type ControlManageDsaIT struct {
	// Criticality indicates if this control is required
	Criticality bool
}

ControlManageDsaIT implements the control described in https://tools.ietf.org/html/rfc3296

func NewControlManageDsaIT

func NewControlManageDsaIT(Criticality bool) *ControlManageDsaIT

NewControlManageDsaIT returns a ControlManageDsaIT control

func (*ControlManageDsaIT) Encode

func (c *ControlManageDsaIT) Encode() *ber.Packet

Encode returns the ber packet representation

func (*ControlManageDsaIT) GetControlType

func (c *ControlManageDsaIT) GetControlType() string

GetControlType returns the OID

func (*ControlManageDsaIT) String

func (c *ControlManageDsaIT) String() string

String returns a human-readable description

type ControlMicrosoftNotification

type ControlMicrosoftNotification struct{}

ControlMicrosoftNotification implements the control described in https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx

func NewControlMicrosoftNotification

func NewControlMicrosoftNotification() *ControlMicrosoftNotification

NewControlMicrosoftNotification returns a ControlMicrosoftNotification control

func (*ControlMicrosoftNotification) Encode

Encode returns the ber packet representation

func (*ControlMicrosoftNotification) GetControlType

func (c *ControlMicrosoftNotification) GetControlType() string

GetControlType returns the OID

func (*ControlMicrosoftNotification) String

String returns a human-readable description

type ControlMicrosoftServerLinkTTL

type ControlMicrosoftServerLinkTTL struct{}

ControlMicrosoftServerLinkTTL implements the control described in https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f4f523a8-abc0-4b3a-a471-6b2fef135481?redirectedfrom=MSDN

func NewControlMicrosoftServerLinkTTL

func NewControlMicrosoftServerLinkTTL() *ControlMicrosoftServerLinkTTL

NewControlMicrosoftServerLinkTTL returns a ControlMicrosoftServerLinkTTL control

func (*ControlMicrosoftServerLinkTTL) Encode

Encode returns the ber packet representation

func (*ControlMicrosoftServerLinkTTL) GetControlType

func (c *ControlMicrosoftServerLinkTTL) GetControlType() string

GetControlType returns the OID

func (*ControlMicrosoftServerLinkTTL) String

String returns a human-readable description

type ControlMicrosoftShowDeleted

type ControlMicrosoftShowDeleted struct{}

ControlMicrosoftShowDeleted implements the control described in https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx

func NewControlMicrosoftShowDeleted

func NewControlMicrosoftShowDeleted() *ControlMicrosoftShowDeleted

NewControlMicrosoftShowDeleted returns a ControlMicrosoftShowDeleted control

func (*ControlMicrosoftShowDeleted) Encode

func (c *ControlMicrosoftShowDeleted) Encode() *ber.Packet

Encode returns the ber packet representation

func (*ControlMicrosoftShowDeleted) GetControlType

func (c *ControlMicrosoftShowDeleted) GetControlType() string

GetControlType returns the OID

func (*ControlMicrosoftShowDeleted) String

func (c *ControlMicrosoftShowDeleted) String() string

String returns a human-readable description

type ControlPaging

type ControlPaging struct {
	// PagingSize indicates the page size
	PagingSize uint32
	// Cookie is an opaque value returned by the server to track a paging cursor
	Cookie []byte
}

ControlPaging implements the paging control described in https://www.ietf.org/rfc/rfc2696.txt

func NewControlPaging

func NewControlPaging(pagingSize uint32) *ControlPaging

NewControlPaging returns a paging control

func (*ControlPaging) Encode

func (c *ControlPaging) Encode() *ber.Packet

Encode returns the ber packet representation

func (*ControlPaging) GetControlType

func (c *ControlPaging) GetControlType() string

GetControlType returns the OID

func (*ControlPaging) SetCookie

func (c *ControlPaging) SetCookie(cookie []byte)

SetCookie stores the given cookie in the paging control

func (*ControlPaging) String

func (c *ControlPaging) String() string

String returns a human-readable description

type ControlString

type ControlString struct {
	ControlType  string
	Criticality  bool
	ControlValue string
}

ControlString implements the Control interface for simple controls

func NewControlString

func NewControlString(controlType string, criticality bool, controlValue string) *ControlString

NewControlString returns a generic control

func (*ControlString) Encode

func (c *ControlString) Encode() *ber.Packet

Encode returns the ber packet representation

func (*ControlString) GetControlType

func (c *ControlString) GetControlType() string

GetControlType returns the OID

func (*ControlString) String

func (c *ControlString) String() string

String returns a human-readable description

type ControlSubtreeDelete

type ControlSubtreeDelete struct{}

func NewControlSubtreeDelete

func NewControlSubtreeDelete() *ControlSubtreeDelete

func (*ControlSubtreeDelete) Encode

func (c *ControlSubtreeDelete) Encode() *ber.Packet

func (*ControlSubtreeDelete) GetControlType

func (c *ControlSubtreeDelete) GetControlType() string

func (*ControlSubtreeDelete) String

func (c *ControlSubtreeDelete) String() string

type ControlVChuPasswordMustChange

type ControlVChuPasswordMustChange struct {
	// MustChange indicates if the password is required to be changed
	MustChange bool
}

ControlVChuPasswordMustChange implements the control described in https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00

func (*ControlVChuPasswordMustChange) Encode

Encode returns the ber packet representation

func (*ControlVChuPasswordMustChange) GetControlType

func (c *ControlVChuPasswordMustChange) GetControlType() string

GetControlType returns the OID

func (*ControlVChuPasswordMustChange) String

String returns a human-readable description

type ControlVChuPasswordWarning

type ControlVChuPasswordWarning struct {
	// Expire indicates the time in seconds until the password expires
	Expire int64
}

ControlVChuPasswordWarning implements the control described in https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00

func (*ControlVChuPasswordWarning) Encode

func (c *ControlVChuPasswordWarning) Encode() *ber.Packet

Encode returns the ber packet representation

func (*ControlVChuPasswordWarning) GetControlType

func (c *ControlVChuPasswordWarning) GetControlType() string

GetControlType returns the OID

func (*ControlVChuPasswordWarning) String

func (c *ControlVChuPasswordWarning) String() string

String returns a human-readable description

type DN

type DN struct {
	RDNs []*RelativeDN
}

DN represents a distinguishedName from https://tools.ietf.org/html/rfc4514

func ParseDN

func ParseDN(str string) (*DN, error)

ParseDN returns a distinguishedName or an error. The function respects https://tools.ietf.org/html/rfc4514

func (*DN) AncestorOf

func (d *DN) AncestorOf(other *DN) bool

AncestorOf returns true if the other DN consists of at least one RDN followed by all the RDNs of the current DN. "ou=widgets,o=acme.com" is an ancestor of "ou=sprockets,ou=widgets,o=acme.com" "ou=widgets,o=acme.com" is not an ancestor of "ou=sprockets,ou=widgets,o=foo.com" "ou=widgets,o=acme.com" is not an ancestor of "ou=widgets,o=acme.com"

func (*DN) AncestorOfFold

func (d *DN) AncestorOfFold(other *DN) bool

AncestorOfFold returns true if the other DN consists of at least one RDN followed by all the RDNs of the current DN. Case of the attribute type and value is not significant

func (*DN) Equal

func (d *DN) Equal(other *DN) bool

Equal returns true if the DNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). Returns true if they have the same number of relative distinguished names and corresponding relative distinguished names (by position) are the same.

func (*DN) EqualFold

func (d *DN) EqualFold(other *DN) bool

Equal returns true if the DNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). Returns true if they have the same number of relative distinguished names and corresponding relative distinguished names (by position) are the same. Case of the attribute type and value is not significant

func (*DN) String

func (d *DN) String() string

String returns a normalized string representation of this DN which is the join of all relative DNs with a ",".

type DialContext

type DialContext struct {
	// contains filtered or unexported fields
}

DialContext contains necessary parameters to dial the given ldap URL.

type DialOpt

type DialOpt func(*DialContext)

DialOpt configures DialContext.

func DialWithContext

func DialWithContext(ctx context.Context) DialOpt

func DialWithDialer

func DialWithDialer(d *net.Dialer) DialOpt

DialWithDialer updates net.Dialer in DialContext.

func DialWithTLSConfig

func DialWithTLSConfig(tc *tls.Config) DialOpt

DialWithTLSConfig updates tls.Config in DialContext.

func DialWithTLSDialer

func DialWithTLSDialer(tlsConfig *tls.Config, dialer *net.Dialer) DialOpt

DialWithTLSDialer is a wrapper for DialWithTLSConfig with the option to specify a net.Dialer to for example define a timeout or a custom resolver. @deprecated Use DialWithDialer and DialWithTLSConfig instead

type DigestMD5BindRequest

type DigestMD5BindRequest struct {
	Host string
	// Username is the name of the Directory object that the client wishes to bind as
	Username string
	// Password is the credentials to bind with
	Password string
	// Controls are optional controls to send with the bind request
	Controls []Control
}

DigestMD5BindRequest represents a digest-md5 bind operation

type DigestMD5BindResult

type DigestMD5BindResult struct {
	Controls []Control
}

DigestMD5BindResult contains the response from the server

type Error

type Error struct {
	// Err is the underlying error
	Err error
	// ResultCode is the LDAP error code
	ResultCode uint16
	// MatchedDN is the matchedDN returned if any
	MatchedDN string
	// Packet is the returned packet if any
	Packet *ber.Packet
}

Error holds LDAP error information

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type GSSAPIBindRequest

type GSSAPIBindRequest struct {
	// Service Principal Name user for the service ticket. Eg. "ldap/<host>"
	ServicePrincipalName string
	// (Optional) Authorization entity
	AuthZID string
	// (Optional) Controls to send with the bind request
	Controls []Control
}

GSSAPIBindRequest represents a GSSAPI SASL mechanism bind request. See rfc4752 and rfc4513 section 5.2.1.2.

type GSSAPIClient

type GSSAPIClient interface {
	// InitSecContext initiates the establishment of a security context for
	// GSS-API between the client and server.
	// Initially the token parameter should be specified as nil.
	// The routine may return a outputToken which should be transferred to
	// the server, where the server will present it to AcceptSecContext.
	// If no token need be sent, InitSecContext will indicate this by setting
	// needContinue to false. To complete the context
	// establishment, one or more reply tokens may be required from the server;
	// if so, InitSecContext will return a needContinue which is true.
	// In this case, InitSecContext should be called again when the
	// reply token is received from the server, passing the reply token
	// to InitSecContext via the token parameters.
	// See RFC 4752 section 3.1.
	InitSecContext(target string, token []byte) (outputToken []byte, needContinue bool, err error)
	// NegotiateSaslAuth performs the last step of the Sasl handshake.
	// It takes a token, which, when unwrapped, describes the servers supported
	// security layers (first octet) and maximum receive buffer (remaining
	// three octets).
	// If the received token is unacceptable an error must be returned to abort
	// the handshake.
	// Outputs a signed token describing the client's selected security layer
	// and receive buffer size and optionally an authorization identity.
	// The returned token will be sent to the server and the handshake considered
	// completed successfully and the server authenticated.
	// See RFC 4752 section 3.1.
	NegotiateSaslAuth(token []byte, authzid string) ([]byte, error)
	// DeleteSecContext destroys any established secure context.
	DeleteSecContext() error
}

GSSAPIClient interface is used as the client-side implementation for the GSSAPI SASL mechanism. Interface inspired by GSSAPIClient from golang.org/x/crypto/ssh

type NTLMBindRequest

type NTLMBindRequest struct {
	// Domain is the AD Domain to authenticate too. If not specified, it will be grabbed from the NTLMSSP Challenge
	Domain string
	// Username is the name of the Directory object that the client wishes to bind as
	Username string
	// Password is the credentials to bind with
	Password string
	// AllowEmptyPassword sets whether the client allows binding with an empty password
	// (normally used for unauthenticated bind).
	AllowEmptyPassword bool
	// Hash is the hex NTLM hash to bind with. Password or hash must be provided
	Hash string
	// Controls are optional controls to send with the bind request
	Controls []Control
}

NTLMBindRequest represents an NTLMSSP bind operation

type NTLMBindResult

type NTLMBindResult struct {
	Controls []Control
}

NTLMBindResult contains the response from the server

type PacketResponse

type PacketResponse struct {
	// Packet is the packet read from the server
	Packet *ber.Packet
	// Error is an error encountered while reading
	Error error
}

PacketResponse contains the packet or error encountered reading a response

func (*PacketResponse) ReadPacket

func (pr *PacketResponse) ReadPacket() (*ber.Packet, error)

ReadPacket returns the packet or an error

type RelativeDN

type RelativeDN struct {
	Attributes []*AttributeTypeAndValue
}

RelativeDN represents a relativeDistinguishedName from https://tools.ietf.org/html/rfc4514

func (*RelativeDN) Equal

func (r *RelativeDN) Equal(other *RelativeDN) bool

Equal returns true if the RelativeDNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). Relative distinguished names are the same if and only if they have the same number of AttributeTypeAndValues and each attribute of the first RDN is the same as the attribute of the second RDN with the same attribute type. The order of attributes is not significant. Case of attribute types is not significant.

func (*RelativeDN) EqualFold

func (r *RelativeDN) EqualFold(other *RelativeDN) bool

Equal returns true if the RelativeDNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). Case of the attribute type is not significant

func (*RelativeDN) String

func (r *RelativeDN) String() string

String returns a normalized string representation of this relative DN which is the a join of all attributes (sorted in increasing order) with a "+".

type SimpleBindRequest

type SimpleBindRequest struct {
	// Username is the name of the Directory object that the client wishes to bind as
	Username string
	// Password is the credentials to bind with
	Password string
	// Controls are optional controls to send with the bind request
	Controls []Control
	// AllowEmptyPassword sets whether the client allows binding with an empty password
	// (normally used for unauthenticated bind).
	AllowEmptyPassword bool
}

SimpleBindRequest represents a username/password bind operation

func NewSimpleBindRequest

func NewSimpleBindRequest(username string, password string, controls []Control) *SimpleBindRequest

NewSimpleBindRequest returns a bind request

type SimpleBindResult

type SimpleBindResult struct {
	Controls []Control
}

SimpleBindResult contains the response from the server

type WhoAmIResult

type WhoAmIResult struct {
	AuthzID string
}

WhoAmIResult is returned by the WhoAmI() call

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL