go-ldap/ldap

repository·master·Indexed 25 days ago

https://github.com/go-ldap/ldap

A Go implementation of the LDAP v3 protocol providing comprehensive support for LDAP operations, authentication mechanisms, and advanced controls. It implements RFC 4511 (Basic Operations), RFC 4514 (DN Parsing), and RFC 4533 (Content Synchronization). Key features include connection management (TLS, STARTTLS, ldapi), various authentication binds (Simple, GSSAPI, SASL, NTLM, External), and data operations such as Search (including paging and asynchronous), Add, Delete, and Modify.

Tokens
15.9K
Snippets
27
Records
108
Agent score
81%

What's inside go-ldap/ldap

  1. Overview of go-ldap/ldap features

    master

    The go-ldap/ldap library provides basic LDAP v3 functionality for the Go programming language, implementing several RFC specifications including RFC 4511 (Basic Operations), RFC 4514 (DN Parsing), and RFC 4533 (Content Synchronization).

    Key capabilities include:

    • Connection Management: Support for non-TLS, TLS, STARTTLS, and custom dialers.
    • Authentication: Bind requests/responses supporting Simple Bind, GSSAPI, and SASL.
    • Operations: Search (normal, paging, and asynchronous), Modify, Add, Delete, Modify DN, Unbind, and Password Modify.
    • Advanced Features: LDAPv3 Filter Compile/Decompile, Server Side Sorting, Content Synchronization, and LDAPv3 Control/Extended Operation support.
  2. How to iterate through LDAP search results

    master

    The Response interface uses an iterator pattern. You call Next() to move to the next item in the result set. After each successful Next() call, you check Err() to see if the operation failed, and then use Entry(), Referral(), or Controls() to inspect the data. The loop terminates when Next() returns false.

    for resp.Next() {
        if err := resp.Err(); err != nil {
            // The search failed or an error occurred in the stream
            log.Fatal(err)
        }
    
        // Check for an entry
        if entry := resp.Entry(); entry != nil {
            fmt.Printf("Found entry: %s\n", entry.DN)
        }
    
        // Check for a referral
        if ref := resp.Referral(); ref != "" {
            fmt.Printf("Referral to: %s\n", ref)
        }
    }
  3. Represent DN components: AttributeTypeAndValue, RelativeDN, and DN

    master

    The DN hierarchy is composed of three main types:

    1. AttributeTypeAndValue: A single attribute pair (e.g., cn=John Doe).
      • Type: The attribute name.
      • Value: The attribute value.
    2. RelativeDN: A collection of *AttributeTypeAndValue objects (e.g., cn=John Doe+sn=Doe).
    3. DN: A collection of *RelativeDN objects separated by commas (e.g., cn=John Doe,ou=users,o=acme.com).
  4. Use the Control interface for LDAP controls

    master

    The Control interface is the core abstraction for LDAP controls. Any type implementing this interface can be used to encode and describe itself for LDAP operations. To implement a custom control, you must provide methods to retrieve its OID, encode it into a BER (Basic Encoding Rules) packet, and return a human-readable string.

    Required methods:

    • GetControlType() string: Returns the Object Identifier (OID) of the control.
    • Encode() *ber.Packet: Returns the BER packet representation of the control.
    • String() string: Returns a human-readable description.
    type Control interface {
    	GetControlType() string
    	Encode() *ber.Packet
    	String() string
    }
  5. Create and execute an LDAP Add operation

    master
    To add a new entry to an LDAP directory, use NewAddRequest to initialize a request for a specific Distinguished Name (DN), populate it with attributes using the Attribute method, and then pass the request to Conn.Add.
  6. Create and execute a ModifyRequest

    master

    To modify an existing LDAP entry, use NewModifyRequest to initialize a request for a specific Distinguished Name (DN). You can then use helper methods to append various attribute changes. Finally, call Modify or ModifyWithResult on your connection to execute the request.

    Available change methods on *ModifyRequest:

    • Add(attrType string, attrVals []string): Appends a new attribute value.
    • Delete(attrType string, attrVals []string): Removes specific attribute values.
    • Replace(attrType string, attrVals []string): Replaces all existing values for an attribute with the provided ones.
    • Increment(attrType string, attrVal string): Increments a numeric attribute (RFC 4525).
  7. Close an LDAP connection

    master
    The Close() method gracefully shuts down the connection. It attempts to send a MessageQuit to the server and waits for confirmation (subject to the configured request timeout) before closing the underlying network connection.
  8. Escape Distinguished Names (DN)

    master
    Use EscapeDN to escape Distinguished Names according to RFC4514. This function handles escaping for characters such as ", +, ,, ;, <, >, and \. It also handles leading/trailing spaces, leading # characters, and replaces null bytes with \00.
  9. Handle LDAP errors using the Error type

    master

    The ldap.Error struct is the primary way to handle errors returned by an LDAP server. It contains the underlying Go error, the specific LDAP ResultCode, and optional metadata like the MatchedDN or the raw BER Packet.

    You can use errors.As to check if an error is an *ldap.Error and access its fields, or use the provided helper functions to check for specific result codes.

  10. Implement a simple LDAP control with ControlString

    master

    For simple LDAP controls that do not require complex data structures, use ControlString. This is a convenient implementation of the Control interface that allows you to specify an OID, criticality, and an optional control value.

    Use NewControlString(controlType string, criticality bool, controlValue string) to instantiate it.

  11. Implement LDAP Paging with ControlPaging

    master

    The ControlPaging type implements the paging control (RFC 2696). It is used to retrieve search results in pages to avoid overwhelming the client or server.

    Key fields:

    • PagingSize: The number of entries to return in the page.
    • Cookie: An opaque value returned by the server to track the paging cursor. Use SetCookie(cookie []byte) to update it.

    Use NewControlPaging(pagingSize uint32) to create a new paging control.