...

Package ldap

import "github.com/go-ldap/ldap/v3"
Overview
Index
Examples
Subdirectories

Overview ▾

Package ldap provides basic LDAP v3 functionality.

Example (Beherappolicy)

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

controls := []Control{}
controls = append(controls, NewControlBeheraPasswordPolicy())
bindRequest := NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", controls)

r, err := l.SimpleBind(bindRequest)
ppolicyControl := FindControl(r.Controls, ControlTypeBeheraPasswordPolicy)

var ppolicy *ControlBeheraPasswordPolicy
if ppolicyControl != nil {
    ppolicy = ppolicyControl.(*ControlBeheraPasswordPolicy)
} else {
    log.Printf("ppolicyControl response not available.\n")
}
if err != nil {
    errStr := "ERROR: Cannot bind: " + err.Error()
    if ppolicy != nil && ppolicy.Error >= 0 {
        errStr += ":" + ppolicy.ErrorString
    }
    log.Print(errStr)
} else {
    logStr := "Login Ok"
    if ppolicy != nil {
        if ppolicy.Expire >= 0 {
            logStr += fmt.Sprintf(". Password expires in %d seconds\n", ppolicy.Expire)
        } else if ppolicy.Grace >= 0 {
            logStr += fmt.Sprintf(". Password expired, %d grace logins remain\n", ppolicy.Grace)
        }
    }
    log.Print(logStr)
}

Example (UserAuthentication)

Example_userAuthentication shows how a typical application can verify a login attempt Refer to https://github.com/go-ldap/ldap/issues/93 for issues revolving around unauthenticated binds, with zero length passwords

Code:

// The username and password we want to check
username := "someuser"
password := "userpassword"

bindusername := "readonly"
bindpassword := "password"

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

// Reconnect with TLS
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
    log.Fatal(err)
}

// First bind with a read only user
err = l.Bind(bindusername, bindpassword)
if err != nil {
    log.Fatal(err)
}

// Search for the given username
searchRequest := NewSearchRequest(
    "dc=example,dc=com",
    ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
    fmt.Sprintf("(&(objectClass=organizationalPerson)(uid=%s))", EscapeFilter(username)),
    []string{"dn"},
    nil,
)

sr, err := l.Search(searchRequest)
if err != nil {
    log.Fatal(err)
}

if len(sr.Entries) != 1 {
    log.Fatal("User does not exist or too many entries returned")
}

userdn := sr.Entries[0].DN

// Bind as the user to verify their password
err = l.Bind(userdn, password)
if err != nil {
    log.Fatal(err)
}

// Rebind as the read only user for any further queries
err = l.Bind(bindusername, bindpassword)
if err != nil {
    log.Fatal(err)
}

Example (Vchuppolicy)

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()
l.Debug = true

bindRequest := NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", nil)

r, err := l.SimpleBind(bindRequest)

passwordMustChangeControl := FindControl(r.Controls, ControlTypeVChuPasswordMustChange)
var passwordMustChange *ControlVChuPasswordMustChange
if passwordMustChangeControl != nil {
    passwordMustChange = passwordMustChangeControl.(*ControlVChuPasswordMustChange)
}

if passwordMustChange != nil && passwordMustChange.MustChange {
    log.Printf("Password Must be changed.\n")
}

passwordWarningControl := FindControl(r.Controls, ControlTypeVChuPasswordWarning)

var passwordWarning *ControlVChuPasswordWarning
if passwordWarningControl != nil {
    passwordWarning = passwordWarningControl.(*ControlVChuPasswordWarning)
} else {
    log.Printf("ppolicyControl response not available.\n")
}
if err != nil {
    log.Print("ERROR: Cannot bind: " + err.Error())
} else {
    logStr := "Login Ok"
    if passwordWarning != nil {
        if passwordWarning.Expire >= 0 {
            logStr += fmt.Sprintf(". Password expires in %d seconds\n", passwordWarning.Expire)
        }
    }
    log.Print(logStr)
}

Index ▾

Constants
Variables
func CompileFilter(filter string) (*ber.Packet, error)
func DebugBinaryFile(fileName string) error
func DecompileFilter(packet *ber.Packet) (_ string, err error)
func EscapeDN(dn string) string
func EscapeFilter(filter string) string
func GetLDAPError(packet *ber.Packet) error
func IsErrorAnyOf(err error, codes ...uint16) bool
func IsErrorWithCode(err error, desiredResultCode uint16) bool
func Logger(l *log.Logger)
func NewError(resultCode uint16, err error) error
type AddRequest
    func NewAddRequest(dn string, controls []Control) *AddRequest
    func (req *AddRequest) Attribute(attrType string, attrVals []string)
type Attribute
type AttributeTypeAndValue
    func (a *AttributeTypeAndValue) Equal(other *AttributeTypeAndValue) bool
    func (a *AttributeTypeAndValue) EqualFold(other *AttributeTypeAndValue) bool
    func (a *AttributeTypeAndValue) String() string
type Change
type Client
type CompareRequest
type Conn
    func Dial(network, addr string) (*Conn, error)
    func DialTLS(network, addr string, config *tls.Config) (*Conn, error)
    func DialURL(addr string, opts ...DialOpt) (*Conn, error)
    func NewConn(conn net.Conn, isTLS bool) *Conn
    func (l *Conn) Add(addRequest *AddRequest) error
    func (l *Conn) Bind(username, password string) error
    func (l *Conn) Close() (err error)
    func (l *Conn) Compare(dn, attribute, value string) (bool, error)
    func (l *Conn) Del(delRequest *DelRequest) error
    func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*DigestMD5BindResult, error)
    func (l *Conn) DirSync(searchRequest *SearchRequest, flags int64, maxAttrCount int64, cookie []byte) (*SearchResult, error)
    func (l *Conn) DirSyncAsync(ctx context.Context, searchRequest *SearchRequest, bufferSize int, flags, maxAttrCount int64, cookie []byte) Response
    func (l *Conn) ExternalBind() error
    func (l *Conn) GSSAPIBind(client GSSAPIClient, servicePrincipal, authzid string) error
    func (l *Conn) GSSAPIBindRequest(client GSSAPIClient, req *GSSAPIBindRequest) error
    func (l *Conn) GetLastError() error
    func (l *Conn) IsClosing() bool
    func (l *Conn) MD5Bind(host, username, password string) error
    func (l *Conn) Modify(modifyRequest *ModifyRequest) error
    func (l *Conn) ModifyDN(m *ModifyDNRequest) error
    func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, error)
    func (l *Conn) NTLMBind(domain, username, password string) error
    func (l *Conn) NTLMBindWithHash(domain, username, hash string) error
    func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindResult, error)
    func (l *Conn) NTLMUnauthenticatedBind(domain, username string) error
    func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*PasswordModifyResult, error)
    func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error)
    func (l *Conn) SearchAsync(ctx context.Context, searchRequest *SearchRequest, bufferSize int) Response
    func (l *Conn) SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error)
    func (l *Conn) SetTimeout(timeout time.Duration)
    func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error)
    func (l *Conn) Start()
    func (l *Conn) StartTLS(config *tls.Config) error
    func (l *Conn) Syncrepl(ctx context.Context, searchRequest *SearchRequest, bufferSize int, mode ControlSyncRequestMode, cookie []byte, reloadHint bool) Response
    func (l *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool)
    func (l *Conn) UnauthenticatedBind(username string) error
    func (l *Conn) Unbind() error
    func (l *Conn) WhoAmI(controls []Control) (*WhoAmIResult, error)
type Control
    func DecodeControl(packet *ber.Packet) (Control, error)
    func FindControl(controls []Control, controlType string) Control
type ControlBeheraPasswordPolicy
    func NewControlBeheraPasswordPolicy() *ControlBeheraPasswordPolicy
    func (c *ControlBeheraPasswordPolicy) Encode() *ber.Packet
    func (c *ControlBeheraPasswordPolicy) GetControlType() string
    func (c *ControlBeheraPasswordPolicy) String() string
type ControlDirSync
    func NewControlDirSync(flags int64, maxAttrCount int64, cookie []byte) *ControlDirSync
    func NewRequestControlDirSync(flags int64, maxAttrCount int64, cookie []byte) *ControlDirSync
    func NewResponseControlDirSync(value *ber.Packet) (*ControlDirSync, error)
    func (c *ControlDirSync) Encode() *ber.Packet
    func (c *ControlDirSync) GetControlType() string
    func (c *ControlDirSync) SetCookie(cookie []byte)
    func (c *ControlDirSync) String() string
type ControlManageDsaIT
    func NewControlManageDsaIT(Criticality bool) *ControlManageDsaIT
    func (c *ControlManageDsaIT) Encode() *ber.Packet
    func (c *ControlManageDsaIT) GetControlType() string
    func (c *ControlManageDsaIT) String() string
type ControlMicrosoftNotification
    func NewControlMicrosoftNotification() *ControlMicrosoftNotification
    func (c *ControlMicrosoftNotification) Encode() *ber.Packet
    func (c *ControlMicrosoftNotification) GetControlType() string
    func (c *ControlMicrosoftNotification) String() string
type ControlMicrosoftServerLinkTTL
    func NewControlMicrosoftServerLinkTTL() *ControlMicrosoftServerLinkTTL
    func (c *ControlMicrosoftServerLinkTTL) Encode() *ber.Packet
    func (c *ControlMicrosoftServerLinkTTL) GetControlType() string
    func (c *ControlMicrosoftServerLinkTTL) String() string
type ControlMicrosoftShowDeleted
    func NewControlMicrosoftShowDeleted() *ControlMicrosoftShowDeleted
    func (c *ControlMicrosoftShowDeleted) Encode() *ber.Packet
    func (c *ControlMicrosoftShowDeleted) GetControlType() string
    func (c *ControlMicrosoftShowDeleted) String() string
type ControlPaging
    func NewControlPaging(pagingSize uint32) *ControlPaging
    func (c *ControlPaging) Encode() *ber.Packet
    func (c *ControlPaging) GetControlType() string
    func (c *ControlPaging) SetCookie(cookie []byte)
    func (c *ControlPaging) String() string
type ControlServerSideSorting
    func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error)
    func NewControlServerSideSortingWithSortKeys(sortKeys []*SortKey) *ControlServerSideSorting
    func (c *ControlServerSideSorting) Encode() *ber.Packet
    func (c *ControlServerSideSorting) GetControlType() string
    func (c *ControlServerSideSorting) String() string
type ControlServerSideSortingCode
    func (c ControlServerSideSortingCode) Valid() error
type ControlServerSideSortingResult
    func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSortingResult, error)
    func (c *ControlServerSideSortingResult) Encode() *ber.Packet
    func (control *ControlServerSideSortingResult) GetControlType() string
    func (c *ControlServerSideSortingResult) String() string
type ControlString
    func NewControlString(controlType string, criticality bool, controlValue string) *ControlString
    func (c *ControlString) Encode() *ber.Packet
    func (c *ControlString) GetControlType() string
    func (c *ControlString) String() string
type ControlSubtreeDelete
    func NewControlSubtreeDelete() *ControlSubtreeDelete
    func (c *ControlSubtreeDelete) Encode() *ber.Packet
    func (c *ControlSubtreeDelete) GetControlType() string
    func (c *ControlSubtreeDelete) String() string
type ControlSyncDone
    func NewControlSyncDone(pkt *ber.Packet) (*ControlSyncDone, error)
    func (c *ControlSyncDone) Encode() *ber.Packet
    func (c *ControlSyncDone) GetControlType() string
    func (c *ControlSyncDone) String() string
type ControlSyncInfo
    func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error)
    func (c *ControlSyncInfo) Encode() *ber.Packet
    func (c *ControlSyncInfo) GetControlType() string
    func (c *ControlSyncInfo) String() string
type ControlSyncInfoNewCookie
    func (c *ControlSyncInfoNewCookie) String() string
type ControlSyncInfoRefreshDelete
    func (c *ControlSyncInfoRefreshDelete) String() string
type ControlSyncInfoRefreshPresent
    func (c *ControlSyncInfoRefreshPresent) String() string
type ControlSyncInfoSyncIdSet
    func (c *ControlSyncInfoSyncIdSet) String() string
type ControlSyncInfoValue
type ControlSyncRequest
    func NewControlSyncRequest(mode ControlSyncRequestMode, cookie []byte, reloadHint bool) *ControlSyncRequest
    func (c *ControlSyncRequest) Encode() *ber.Packet
    func (c *ControlSyncRequest) GetControlType() string
    func (c *ControlSyncRequest) String() string
type ControlSyncRequestMode
type ControlSyncState
    func NewControlSyncState(pkt *ber.Packet) (*ControlSyncState, error)
    func (c *ControlSyncState) Encode() *ber.Packet
    func (c *ControlSyncState) GetControlType() string
    func (c *ControlSyncState) String() string
type ControlSyncStateState
type ControlVChuPasswordMustChange
    func (c *ControlVChuPasswordMustChange) Encode() *ber.Packet
    func (c *ControlVChuPasswordMustChange) GetControlType() string
    func (c *ControlVChuPasswordMustChange) String() string
type ControlVChuPasswordWarning
    func (c *ControlVChuPasswordWarning) Encode() *ber.Packet
    func (c *ControlVChuPasswordWarning) GetControlType() string
    func (c *ControlVChuPasswordWarning) String() string
type DN
    func ParseDN(str string) (*DN, error)
    func (d *DN) AncestorOf(other *DN) bool
    func (d *DN) AncestorOfFold(other *DN) bool
    func (d *DN) Equal(other *DN) bool
    func (d *DN) EqualFold(other *DN) bool
    func (d *DN) String() string
type DelRequest
    func NewDelRequest(DN string, Controls []Control) *DelRequest
type DialContext
type DialOpt
    func DialWithDialer(d *net.Dialer) DialOpt
    func DialWithTLSConfig(tc *tls.Config) DialOpt
    func DialWithTLSDialer(tlsConfig *tls.Config, dialer *net.Dialer) DialOpt
type DigestMD5BindRequest
type DigestMD5BindResult
type Entry
    func NewEntry(dn string, attributes map[string][]string) *Entry
    func (e *Entry) GetAttributeValue(attribute string) string
    func (e *Entry) GetAttributeValues(attribute string) []string
    func (e *Entry) GetEqualFoldAttributeValue(attribute string) string
    func (e *Entry) GetEqualFoldAttributeValues(attribute string) []string
    func (e *Entry) GetEqualFoldRawAttributeValue(attribute string) []byte
    func (e *Entry) GetEqualFoldRawAttributeValues(attribute string) [][]byte
    func (e *Entry) GetRawAttributeValue(attribute string) []byte
    func (e *Entry) GetRawAttributeValues(attribute string) [][]byte
    func (e *Entry) PrettyPrint(indent int)
    func (e *Entry) Print()
    func (e *Entry) Unmarshal(i interface{}) (err error)
type EntryAttribute
    func NewEntryAttribute(name string, values []string) *EntryAttribute
    func (e *EntryAttribute) PrettyPrint(indent int)
    func (e *EntryAttribute) Print()
type Error
    func (e *Error) Error() string
    func (e *Error) Unwrap() error
type GSSAPIBindRequest
type GSSAPIClient
type ModifyDNRequest
    func NewModifyDNRequest(dn string, rdn string, delOld bool, newSup string) *ModifyDNRequest
    func NewModifyDNWithControlsRequest(dn string, rdn string, delOld bool, newSup string, controls []Control) *ModifyDNRequest
type ModifyRequest
    func NewModifyRequest(dn string, controls []Control) *ModifyRequest
    func (req *ModifyRequest) Add(attrType string, attrVals []string)
    func (req *ModifyRequest) Delete(attrType string, attrVals []string)
    func (req *ModifyRequest) Increment(attrType string, attrVal string)
    func (req *ModifyRequest) Replace(attrType string, attrVals []string)
type ModifyResult
type NTLMBindRequest
type NTLMBindResult
type PacketResponse
    func (pr *PacketResponse) ReadPacket() (*ber.Packet, error)
type PartialAttribute
type PasswordModifyRequest
    func NewPasswordModifyRequest(userIdentity string, oldPassword string, newPassword string) *PasswordModifyRequest
type PasswordModifyResult
type RelativeDN
    func (r *RelativeDN) Equal(other *RelativeDN) bool
    func (r *RelativeDN) EqualFold(other *RelativeDN) bool
    func (r *RelativeDN) String() string
type Response
type SearchRequest
    func NewSearchRequest(BaseDN string, Scope, DerefAliases, SizeLimit, TimeLimit int, TypesOnly bool, Filter string, Attributes []string, Controls []Control) *SearchRequest
type SearchResult
    func (s *SearchResult) PrettyPrint(indent int)
    func (s *SearchResult) Print()
type SearchSingleResult
    func (s *SearchSingleResult) PrettyPrint(indent int)
    func (s *SearchSingleResult) Print()
type SimpleBindRequest
    func NewSimpleBindRequest(username string, password string, controls []Control) *SimpleBindRequest
type SimpleBindResult
type SortKey
type WhoAmIResult

Package files

add.go bind.go client.go compare.go conn.go control.go debug.go del.go dn.go doc.go error.go filter.go ldap.go moddn.go modify.go passwdmodify.go request.go response.go search.go unbind.go whoami.go

Constants

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
)
const (
    // DefaultLdapPort default ldap port for pure TCP connection
    DefaultLdapPort = "389"
    // DefaultLdapsPort default ldap port for SSL connection
    DefaultLdapsPort = "636"
)
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"

    // ControlTypeServerSideSorting - https://www.ietf.org/rfc/rfc2891.txt
    ControlTypeServerSideSorting = "1.2.840.113556.1.4.473"
    // ControlTypeServerSideSorting - https://www.ietf.org/rfc/rfc2891.txt
    ControlTypeServerSideSortingResult = "1.2.840.113556.1.4.474"

    // 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"
    // ControlTypeDirSync - Active Directory DirSync - https://msdn.microsoft.com/en-us/library/aa366978(v=vs.85).aspx
    ControlTypeDirSync = "1.2.840.113556.1.4.841"

    // ControlTypeSyncRequest - https://www.ietf.org/rfc/rfc4533.txt
    ControlTypeSyncRequest = "1.3.6.1.4.1.4203.1.9.1.1"
    // ControlTypeSyncState - https://www.ietf.org/rfc/rfc4533.txt
    ControlTypeSyncState = "1.3.6.1.4.1.4203.1.9.1.2"
    // ControlTypeSyncDone - https://www.ietf.org/rfc/rfc4533.txt
    ControlTypeSyncDone = "1.3.6.1.4.1.4203.1.9.1.3"
    // ControlTypeSyncInfo - https://www.ietf.org/rfc/rfc4533.txt
    ControlTypeSyncInfo = "1.3.6.1.4.1.4203.1.9.1.4"
)

Flags for DirSync control

const (
    DirSyncIncrementalValues   int64 = 2147483648
    DirSyncPublicDataOnly      int64 = 8192
    DirSyncAncestorsFirstOrder int64 = 2048
    DirSyncObjectSecurity      int64 = 1
)

LDAP Result Codes

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
)

Filter choices

const (
    FilterAnd             = 0
    FilterOr              = 1
    FilterNot             = 2
    FilterEqualityMatch   = 3
    FilterSubstrings      = 4
    FilterGreaterOrEqual  = 5
    FilterLessOrEqual     = 6
    FilterPresent         = 7
    FilterApproxMatch     = 8
    FilterExtensibleMatch = 9
)

SubstringFilter options

const (
    FilterSubstringsInitial = 0
    FilterSubstringsAny     = 1
    FilterSubstringsFinal   = 2
)

MatchingRuleAssertion choices

const (
    MatchingRuleAssertionMatchingRule = 1
    MatchingRuleAssertionType         = 2
    MatchingRuleAssertionMatchValue   = 3
    MatchingRuleAssertionDNAttributes = 4
)

LDAP Application Codes

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
    ApplicationIntermediateResponse  = 25
)

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

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

Change operation choices

const (
    AddAttribute       = 0
    DeleteAttribute    = 1
    ReplaceAttribute   = 2
    IncrementAttribute = 3 // (https://tools.ietf.org/html/rfc4525)
)

scope choices

const (
    ScopeBaseObject   = 0
    ScopeSingleLevel  = 1
    ScopeWholeSubtree = 2
)

derefAliases

const (
    NeverDerefAliases   = 0
    DerefInSearching    = 1
    DerefFindingBaseObj = 2
    DerefAlways         = 3
)

Variables

ApplicationMap contains human readable descriptions of LDAP Application Codes

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",
    ApplicationIntermediateResponse:  "Intermediate Response",
}

BeheraPasswordPolicyErrorMap contains human readable descriptions of Behera Password Policy error codes

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",
}
var ControlServerSideSortingCodes = []ControlServerSideSortingCode{
    ControlServerSideSortingCodeSuccess,
    ControlServerSideSortingCodeOperationsError,
    ControlServerSideSortingCodeTimeLimitExceeded,
    ControlServerSideSortingCodeStrongAuthRequired,
    ControlServerSideSortingCodeAdminLimitExceeded,
    ControlServerSideSortingCodeNoSuchAttribute,
    ControlServerSideSortingCodeInappropriateMatching,
    ControlServerSideSortingCodeInsufficientAccessRights,
    ControlServerSideSortingCodeBusy,
    ControlServerSideSortingCodeUnwillingToPerform,
    ControlServerSideSortingCodeOther,
}

ControlTypeMap maps controls to text descriptions

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",
    ControlTypeServerSideSorting:       "Server Side Sorting Request - LDAP Control Extension for Server Side Sorting of Search Results (RFC2891)",
    ControlTypeServerSideSortingResult: "Server Side Sorting Results - LDAP Control Extension for Server Side Sorting of Search Results (RFC2891)",
    ControlTypeDirSync:                 "DirSync",
    ControlTypeSyncRequest:             "Sync Request",
    ControlTypeSyncState:               "Sync State",
    ControlTypeSyncDone:                "Sync Done",
    ControlTypeSyncInfo:                "Sync Info",
}

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.

var DefaultTimeout = 60 * time.Second

DerefMap contains human readable descriptions of derefAliases choices

var DerefMap = map[int]string{
    NeverDerefAliases:   "NeverDerefAliases",
    DerefInSearching:    "DerefInSearching",
    DerefFindingBaseObj: "DerefFindingBaseObj",
    DerefAlways:         "DerefAlways",
}

ErrConnUnbound is returned when Unbind is called on an already closing connection.

var ErrConnUnbound = NewError(ErrorNetwork, errors.New("ldap: connection is closed"))
var (

    // ErrNilConnection is returned if doRequest is called with a nil connection.
    ErrNilConnection = errors.New("ldap: conn is nil, expected net.Conn")
)

FilterMap contains human readable descriptions of Filter choices

var FilterMap = map[uint64]string{
    FilterAnd:             "And",
    FilterOr:              "Or",
    FilterNot:             "Not",
    FilterEqualityMatch:   "Equality Match",
    FilterSubstrings:      "Substrings",
    FilterGreaterOrEqual:  "Greater Or Equal",
    FilterLessOrEqual:     "Less Or Equal",
    FilterPresent:         "Present",
    FilterApproxMatch:     "Approx Match",
    FilterExtensibleMatch: "Extensible Match",
}

FilterSubstringsMap contains human readable descriptions of SubstringFilter choices

var FilterSubstringsMap = map[uint64]string{
    FilterSubstringsInitial: "Substrings Initial",
    FilterSubstringsAny:     "Substrings Any",
    FilterSubstringsFinal:   "Substrings Final",
}

LDAPResultCodeMap contains string descriptions for LDAP error codes

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",
}

MatchingRuleAssertionMap contains human readable descriptions of MatchingRuleAssertion choices

var MatchingRuleAssertionMap = map[uint64]string{
    MatchingRuleAssertionMatchingRule: "Matching Rule Assertion Matching Rule",
    MatchingRuleAssertionType:         "Matching Rule Assertion Type",
    MatchingRuleAssertionMatchValue:   "Matching Rule Assertion Match Value",
    MatchingRuleAssertionDNAttributes: "Matching Rule Assertion DN Attributes",
}

ScopeMap contains human readable descriptions of scope choices

var ScopeMap = map[int]string{
    ScopeBaseObject:   "Base Object",
    ScopeSingleLevel:  "Single Level",
    ScopeWholeSubtree: "Whole Subtree",
}

func CompileFilter

func CompileFilter(filter string) (*ber.Packet, error)

CompileFilter converts a string representation of a filter into a BER-encoded packet

func DebugBinaryFile

func DebugBinaryFile(fileName string) error

DebugBinaryFile reads and prints packets from the given filename

func DecompileFilter

func DecompileFilter(packet *ber.Packet) (_ string, err error)

DecompileFilter converts a packet representation of a filter into a string representation

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

type AddRequest

AddRequest represents an LDAP AddRequest operation

type AddRequest struct {
    // DN identifies the entry being added
    DN string
    // Attributes list the attributes of the new entry
    Attributes []Attribute
    // Controls hold optional controls to send with the request
    Controls []Control
}

func NewAddRequest

func NewAddRequest(dn string, controls []Control) *AddRequest

NewAddRequest returns an AddRequest for the given DN, with no attributes

func (*AddRequest) Attribute

func (req *AddRequest) Attribute(attrType string, attrVals []string)

Attribute adds an attribute with the given type and values

type Attribute

Attribute represents an LDAP attribute

type Attribute struct {
    // Type is the name of the LDAP attribute
    Type string
    // Vals are the LDAP attribute values
    Vals []string
}

type AttributeTypeAndValue

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

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

func (*AttributeTypeAndValue) Equal

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

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 Change

Change for a ModifyRequest as defined in https://tools.ietf.org/html/rfc4511

type Change struct {
    // Operation is the type of change to be made
    Operation uint
    // Modification is the attribute to be modified
    Modification PartialAttribute
}

type Client

Client knows how to interact with an LDAP server

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

    Bind(username, password string) error
    UnauthenticatedBind(username string) error
    SimpleBind(*SimpleBindRequest) (*SimpleBindResult, error)
    ExternalBind() error
    NTLMUnauthenticatedBind(domain, username string) error
    Unbind() error

    Add(*AddRequest) error
    Del(*DelRequest) error
    Modify(*ModifyRequest) error
    ModifyDN(*ModifyDNRequest) error
    ModifyWithResult(*ModifyRequest) (*ModifyResult, error)

    Compare(dn, attribute, value string) (bool, error)
    PasswordModify(*PasswordModifyRequest) (*PasswordModifyResult, error)

    Search(*SearchRequest) (*SearchResult, error)
    SearchAsync(ctx context.Context, searchRequest *SearchRequest, bufferSize int) Response
    SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error)
    DirSync(searchRequest *SearchRequest, flags, maxAttrCount int64, cookie []byte) (*SearchResult, error)
    DirSyncAsync(ctx context.Context, searchRequest *SearchRequest, bufferSize int, flags, maxAttrCount int64, cookie []byte) Response
    Syncrepl(ctx context.Context, searchRequest *SearchRequest, bufferSize int, mode ControlSyncRequestMode, cookie []byte, reloadHint bool) Response
}

type CompareRequest

CompareRequest represents an LDAP CompareRequest operation.

type CompareRequest struct {
    DN        string
    Attribute string
    Value     string
}

type Conn

Conn represents an LDAP Connection

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

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) Add

func (l *Conn) Add(addRequest *AddRequest) error

Add performs the given AddRequest

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.

Example

This example demonstrates how to bind a connection to an ldap user allowing access to restricted attributes that user has access to

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

err = l.Bind("cn=read-only-admin,dc=example,dc=com", "password")
if err != nil {
    log.Fatal(err)
}

func (*Conn) Close

func (l *Conn) Close() (err error)

Close closes the connection.

func (*Conn) Compare

func (l *Conn) Compare(dn, attribute, value string) (bool, error)

Compare checks to see if the attribute of the dn matches value. Returns true if it does otherwise false with any error that occurs if any.

Example

This example demonstrates how to compare an attribute with a value

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

matched, err := l.Compare("cn=user,dc=example,dc=com", "uid", "someuserid")
if err != nil {
    log.Fatal(err)
}

fmt.Println(matched)

func (*Conn) Del

func (l *Conn) Del(delRequest *DelRequest) error

Del executes the given delete request

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) DirSync

func (l *Conn) DirSync(
    searchRequest *SearchRequest, flags int64, maxAttrCount int64, cookie []byte,
) (*SearchResult, error)

DirSync does a Search with dirSync Control.

Example

This example demonstrates how to use DirSync to manually execute a DirSync search request

Code:

conn, err := Dial("tcp", "ad.example.org:389")
if err != nil {
    log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()

_, err = conn.SimpleBind(&SimpleBindRequest{
    Username: "cn=Some User,ou=people,dc=example,dc=org",
    Password: "MySecretPass",
})
if err != nil {
    log.Fatalf("failed to bind: %s", err)
}

req := &SearchRequest{
    BaseDN:     `DC=example,DC=org`,
    Filter:     `(&(objectClass=person)(!(objectClass=computer)))`,
    Attributes: []string{"*"},
    Scope:      ScopeWholeSubtree,
}
// This is the initial sync with all entries matching the filter
doMore := true
var cookie []byte
for doMore {
    res, err := conn.DirSync(req, DirSyncObjectSecurity, 1000, cookie)
    if err != nil {
        log.Fatalf("failed to search: %s", err)
    }
    for _, entry := range res.Entries {
        entry.Print()
    }
    ctrl := FindControl(res.Controls, ControlTypeDirSync)
    if ctrl == nil || ctrl.(*ControlDirSync).Flags == 0 {
        doMore = false
    }
    cookie = ctrl.(*ControlDirSync).Cookie
}
// We're done with the initial sync. Now pull every 15 seconds for the
// updated entries - note that you get just the changes, not a full entry.
for {
    res, err := conn.DirSync(req, DirSyncObjectSecurity, 1000, cookie)
    if err != nil {
        log.Fatalf("failed to search: %s", err)
    }
    for _, entry := range res.Entries {
        entry.Print()
    }
    time.Sleep(15 * time.Second)
}

func (*Conn) DirSyncAsync

func (l *Conn) DirSyncAsync(
    ctx context.Context, searchRequest *SearchRequest, bufferSize int,
    flags, maxAttrCount int64, cookie []byte,
) Response

DirSyncDirSyncAsync performs a search request and returns all search results asynchronously. This is efficient when the server returns lots of entries.

Example

This example demonstrates how to use DirSync search asynchronously

Code:

conn, err := Dial("tcp", "ad.example.org:389")
if err != nil {
    log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()

_, err = conn.SimpleBind(&SimpleBindRequest{
    Username: "cn=Some User,ou=people,dc=example,dc=org",
    Password: "MySecretPass",
})
if err != nil {
    log.Fatalf("failed to bind: %s", err)
}

req := &SearchRequest{
    BaseDN:     `DC=example,DC=org`,
    Filter:     `(&(objectClass=person)(!(objectClass=computer)))`,
    Attributes: []string{"*"},
    Scope:      ScopeWholeSubtree,
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

var cookie []byte = nil
r := conn.DirSyncAsync(ctx, req, 64, DirSyncObjectSecurity, 1000, cookie)
for r.Next() {
    entry := r.Entry()
    if entry != nil {
        entry.Print()
    }
    controls := r.Controls()
    if len(controls) != 0 {
        fmt.Printf("%s", controls)
    }
}
if err := r.Err(); err != nil {
    log.Fatal(err)
}

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

Example

This example demonstrates how to use EXTERNAL SASL with TLS client certificates.

Code:

ldapCert := "/path/to/cert.pem"
ldapKey := "/path/to/key.pem"
ldapCAchain := "/path/to/ca_chain.pem"

// Load client cert and key
cert, err := tls.LoadX509KeyPair(ldapCert, ldapKey)
if err != nil {
    log.Fatal(err)
}

// Load CA chain
caCert, err := ioutil.ReadFile(ldapCAchain)
if err != nil {
    log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

// Setup TLS with ldap client cert
tlsConfig := &tls.Config{
    Certificates:       []tls.Certificate{cert},
    RootCAs:            caCertPool,
    InsecureSkipVerify: true,
}

// connect to ldap server
l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

// reconnect using tls
err = l.StartTLS(tlsConfig)
if err != nil {
    log.Fatal(err)
}

// sasl external bind
err = l.ExternalBind()
if err != nil {
    log.Fatal(err)
}

// Conduct ldap queries

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) GetLastError

func (l *Conn) GetLastError() error

GetLastError returns the last recorded error from goroutines like processMessages and reader. Only the last recorded error will be returned.

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) Modify

func (l *Conn) Modify(modifyRequest *ModifyRequest) error

Modify performs the ModifyRequest

Example

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

// Add a description, and replace the mail attributes
modify := NewModifyRequest("cn=user,dc=example,dc=com", nil)
modify.Add("description", []string{"An example user"})
modify.Replace("mail", []string{"user@example.org"})

err = l.Modify(modify)
if err != nil {
    log.Fatal(err)
}

func (*Conn) ModifyDN

func (l *Conn) ModifyDN(m *ModifyDNRequest) error

ModifyDN renames the given DN and optionally move to another base (when the "newSup" argument to NewModifyDNRequest() is not "").

Example (MoveOnly)

This example shows how to move an entry to a new base without renaming the RDN

Code:

conn, err := DialURL("ldap://ldap.example.org:389")
if err != nil {
    log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()

_, err = conn.SimpleBind(&SimpleBindRequest{
    Username: "uid=someone,ou=people,dc=example,dc=org",
    Password: "MySecretPass",
})
if err != nil {
    log.Fatalf("Failed to bind: %s\n", err)
}
// move to ou=users,dc=example,dc=org -> uid=user,ou=users,dc=example,dc=org
req := NewModifyDNRequest("uid=user,ou=people,dc=example,dc=org", "uid=user", true, "ou=users,dc=example,dc=org")
if err = conn.ModifyDN(req); err != nil {
    log.Fatalf("Failed to call ModifyDN(): %s\n", err)
}

Example (RenameAndMove)

This example shows how to rename an entry and moving it to a new base

Code:

conn, err := DialURL("ldap://ldap.example.org:389")
if err != nil {
    log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()

_, err = conn.SimpleBind(&SimpleBindRequest{
    Username: "uid=someone,ou=people,dc=example,dc=org",
    Password: "MySecretPass",
})
if err != nil {
    log.Fatalf("Failed to bind: %s\n", err)
}
// rename to uid=new,ou=people,dc=example,dc=org and move to ou=users,dc=example,dc=org ->
// uid=new,ou=users,dc=example,dc=org
req := NewModifyDNRequest("uid=user,ou=people,dc=example,dc=org", "uid=new", true, "ou=users,dc=example,dc=org")

if err = conn.ModifyDN(req); err != nil {
    log.Fatalf("Failed to call ModifyDN(): %s\n", err)
}

Example (RenameNoMove)

This example shows how to rename an entry without moving it

Code:

conn, err := DialURL("ldap://ldap.example.org:389")
if err != nil {
    log.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()

_, err = conn.SimpleBind(&SimpleBindRequest{
    Username: "uid=someone,ou=people,dc=example,dc=org",
    Password: "MySecretPass",
})
if err != nil {
    log.Fatalf("Failed to bind: %s\n", err)
}
// just rename to uid=new,ou=people,dc=example,dc=org:
req := NewModifyDNRequest("uid=user,ou=people,dc=example,dc=org", "uid=new", true, "")
if err = conn.ModifyDN(req); err != nil {
    log.Fatalf("Failed to call ModifyDN(): %s\n", err)
}

func (*Conn) ModifyWithResult

func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, error)

ModifyWithResult performs the ModifyRequest and returns the result

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) PasswordModify

func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*PasswordModifyResult, error)

PasswordModify performs the modification request

Example (Admin)

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

err = l.Bind("cn=admin,dc=example,dc=com", "password")
if err != nil {
    log.Fatal(err)
}

passwordModifyRequest := NewPasswordModifyRequest("cn=user,dc=example,dc=com", "", "NewPassword")
_, err = l.PasswordModify(passwordModifyRequest)

if err != nil {
    log.Fatalf("Password could not be changed: %s", err.Error())
}

Example (GeneratedPassword)

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

err = l.Bind("cn=user,dc=example,dc=com", "password")
if err != nil {
    log.Fatal(err)
}

passwordModifyRequest := NewPasswordModifyRequest("", "OldPassword", "")
passwordModifyResponse, err := l.PasswordModify(passwordModifyRequest)
if err != nil {
    log.Fatalf("Password could not be changed: %s", err.Error())
}

generatedPassword := passwordModifyResponse.GeneratedPassword
log.Printf("Generated password: %s\n", generatedPassword)

Example (SetNewPassword)

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

err = l.Bind("cn=user,dc=example,dc=com", "password")
if err != nil {
    log.Fatal(err)
}

passwordModifyRequest := NewPasswordModifyRequest("", "OldPassword", "NewPassword")
_, err = l.PasswordModify(passwordModifyRequest)

if err != nil {
    log.Fatalf("Password could not be changed: %s", err.Error())
}

func (*Conn) Search

func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error)

Search performs the given search request

func (*Conn) SearchAsync

func (l *Conn) SearchAsync(
    ctx context.Context, searchRequest *SearchRequest, bufferSize int) Response

SearchAsync performs a search request and returns all search results asynchronously. This means you get all results until an error happens (or the search successfully finished), e.g. for size / time limited requests all are recieved until the limit is reached. To stop the search, call cancel function of the context.

Example

This example demonstrates how to search asynchronously

Code:

l, err := DialURL(fmt.Sprintf("%s:%d", "ldap.example.com", 389))
if err != nil {
    log.Fatal(err)
}
defer l.Close()

searchRequest := NewSearchRequest(
    "dc=example,dc=com", // The base dn to search
    ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
    "(&(objectClass=organizationalPerson))", // The filter to apply
    []string{"dn", "cn"},                    // A list attributes to retrieve
    nil,
)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

r := l.SearchAsync(ctx, searchRequest, 64)
for r.Next() {
    entry := r.Entry()
    fmt.Printf("%s has DN %s\n", entry.GetAttributeValue("cn"), entry.DN)
}
if err := r.Err(); err != nil {
    log.Fatal(err)
}

func (*Conn) SearchWithPaging

func (l *Conn) SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error)

SearchWithPaging accepts a search request and desired page size in order to execute LDAP queries to fulfill the search request. All paged LDAP query responses will be buffered and the final result will be returned atomically. The following four cases are possible given the arguments:

A requested pagingSize of 0 is interpreted as no limit by LDAP servers.

func (*Conn) SetTimeout

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

SetTimeout sets the time after a request is sent that a MessageTimeout triggers

func (*Conn) SimpleBind

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

SimpleBind performs the simple bind operation defined in the given request

func (*Conn) Start

func (l *Conn) Start()

Start initializes goroutines to read responses and process messages

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

Example

This example demonstrates how to start a TLS connection

Code:

l, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer l.Close()

// Reconnect with TLS
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
    log.Fatal(err)
}

// Operations via l are now encrypted

func (*Conn) Syncrepl

func (l *Conn) Syncrepl(
    ctx context.Context, searchRequest *SearchRequest, bufferSize int,
    mode ControlSyncRequestMode, cookie []byte, reloadHint bool,
) Response

Syncrepl is a short name for LDAP Sync Replication engine that works on the consumer-side. This can perform a persistent search and returns an entry when the entry is updated on the server side. To stop the search, call cancel function of the context.

Example

This example demonstrates how to do syncrepl (persistent search)

Code:

l, err := DialURL(fmt.Sprintf("%s:%d", "ldap.example.com", 389))
if err != nil {
    log.Fatal(err)
}
defer l.Close()

searchRequest := NewSearchRequest(
    "dc=example,dc=com", // The base dn to search
    ScopeWholeSubtree, NeverDerefAliases, 0, 0, false,
    "(&(objectClass=organizationalPerson))", // The filter to apply
    []string{"dn", "cn"},                    // A list attributes to retrieve
    nil,
)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

mode := SyncRequestModeRefreshAndPersist
var cookie []byte = nil
r := l.Syncrepl(ctx, searchRequest, 64, mode, cookie, false)
for r.Next() {
    entry := r.Entry()
    if entry != nil {
        fmt.Printf("%s has DN %s\n", entry.GetAttributeValue("cn"), entry.DN)
    }
    controls := r.Controls()
    if len(controls) != 0 {
        fmt.Printf("%s", controls)
    }
}
if err := r.Err(); err != nil {
    log.Fatal(err)
}

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

Example

ExampleConn_WhoAmI demonstrates how to run a whoami request according to https://tools.ietf.org/html/rfc4532

Code:

conn, err := DialURL("ldap.example.org:389")
if err != nil {
    log.Fatalf("Failed to connect: %s\n", err)
}

_, err = conn.SimpleBind(&SimpleBindRequest{
    Username: "uid=someone,ou=people,dc=example,dc=org",
    Password: "MySecretPass",
})
if err != nil {
    log.Fatalf("Failed to bind: %s\n", err)
}

res, err := conn.WhoAmI(nil)
if err != nil {
    log.Fatalf("Failed to call WhoAmI(): %s\n", err)
}
fmt.Printf("I am: %s\n", res.AuthzID)

type Control

Control defines an interface controls provide to encode and describe themselves

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
}

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

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

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
}

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 ControlDirSync

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

type ControlDirSync struct {
    Criticality  bool
    Flags        int64
    MaxAttrCount int64
    Cookie       []byte
}

func NewControlDirSync

func NewControlDirSync(flags int64, maxAttrCount int64, cookie []byte) *ControlDirSync

@deprecated Use NewRequestControlDirSync instead

func NewRequestControlDirSync

func NewRequestControlDirSync(
    flags int64, maxAttrCount int64, cookie []byte,
) *ControlDirSync

NewRequestControlDirSync returns a dir sync control

func NewResponseControlDirSync

func NewResponseControlDirSync(value *ber.Packet) (*ControlDirSync, error)

NewResponseControlDirSync returns a dir sync control

func (*ControlDirSync) Encode

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

Encode returns the ber packet representation

func (*ControlDirSync) GetControlType

func (c *ControlDirSync) GetControlType() string

GetControlType returns the OID

func (*ControlDirSync) SetCookie

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

SetCookie stores the given cookie in the dirSync control

func (*ControlDirSync) String

func (c *ControlDirSync) String() string

String returns a human-readable description

type ControlManageDsaIT

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

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

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

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

type ControlMicrosoftNotification struct{}

func NewControlMicrosoftNotification

func NewControlMicrosoftNotification() *ControlMicrosoftNotification

NewControlMicrosoftNotification returns a ControlMicrosoftNotification control

func (*ControlMicrosoftNotification) Encode

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

Encode returns the ber packet representation

func (*ControlMicrosoftNotification) GetControlType

func (c *ControlMicrosoftNotification) GetControlType() string

GetControlType returns the OID

func (*ControlMicrosoftNotification) String

func (c *ControlMicrosoftNotification) String() string

String returns a human-readable description

type ControlMicrosoftServerLinkTTL

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

type ControlMicrosoftServerLinkTTL struct{}

func NewControlMicrosoftServerLinkTTL

func NewControlMicrosoftServerLinkTTL() *ControlMicrosoftServerLinkTTL

NewControlMicrosoftServerLinkTTL returns a ControlMicrosoftServerLinkTTL control

func (*ControlMicrosoftServerLinkTTL) Encode

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

Encode returns the ber packet representation

func (*ControlMicrosoftServerLinkTTL) GetControlType

func (c *ControlMicrosoftServerLinkTTL) GetControlType() string

GetControlType returns the OID

func (*ControlMicrosoftServerLinkTTL) String

func (c *ControlMicrosoftServerLinkTTL) String() string

String returns a human-readable description

type ControlMicrosoftShowDeleted

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

type ControlMicrosoftShowDeleted struct{}

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

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

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
}

Example (ManualPaging)

This example demonstrates how to use ControlPaging to manually execute a paginated search request instead of using SearchWithPaging.

Code:

conn, err := DialURL("ldap://ldap.example.com:389")
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

var pageSize uint32 = 32
searchBase := "dc=example,dc=com"
filter := "(objectClass=group)"
pagingControl := NewControlPaging(pageSize)
attributes := []string{}
controls := []Control{pagingControl}

for {
    request := NewSearchRequest(searchBase, ScopeWholeSubtree, DerefAlways, 0, 0, false, filter, attributes, controls)
    response, err := conn.Search(request)
    if err != nil {
        log.Fatalf("Failed to execute search request: %s", err.Error())
    }

    // [do something with the response entries]

    // In order to prepare the next request, we check if the response
    // contains another ControlPaging object and a not-empty cookie and
    // copy that cookie into our pagingControl object:
    updatedControl := FindControl(response.Controls, ControlTypePaging)
    if ctrl, ok := updatedControl.(*ControlPaging); ctrl != nil && ok && len(ctrl.Cookie) != 0 {
        pagingControl.SetCookie(ctrl.Cookie)
        continue
    }
    // If no new paging information is available or the cookie is empty, we
    // are done with the pagination.
    break
}

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 ControlServerSideSorting

type ControlServerSideSorting struct {
    SortKeys []*SortKey
}

func NewControlServerSideSorting

func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error)

func NewControlServerSideSortingWithSortKeys

func NewControlServerSideSortingWithSortKeys(sortKeys []*SortKey) *ControlServerSideSorting

func (*ControlServerSideSorting) Encode

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

func (*ControlServerSideSorting) GetControlType

func (c *ControlServerSideSorting) GetControlType() string

func (*ControlServerSideSorting) String

func (c *ControlServerSideSorting) String() string

type ControlServerSideSortingCode

type ControlServerSideSortingCode int64
const (
    ControlServerSideSortingCodeSuccess                  ControlServerSideSortingCode = 0
    ControlServerSideSortingCodeOperationsError          ControlServerSideSortingCode = 1
    ControlServerSideSortingCodeTimeLimitExceeded        ControlServerSideSortingCode = 2
    ControlServerSideSortingCodeStrongAuthRequired       ControlServerSideSortingCode = 8
    ControlServerSideSortingCodeAdminLimitExceeded       ControlServerSideSortingCode = 11
    ControlServerSideSortingCodeNoSuchAttribute          ControlServerSideSortingCode = 16
    ControlServerSideSortingCodeInappropriateMatching    ControlServerSideSortingCode = 18
    ControlServerSideSortingCodeInsufficientAccessRights ControlServerSideSortingCode = 50
    ControlServerSideSortingCodeBusy                     ControlServerSideSortingCode = 51
    ControlServerSideSortingCodeUnwillingToPerform       ControlServerSideSortingCode = 53
    ControlServerSideSortingCodeOther                    ControlServerSideSortingCode = 80
)

func (ControlServerSideSortingCode) Valid

func (c ControlServerSideSortingCode) Valid() error

Valid test the code contained in the control against the ControlServerSideSortingCodes slice and return an error if the code is unknown.

type ControlServerSideSortingResult

type ControlServerSideSortingResult struct {
    Criticality bool

    Result ControlServerSideSortingCode
}

func NewControlServerSideSortingResult

func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSortingResult, error)

func (*ControlServerSideSortingResult) Encode

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

func (*ControlServerSideSortingResult) GetControlType

func (control *ControlServerSideSortingResult) GetControlType() string

func (*ControlServerSideSortingResult) String

func (c *ControlServerSideSortingResult) String() string

type ControlString

ControlString implements the Control interface for simple controls

type ControlString struct {
    ControlType  string
    Criticality  bool
    ControlValue string
}

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

ControlSubtreeDelete implements the subtree delete control described in https://datatracker.ietf.org/doc/html/draft-armijo-ldap-treedelete-02

type ControlSubtreeDelete struct{}

func NewControlSubtreeDelete

func NewControlSubtreeDelete() *ControlSubtreeDelete

NewControlSubtreeDelete returns a ControlSubtreeDelete control.

func (*ControlSubtreeDelete) Encode

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

Encode returns the ber packet representation

func (*ControlSubtreeDelete) GetControlType

func (c *ControlSubtreeDelete) GetControlType() string

GetControlType returns the OID

func (*ControlSubtreeDelete) String

func (c *ControlSubtreeDelete) String() string

type ControlSyncDone

ControlSyncDone implements the Sync Done Control described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncDone struct {
    Criticality    bool
    Cookie         []byte
    RefreshDeletes bool
}

func NewControlSyncDone

func NewControlSyncDone(pkt *ber.Packet) (*ControlSyncDone, error)

func (*ControlSyncDone) Encode

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

Encode encodes the control

func (*ControlSyncDone) GetControlType

func (c *ControlSyncDone) GetControlType() string

GetControlType returns the OID

func (*ControlSyncDone) String

func (c *ControlSyncDone) String() string

String returns a human-readable description

type ControlSyncInfo

ControlSyncInfo implements the Sync Info Control described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncInfo struct {
    Criticality    bool
    Value          ControlSyncInfoValue
    NewCookie      *ControlSyncInfoNewCookie
    RefreshDelete  *ControlSyncInfoRefreshDelete
    RefreshPresent *ControlSyncInfoRefreshPresent
    SyncIdSet      *ControlSyncInfoSyncIdSet
}

func NewControlSyncInfo

func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error)

func (*ControlSyncInfo) Encode

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

Encode encodes the control

func (*ControlSyncInfo) GetControlType

func (c *ControlSyncInfo) GetControlType() string

GetControlType returns the OID

func (*ControlSyncInfo) String

func (c *ControlSyncInfo) String() string

String returns a human-readable description

type ControlSyncInfoNewCookie

ControlSyncInfoNewCookie implements a part of syncInfoValue described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncInfoNewCookie struct {
    Cookie []byte
}

func (*ControlSyncInfoNewCookie) String

func (c *ControlSyncInfoNewCookie) String() string

String returns a human-readable description

type ControlSyncInfoRefreshDelete

ControlSyncInfoRefreshDelete implements a part of syncInfoValue described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncInfoRefreshDelete struct {
    Cookie      []byte
    RefreshDone bool
}

func (*ControlSyncInfoRefreshDelete) String

func (c *ControlSyncInfoRefreshDelete) String() string

String returns a human-readable description

type ControlSyncInfoRefreshPresent

ControlSyncInfoRefreshPresent implements a part of syncInfoValue described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncInfoRefreshPresent struct {
    Cookie      []byte
    RefreshDone bool
}

func (*ControlSyncInfoRefreshPresent) String

func (c *ControlSyncInfoRefreshPresent) String() string

String returns a human-readable description

type ControlSyncInfoSyncIdSet

ControlSyncInfoSyncIdSet implements a part of syncInfoValue described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncInfoSyncIdSet struct {
    Cookie         []byte
    RefreshDeletes bool
    SyncUUIDs      []uuid.UUID
}

func (*ControlSyncInfoSyncIdSet) String

func (c *ControlSyncInfoSyncIdSet) String() string

String returns a human-readable description

type ControlSyncInfoValue

Tag For ControlSyncInfo

type ControlSyncInfoValue uint64
const (
    SyncInfoNewcookie      ControlSyncInfoValue = 0
    SyncInfoRefreshDelete  ControlSyncInfoValue = 1
    SyncInfoRefreshPresent ControlSyncInfoValue = 2
    SyncInfoSyncIdSet      ControlSyncInfoValue = 3
)

type ControlSyncRequest

ControlSyncRequest implements the Sync Request Control described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncRequest struct {
    Criticality bool
    Mode        ControlSyncRequestMode
    Cookie      []byte
    ReloadHint  bool
}

func NewControlSyncRequest

func NewControlSyncRequest(
    mode ControlSyncRequestMode, cookie []byte, reloadHint bool,
) *ControlSyncRequest

func (*ControlSyncRequest) Encode

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

Encode encodes the control

func (*ControlSyncRequest) GetControlType

func (c *ControlSyncRequest) GetControlType() string

GetControlType returns the OID

func (*ControlSyncRequest) String

func (c *ControlSyncRequest) String() string

String returns a human-readable description

type ControlSyncRequestMode

Mode for ControlTypeSyncRequest

type ControlSyncRequestMode int64
const (
    SyncRequestModeRefreshOnly       ControlSyncRequestMode = 1
    SyncRequestModeRefreshAndPersist ControlSyncRequestMode = 3
)

type ControlSyncState

ControlSyncState implements the Sync State Control described in https://www.ietf.org/rfc/rfc4533.txt

type ControlSyncState struct {
    Criticality bool
    State       ControlSyncStateState
    EntryUUID   uuid.UUID
    Cookie      []byte
}

func NewControlSyncState

func NewControlSyncState(pkt *ber.Packet) (*ControlSyncState, error)

func (*ControlSyncState) Encode

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

Encode encodes the control

func (*ControlSyncState) GetControlType

func (c *ControlSyncState) GetControlType() string

GetControlType returns the OID

func (*ControlSyncState) String

func (c *ControlSyncState) String() string

String returns a human-readable description

type ControlSyncStateState

State for ControlSyncState

type ControlSyncStateState int64
const (
    SyncStatePresent ControlSyncStateState = 0
    SyncStateAdd     ControlSyncStateState = 1
    SyncStateModify  ControlSyncStateState = 2
    SyncStateDelete  ControlSyncStateState = 3
)

type ControlVChuPasswordMustChange

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

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

func (*ControlVChuPasswordMustChange) Encode

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

Encode returns the ber packet representation

func (*ControlVChuPasswordMustChange) GetControlType

func (c *ControlVChuPasswordMustChange) GetControlType() string

GetControlType returns the OID

func (*ControlVChuPasswordMustChange) String

func (c *ControlVChuPasswordMustChange) String() string

String returns a human-readable description

type ControlVChuPasswordWarning

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

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

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

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

type DN struct {
    RDNs []*RelativeDN
}

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

EqualFold 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 DelRequest

DelRequest implements an LDAP deletion request

type DelRequest struct {
    // DN is the name of the directory entry to delete
    DN string
    // Controls hold optional controls to send with the request
    Controls []Control
}

func NewDelRequest

func NewDelRequest(DN string, Controls []Control) *DelRequest

NewDelRequest creates a delete request for the given DN and controls

type DialContext

DialContext contains necessary parameters to dial the given ldap URL.

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

type DialOpt

DialOpt configures DialContext.

type DialOpt func(*DialContext)

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

DigestMD5BindRequest represents a digest-md5 bind operation

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
}

type DigestMD5BindResult

DigestMD5BindResult contains the response from the server

type DigestMD5BindResult struct {
    Controls []Control
}

type Entry

Entry represents a single search result entry

type Entry struct {
    // DN is the distinguished name of the entry
    DN string
    // Attributes are the returned attributes for the entry
    Attributes []*EntryAttribute
}

func NewEntry

func NewEntry(dn string, attributes map[string][]string) *Entry

NewEntry returns an Entry object with the specified distinguished name and attribute key-value pairs. The map of attributes is accessed in alphabetical order of the keys in order to ensure that, for the same input map of attributes, the output entry will contain the same order of attributes

func (*Entry) GetAttributeValue

func (e *Entry) GetAttributeValue(attribute string) string

GetAttributeValue returns the first value for the named attribute, or ""

func (*Entry) GetAttributeValues

func (e *Entry) GetAttributeValues(attribute string) []string

GetAttributeValues returns the values for the named attribute, or an empty list

func (*Entry) GetEqualFoldAttributeValue

func (e *Entry) GetEqualFoldAttributeValue(attribute string) string

GetEqualFoldAttributeValue returns the first value for the named attribute, or "". Attribute comparison is done with strings.EqualFold.

func (*Entry) GetEqualFoldAttributeValues

func (e *Entry) GetEqualFoldAttributeValues(attribute string) []string

GetEqualFoldAttributeValues returns the values for the named attribute, or an empty list. Attribute matching is done with strings.EqualFold.

func (*Entry) GetEqualFoldRawAttributeValue

func (e *Entry) GetEqualFoldRawAttributeValue(attribute string) []byte

GetEqualFoldRawAttributeValue returns the first value for the named attribute, or an empty slice

func (*Entry) GetEqualFoldRawAttributeValues

func (e *Entry) GetEqualFoldRawAttributeValues(attribute string) [][]byte

GetEqualFoldRawAttributeValues returns the byte values for the named attribute, or an empty list

func (*Entry) GetRawAttributeValue

func (e *Entry) GetRawAttributeValue(attribute string) []byte

GetRawAttributeValue returns the first value for the named attribute, or an empty slice

func (*Entry) GetRawAttributeValues

func (e *Entry) GetRawAttributeValues(attribute string) [][]byte

GetRawAttributeValues returns the byte values for the named attribute, or an empty list

func (*Entry) PrettyPrint

func (e *Entry) PrettyPrint(indent int)

PrettyPrint outputs a human-readable description indenting

func (*Entry) Print

func (e *Entry) Print()

Print outputs a human-readable description

func (*Entry) Unmarshal

func (e *Entry) Unmarshal(i interface{}) (err error)

Unmarshal parses the Entry in the value pointed to by i

Currently, this methods only supports struct fields of type string, []string, int, int64, []byte, *DN, []*DN or time.Time. Other field types will not be regarded. If the field type is a string or int but multiple attribute values are returned, the first value will be used to fill the field.

Example:

type UserEntry struct {
	// Fields with the tag key `dn` are automatically filled with the
	// objects distinguishedName. This can be used multiple times.
	DN string `ldap:"dn"`

	// This field will be filled with the attribute value for
	// userPrincipalName. An attribute can be read into a struct field
	// multiple times. Missing attributes will not result in an error.
	UserPrincipalName string `ldap:"userPrincipalName"`

	// memberOf may have multiple values. If you don't
	// know the amount of attribute values at runtime, use a string array.
	MemberOf []string `ldap:"memberOf"`

	// ID is an integer value, it will fail unmarshaling when the given
	// attribute value cannot be parsed into an integer.
	ID int `ldap:"id"`

	// LongID is similar to ID but uses an int64 instead.
	LongID int64 `ldap:"longId"`

	// Data is similar to MemberOf a slice containing all attribute
	// values.
	Data []byte `ldap:"data"`

	// Time is parsed with the generalizedTime spec into a time.Time
	Created time.Time `ldap:"createdTimestamp"`

	// *DN is parsed with the ParseDN
	Owner *ldap.DN `ldap:"owner"`

	// []*DN is parsed with the ParseDN
	Children []*ldap.DN `ldap:"children"`

	// This won't work, as the field is not of type string. For this
	// to work, you'll have to temporarily store the result in string
	// (or string array) and convert it to the desired type afterwards.
	UserAccountControl uint32 `ldap:"userPrincipalName"`
}
user := UserEntry{}

if err := result.Unmarshal(&user); err != nil {
	// ...
}

type EntryAttribute

EntryAttribute holds a single attribute

type EntryAttribute struct {
    // Name is the name of the attribute
    Name string
    // Values contain the string values of the attribute
    Values []string
    // ByteValues contain the raw values of the attribute
    ByteValues [][]byte
}

func NewEntryAttribute

func NewEntryAttribute(name string, values []string) *EntryAttribute

NewEntryAttribute returns a new EntryAttribute with the desired key-value pair

func (*EntryAttribute) PrettyPrint

func (e *EntryAttribute) PrettyPrint(indent int)

PrettyPrint outputs a human-readable description with indenting

func (*EntryAttribute) Print

func (e *EntryAttribute) Print()

Print outputs a human-readable description

type Error

Error holds LDAP error information

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
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type GSSAPIBindRequest

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

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
}

type GSSAPIClient

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 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
}

type ModifyDNRequest

ModifyDNRequest holds the request to modify a DN

type ModifyDNRequest struct {
    DN           string
    NewRDN       string
    DeleteOldRDN bool
    NewSuperior  string
    // Controls hold optional controls to send with the request
    Controls []Control
}

func NewModifyDNRequest

func NewModifyDNRequest(dn string, rdn string, delOld bool, newSup string) *ModifyDNRequest

NewModifyDNRequest creates a new request which can be passed to ModifyDN().

To move an object in the tree, set the "newSup" to the new parent entry DN. Use an empty string for just changing the object's RDN.

For moving the object without renaming, the "rdn" must be the first RDN of the given DN.

A call like

mdnReq := NewModifyDNRequest("uid=someone,dc=example,dc=org", "uid=newname", true, "")

will setup the request to just rename uid=someone,dc=example,dc=org to uid=newname,dc=example,dc=org.

func NewModifyDNWithControlsRequest

func NewModifyDNWithControlsRequest(dn string, rdn string, delOld bool,
    newSup string, controls []Control) *ModifyDNRequest

NewModifyDNWithControlsRequest creates a new request which can be passed to ModifyDN() and also allows setting LDAP request controls.

Refer NewModifyDNRequest for other parameters

type ModifyRequest

ModifyRequest as defined in https://tools.ietf.org/html/rfc4511

type ModifyRequest struct {
    // DN is the distinguishedName of the directory entry to modify
    DN string
    // Changes contain the attributes to modify
    Changes []Change
    // Controls hold optional controls to send with the request
    Controls []Control
}

func NewModifyRequest

func NewModifyRequest(dn string, controls []Control) *ModifyRequest

NewModifyRequest creates a modify request for the given DN

func (*ModifyRequest) Add

func (req *ModifyRequest) Add(attrType string, attrVals []string)

Add appends the given attribute to the list of changes to be made

func (*ModifyRequest) Delete

func (req *ModifyRequest) Delete(attrType string, attrVals []string)

Delete appends the given attribute to the list of changes to be made

func (*ModifyRequest) Increment

func (req *ModifyRequest) Increment(attrType string, attrVal string)

Increment appends the given attribute to the list of changes to be made

func (*ModifyRequest) Replace

func (req *ModifyRequest) Replace(attrType string, attrVals []string)

Replace appends the given attribute to the list of changes to be made

type ModifyResult

ModifyResult holds the server's response to a modify request

type ModifyResult struct {
    // Controls are the returned controls
    Controls []Control
    // Referral is the returned referral
    Referral string
}

type NTLMBindRequest

NTLMBindRequest represents an NTLMSSP bind operation

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
}

type NTLMBindResult

NTLMBindResult contains the response from the server

type NTLMBindResult struct {
    Controls []Control
}

type PacketResponse

PacketResponse contains the packet or error encountered reading a response

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

func (*PacketResponse) ReadPacket

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

ReadPacket returns the packet or an error

type PartialAttribute

PartialAttribute for a ModifyRequest as defined in https://tools.ietf.org/html/rfc4511

type PartialAttribute struct {
    // Type is the type of the partial attribute
    Type string
    // Vals are the values of the partial attribute
    Vals []string
}

type PasswordModifyRequest

PasswordModifyRequest implements the Password Modify Extended Operation as defined in https://www.ietf.org/rfc/rfc3062.txt

type PasswordModifyRequest struct {
    // UserIdentity is an optional string representation of the user associated with the request.
    // This string may or may not be an LDAPDN [RFC2253].
    // If no UserIdentity field is present, the request acts up upon the password of the user currently associated with the LDAP session
    UserIdentity string
    // OldPassword, if present, contains the user's current password
    OldPassword string
    // NewPassword, if present, contains the desired password for this user
    NewPassword string
}

func NewPasswordModifyRequest

func NewPasswordModifyRequest(userIdentity string, oldPassword string, newPassword string) *PasswordModifyRequest

NewPasswordModifyRequest creates a new PasswordModifyRequest

According to the RFC 3602 (https://tools.ietf.org/html/rfc3062): userIdentity is a string representing the user associated with the request. This string may or may not be an LDAPDN (RFC 2253). If userIdentity is empty then the operation will act on the user associated with the session.

oldPassword is the current user's password, it can be empty or it can be needed depending on the session user access rights (usually an administrator can change a user's password without knowing the current one) and the password policy (see pwdSafeModify password policy's attribute)

newPassword is the desired user's password. If empty the server can return an error or generate a new password that will be available in the PasswordModifyResult.GeneratedPassword

type PasswordModifyResult

PasswordModifyResult holds the server response to a PasswordModifyRequest

type PasswordModifyResult struct {
    // GeneratedPassword holds a password generated by the server, if present
    GeneratedPassword string
    // Referral are the returned referral
    Referral string
}

type RelativeDN

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

type RelativeDN struct {
    Attributes []*AttributeTypeAndValue
}

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

EqualFold 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 Response

Response defines an interface to get data from an LDAP server

type Response interface {
    Entry() *Entry
    Referral() string
    Controls() []Control
    Err() error
    Next() bool
}

type SearchRequest

SearchRequest represents a search request to send to the server

type SearchRequest struct {
    BaseDN       string
    Scope        int
    DerefAliases int
    SizeLimit    int
    TimeLimit    int
    TypesOnly    bool
    Filter       string
    Attributes   []string
    Controls     []Control
}

func NewSearchRequest

func NewSearchRequest(
    BaseDN string,
    Scope, DerefAliases, SizeLimit, TimeLimit int,
    TypesOnly bool,
    Filter string,
    Attributes []string,
    Controls []Control,
) *SearchRequest

NewSearchRequest creates a new search request

type SearchResult

SearchResult holds the server's response to a search request

type SearchResult struct {
    // Entries are the returned entries
    Entries []*Entry
    // Referrals are the returned referrals
    Referrals []string
    // Controls are the returned controls
    Controls []Control
}

func (*SearchResult) PrettyPrint

func (s *SearchResult) PrettyPrint(indent int)

PrettyPrint outputs a human-readable description with indenting

func (*SearchResult) Print

func (s *SearchResult) Print()

Print outputs a human-readable description

type SearchSingleResult

SearchSingleResult holds the server's single entry response to a search request

type SearchSingleResult struct {
    // Entry is the returned entry
    Entry *Entry
    // Referral is the returned referral
    Referral string
    // Controls are the returned controls
    Controls []Control
    // Error is set when the search request was failed
    Error error
}

func (*SearchSingleResult) PrettyPrint

func (s *SearchSingleResult) PrettyPrint(indent int)

PrettyPrint outputs a human-readable description with indenting

func (*SearchSingleResult) Print

func (s *SearchSingleResult) Print()

Print outputs a human-readable description

type SimpleBindRequest

SimpleBindRequest represents a username/password bind operation

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
}

func NewSimpleBindRequest

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

NewSimpleBindRequest returns a bind request

type SimpleBindResult

SimpleBindResult contains the response from the server

type SimpleBindResult struct {
    Controls []Control
}

type SortKey

type SortKey struct {
    Reverse       bool
    AttributeType string
    MatchingRule  string
}

type WhoAmIResult

WhoAmIResult is returned by the WhoAmI() call

type WhoAmIResult struct {
    AuthzID string
}

Subdirectories

Name Synopsis
..
gssapi