Documentation
¶
Overview ¶
Package ldap provides a simplified interface for LDAP operations with Active Directory support.
Package ldap provides a simple wrapper around go-ldap/ldap for common LDAP and Active Directory operations.
This package simplifies common LDAP operations including:
- User authentication and password management
- User, group, and computer object queries
- User creation and deletion
- Group membership management
The package is designed to work with both generic LDAP servers and Microsoft Active Directory, with special handling for AD-specific features like password changes and user account control flags.
Basic Usage ¶
config := ldap.Config{
Server: "ldaps://ldap.example.com:636",
BaseDN: "dc=example,dc=com",
IsActiveDirectory: true,
}
client, err := ldap.New(config, "cn=admin,dc=example,dc=com", "password")
if err != nil {
log.Fatal(err)
}
// Authenticate a user
user, err := client.CheckPasswordForSAMAccountName("username", "password")
if err != nil {
log.Printf("Authentication failed: %v", err)
return
}
fmt.Printf("Authenticated user: %s\n", user.CN())
// Find users
users, err := client.FindUsers()
if err != nil {
log.Printf("Failed to find users: %v", err)
return
}
for _, u := range users {
fmt.Printf("User: %s (%s)\n", u.CN(), u.SAMAccountName)
}
Active Directory Considerations ¶
When working with Active Directory, set IsActiveDirectory to true in the Config. This enables AD-specific features:
- Password changes require LDAPS connection
- Proper handling of User Account Control flags
- Support for AD-specific attributes
Error Handling ¶
The package defines specific error variables for common scenarios:
- ErrUserNotFound: User lookup failed
- ErrGroupNotFound: Group lookup failed
- ErrComputerNotFound: Computer lookup failed
- ErrDNDuplicated: Distinguished name is not unique
- ErrSAMAccountNameDuplicated: SAM account name already exists
- ErrMailDuplicated: Email address already exists
- ErrActiveDirectoryMustBeLDAPS: LDAPS required for AD password operations
Always check for these specific errors when appropriate to provide better error handling in your applications.
Index ¶
- Variables
- type Computer
- type Config
- type FullUser
- type Group
- type LDAP
- func (l *LDAP) AddUserToGroup(dn, groupDN string) error
- func (l *LDAP) ChangePasswordForSAMAccountName(sAMAccountName, oldPassword, newPassword string) (err error)
- func (l *LDAP) CheckPasswordForDN(dn, password string) (*User, error)
- func (l *LDAP) CheckPasswordForSAMAccountName(sAMAccountName, password string) (*User, error)
- func (l *LDAP) CreateUser(user FullUser, password string) (string, error)
- func (l *LDAP) DeleteUser(dn string) error
- func (l *LDAP) FindComputerByDN(dn string) (computer *Computer, err error)
- func (l *LDAP) FindComputerBySAMAccountName(sAMAccountName string) (computer *Computer, err error)
- func (l *LDAP) FindComputers() (computers []Computer, err error)
- func (l *LDAP) FindGroupByDN(dn string) (group *Group, err error)
- func (l *LDAP) FindGroups() (groups []Group, err error)
- func (l *LDAP) FindUserByDN(dn string) (user *User, err error)
- func (l *LDAP) FindUserByMail(mail string) (user *User, err error)
- func (l *LDAP) FindUserBySAMAccountName(sAMAccountName string) (user *User, err error)
- func (l *LDAP) FindUsers() (users []User, err error)
- func (l LDAP) GetConnection() (*ldap.Conn, error)
- func (l *LDAP) RemoveUserFromGroup(dn, groupDN string) error
- func (l *LDAP) WithCredentials(dn, password string) (*LDAP, error)
- type Object
- type SamAccountType
- type UAC
- type User
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUserNotFound is returned when a user search operation finds no matching entries. ErrUserNotFound = errors.New("user not found") // ErrSAMAccountNameDuplicated is returned when multiple users have the same sAMAccountName, // indicating a data integrity issue in the directory. ErrSAMAccountNameDuplicated = errors.New("sAMAccountName is not unique") // ErrMailDuplicated is returned when multiple users have the same email address, // indicating a data integrity issue in the directory. ErrMailDuplicated = errors.New("mail is not unique") )
var ( // ErrActiveDirectoryMustBeLDAPS is returned when attempting to change passwords on Active Directory // over an unencrypted connection. Password changes in AD require LDAPS (LDAP over SSL/TLS). ErrActiveDirectoryMustBeLDAPS = errors.New("ActiveDirectory servers must be connected to via LDAPS to change passwords") )
var ErrComputerNotFound = errors.New("computer not found")
ErrComputerNotFound is returned when a computer search operation finds no matching entries.
var ErrDNDuplicated = errors.New("DN is not unique")
ErrDNDuplicated is returned when a search operation finds multiple entries with the same DN, indicating a data integrity issue.
var ErrGroupNotFound = errors.New("group not found")
ErrGroupNotFound is returned when a group search operation finds no matching entries.
Functions ¶
This section is empty.
Types ¶
type Computer ¶
type Computer struct {
Object
// SAMAccountName is the Security Account Manager account name for the computer (typically ends with $).
SAMAccountName string
// Enabled indicates whether the computer account is enabled (not disabled by userAccountControl).
Enabled bool
// OS contains the operating system name from the operatingSystem attribute.
OS string
// OSVersion contains the operating system version from the operatingSystemVersion attribute.
OSVersion string
// Groups contains a list of distinguished names (DNs) of groups the computer belongs to.
Groups []string
}
Computer represents an LDAP computer object with common attributes.
type Config ¶
type Config struct {
// Server is the LDAP server URL (e.g., "ldap://localhost:389" or "ldaps://domain.com:636")
Server string
// BaseDN is the base distinguished name for LDAP searches (e.g., "DC=example,DC=com")
BaseDN string
// IsActiveDirectory indicates whether the server is Microsoft Active Directory.
// This affects password change operations which require LDAPS for AD.
IsActiveDirectory bool
// DialOptions contains additional options for the LDAP connection
DialOptions []ldap.DialOpt
}
Config holds the configuration for connecting to an LDAP server.
type FullUser ¶
type FullUser struct {
// CN is the common name of the user (required, used as the RDN component).
CN string
// SAMAccountName is the Security Account Manager account name (optional for creation).
SAMAccountName *string
// FirstName is the user's given name (required).
FirstName string
// LastName is the user's surname (required).
LastName string
// DisplayName is the name displayed in address lists (optional, defaults to CN if nil).
DisplayName *string
// Description contains additional information about the user (optional).
Description *string
// Email is the user's email address (optional).
Email *string
// ObjectClasses defines the LDAP object classes (optional, defaults to standard user classes).
ObjectClasses []string
// AccountExpires represents the expiration date of the user's account.
// When set to nil, the account never expires.
AccountExpires *time.Time
// UserAccountControl contains the account control flags (enabled/disabled, password policies, etc.).
UserAccountControl UAC
// Path specifies the organizational unit path relative to BaseDN (optional, defaults to BaseDN).
Path *string
}
FullUser represents a complete user object for creation operations with all configurable attributes.
type Group ¶
type Group struct {
Object
// Members contains a list of distinguished names (DNs) of group members.
Members []string
}
Group represents an LDAP group object with its members.
type LDAP ¶
type LDAP struct {
// contains filtered or unexported fields
}
LDAP represents a client connection to an LDAP server with authentication credentials.
func New ¶
New creates a new LDAP client with the specified configuration and credentials. It validates the connection by attempting to connect and authenticate with the provided credentials.
Parameters:
- config: The LDAP server configuration including server URL and base DN
- user: The distinguished name (DN) or username for authentication
- password: The password for authentication
Returns:
- *LDAP: A configured LDAP client ready for operations
- error: Any error encountered during connection validation
Example:
config := Config{
Server: "ldaps://ad.example.com:636",
BaseDN: "DC=example,DC=com",
IsActiveDirectory: true,
}
client, err := New(config, "CN=admin,CN=Users,DC=example,DC=com", "password")
func (*LDAP) AddUserToGroup ¶
AddUserToGroup adds a user to a group by modifying the group's member attribute.
Parameters:
- dn: The distinguished name of the user to add to the group
- groupDN: The distinguished name of the group to modify
Returns:
- error: Any LDAP operation error, including insufficient permissions or if the user is already a member
This operation requires write permissions on the target group object.
func (*LDAP) ChangePasswordForSAMAccountName ¶
func (l *LDAP) ChangePasswordForSAMAccountName(sAMAccountName, oldPassword, newPassword string) (err error)
ChangePasswordForSAMAccountName changes a user's password in Active Directory. This method requires the current password for authentication and changes it to the new password.
Parameters:
- sAMAccountName: The Security Account Manager account name of the user
- oldPassword: The current password (required for authentication)
- newPassword: The new password to set
Returns:
- error: ErrActiveDirectoryMustBeLDAPS if trying to change AD passwords over unencrypted connection, ErrUserNotFound if user doesn't exist, authentication error if old password is wrong, or any other LDAP operation error
Requirements:
- For Active Directory servers, LDAPS (SSL/TLS) connection is mandatory
- User must provide their current password for verification
- New password must meet the domain's password policy requirements
The password change uses the Microsoft-specific unicodePwd attribute with proper UTF-16LE encoding. Reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/6e803168-f140-4d23-b2d3-c3a8ab5917d2
func (*LDAP) CheckPasswordForDN ¶
CheckPasswordForDN validates a user's password by attempting to bind with their credentials. This method finds the user by their distinguished name and then attempts authentication.
Parameters:
- dn: The distinguished name of the user (e.g., "CN=John Doe,CN=Users,DC=example,DC=com")
- password: The password to validate
Returns:
- *User: The user object if authentication succeeds
- error: ErrUserNotFound if the user doesn't exist, or authentication error if credentials are invalid
This method is useful when you already have the user's DN and want to validate their password.
func (*LDAP) CheckPasswordForSAMAccountName ¶
CheckPasswordForSAMAccountName validates a user's password by attempting to bind with their credentials. This method finds the user by their sAMAccountName and then attempts authentication.
Parameters:
- sAMAccountName: The Security Account Manager account name (e.g., "jdoe" for john.doe@domain.com)
- password: The password to validate
Returns:
- *User: The user object if authentication succeeds
- error: ErrUserNotFound if the user doesn't exist, or authentication error if credentials are invalid
This is commonly used for login validation in Active Directory environments.
func (*LDAP) CreateUser ¶
CreateUser creates a new user in the directory with the specified attributes.
Parameters:
- user: The FullUser object containing all user attributes
- password: The initial password for the user (currently not implemented in this version)
Returns:
- string: The distinguished name of the created user
- error: Any LDAP operation error, including duplicate entries or insufficient permissions
Default behaviors:
- ObjectClasses defaults to ["top", "person", "organizationalPerson", "user"] if not specified
- DisplayName defaults to CN if not specified
- The user is created at the specified Path relative to BaseDN, or directly under BaseDN if Path is nil
Example:
user := FullUser{
CN: "John Doe",
FirstName: "John",
LastName: "Doe",
SAMAccountName: &"jdoe",
Email: &"john.doe@example.com",
UserAccountControl: UAC{NormalAccount: true},
}
dn, err := client.CreateUser(user, "")
func (*LDAP) DeleteUser ¶
DeleteUser removes a user from the directory.
Parameters:
- dn: The distinguished name of the user to delete
Returns:
- error: Any LDAP operation error, including user not found or insufficient permissions
Warning: This operation is irreversible. Ensure you have proper backups and permissions before deletion.
func (*LDAP) FindComputerByDN ¶
FindComputerByDN retrieves a computer by its distinguished name.
Parameters:
- dn: The distinguished name of the computer (e.g., "CN=COMPUTER01,CN=Computers,DC=example,DC=com")
Returns:
- *Computer: The computer object if found
- error: ErrComputerNotFound if no computer exists with the given DN, ErrDNDuplicated if multiple entries share the same DN (data integrity issue), or any LDAP operation error
func (*LDAP) FindComputerBySAMAccountName ¶
FindComputerBySAMAccountName retrieves a computer by its Security Account Manager account name.
Parameters:
- sAMAccountName: The SAM account name of the computer (e.g., "COMPUTER01$")
Returns:
- *Computer: The computer object if found
- error: ErrComputerNotFound if no computer exists with the given sAMAccountName, ErrSAMAccountNameDuplicated if multiple computers have the same sAMAccountName, or any LDAP operation error
This method performs a subtree search starting from the configured BaseDN. Computer sAMAccountNames typically end with a dollar sign ($).
func (*LDAP) FindComputers ¶
FindComputers retrieves all computer objects from the directory.
Returns:
- []Computer: A slice of all computer objects found in the directory
- error: Any LDAP operation error
This method performs a subtree search starting from the configured BaseDN. Computers that cannot be parsed (due to missing required attributes) are skipped.
func (*LDAP) FindGroupByDN ¶
FindGroupByDN retrieves a group by its distinguished name.
Parameters:
- dn: The distinguished name of the group (e.g., "CN=Administrators,CN=Builtin,DC=example,DC=com")
Returns:
- *Group: The group object if found
- error: ErrGroupNotFound if no group exists with the given DN, ErrDNDuplicated if multiple entries share the same DN (data integrity issue), or any LDAP operation error
func (*LDAP) FindGroups ¶
FindGroups retrieves all group objects from the directory.
Returns:
- []Group: A slice of all group objects found in the directory
- error: Any LDAP operation error
This method performs a subtree search starting from the configured BaseDN. Groups that cannot be parsed are skipped and not included in the results.
func (*LDAP) FindUserByDN ¶
FindUserByDN retrieves a user by their distinguished name.
Parameters:
- dn: The distinguished name of the user (e.g., "CN=John Doe,CN=Users,DC=example,DC=com")
Returns:
- *User: The user object if found
- error: ErrUserNotFound if no user exists with the given DN, ErrDNDuplicated if multiple entries share the same DN (data integrity issue), or any LDAP operation error
func (*LDAP) FindUserByMail ¶
FindUserByMail retrieves a user by their email address.
Parameters:
- mail: The email address to search for (e.g., "john.doe@example.com")
Returns:
- *User: The user object if found
- error: ErrUserNotFound if no user exists with the given email, ErrMailDuplicated if multiple users have the same email address, or any LDAP operation error
This method performs a subtree search starting from the configured BaseDN.
func (*LDAP) FindUserBySAMAccountName ¶
FindUserBySAMAccountName retrieves a user by their Security Account Manager account name.
Parameters:
- sAMAccountName: The SAM account name (e.g., "jdoe" for john.doe@domain.com)
Returns:
- *User: The user object if found
- error: ErrUserNotFound if no user exists with the given sAMAccountName, ErrSAMAccountNameDuplicated if multiple users have the same sAMAccountName, or any LDAP operation error
This method performs a subtree search starting from the configured BaseDN.
func (*LDAP) FindUsers ¶
FindUsers retrieves all user objects from the directory.
Returns:
- []User: A slice of all user objects found in the directory
- error: Any LDAP operation error
This method performs a subtree search starting from the configured BaseDN. Users that cannot be parsed (due to missing required attributes) are skipped.
func (LDAP) GetConnection ¶
GetConnection establishes and returns an authenticated LDAP connection. The connection must be closed by the caller when no longer needed.
Returns:
- *ldap.Conn: An authenticated LDAP connection
- error: Any error encountered during connection or authentication
The returned connection is ready for LDAP operations. Always defer Close() on the connection:
conn, err := client.GetConnection()
if err != nil {
return err
}
defer conn.Close()
func (*LDAP) RemoveUserFromGroup ¶
RemoveUserFromGroup removes a user from a group by modifying the group's member attribute.
Parameters:
- dn: The distinguished name of the user to remove from the group
- groupDN: The distinguished name of the group to modify
Returns:
- error: Any LDAP operation error, including insufficient permissions or if the user is not a member
This operation requires write permissions on the target group object.
func (*LDAP) WithCredentials ¶
WithCredentials creates a new LDAP client using the same configuration but with different credentials. This is useful for operations that need to be performed with different user privileges.
Parameters:
- dn: The distinguished name for the new credentials
- password: The password for the new credentials
Returns:
- *LDAP: A new LDAP client with updated credentials
- error: Any error encountered during connection validation
type Object ¶
type Object struct {
// contains filtered or unexported fields
}
Object represents the base LDAP object with common name and distinguished name.
type SamAccountType ¶
type SamAccountType uint32
SamAccountType represents the Security Account Manager account type values used in Active Directory. This enumeration defines the type of account object and is stored in the sAMAccountType attribute.
Reference: https://learn.microsoft.com/en-us/windows/win32/adschema/a-samaccounttype
const ( // SamDomainObject (0x0) represents a domain object. SamDomainObject SamAccountType = 0x0 // SamGroupObject (0x10000000) represents a security group object. SamGroupObject SamAccountType = 0x10000000 // SamNonSecurityGroupObject (0x10000001) represents a non-security group object. SamNonSecurityGroupObject SamAccountType = 0x10000001 // SamAliasObject (0x20000000) represents an alias object (local group). SamAliasObject SamAccountType = 0x20000000 // SamNonSecurityAliasObject (0x20000001) represents a non-security alias object. SamNonSecurityAliasObject SamAccountType = 0x20000001 // SamUserObject (0x30000000) represents a normal user account (also known as SAM_NORMAL_USER_ACCOUNT). SamUserObject SamAccountType = 0x30000000 // SamMachineAccount (0x30000001) represents a computer/machine account. SamMachineAccount SamAccountType = 0x30000001 // SamTrustAccount (0x30000002) represents an interdomain trust account. SamTrustAccount SamAccountType = 0x30000002 // SamAppBasicGroup (0x40000000) represents an application basic group. SamAppBasicGroup SamAccountType = 0x40000000 // SamAppQueryGroup (0x40000001) represents an application query group. SamAppQueryGroup SamAccountType = 0x40000001 // SamAccountTypeMax (0x7fffffff) represents the maximum account type value. SamAccountTypeMax SamAccountType = 0x7fffffff )
func (SamAccountType) String ¶
func (t SamAccountType) String() string
String returns a human-readable description of the SAM account type.
Returns:
- string: A descriptive name for the account type, or "Unknown" for unrecognized values
This method is useful for logging and debugging to understand what type of account object is being processed.
type UAC ¶
type UAC struct {
// LogonScript (0x1) - Execute a logon script for the user
LogonScript bool
// AccountDisabled (0x2) - The account is disabled
AccountDisabled bool
// HomeDirRequired (0x8) - A home directory is required for the user
HomeDirRequired bool
// Lockout (0x10) - The account is locked out (read-only flag, set by the system)
Lockout bool
// PasswordNotRequired (0x20) - No password is required for the account
PasswordNotRequired bool
// PasswordCantChange (0x40) - The user cannot change their password
PasswordCantChange bool
// EncryptedTextPasswordAllowed (0x80) - Allows encrypted text passwords for the account
EncryptedTextPasswordAllowed bool
// TempDuplicateAccount (0x100) - This is a temporary duplicate account
TempDuplicateAccount bool
// NormalAccount (0x200) - This is a default account type representing a typical user
NormalAccount bool
// InterdomainTrustAccount (0x800) - This is a permit to trust account for a system domain that trusts other domains
InterdomainTrustAccount bool
// WorkstationTrustAccount (0x1000) - This is a computer account for a computer that is a member of this domain
WorkstationTrustAccount bool
// ServerTrustAccount (0x2000) - This is a computer account for a system backup domain controller that is a member of this domain
ServerTrustAccount bool
// NoPasswordExpiration (0x10000) - The password for this account does not expire
NoPasswordExpiration bool
// MNSLogonAccount (0x20000) - This is an MNS logon account
MNSLogonAccount bool
// SmartCardRequired (0x40000) - The user is required to log on using a smart card
SmartCardRequired bool
// TrustedForDelegation (0x80000) - The service account (user or computer account) under which a service runs is trusted for Kerberos delegation
TrustedForDelegation bool
// NotDelegated (0x100000) - The security context of the user will not be delegated to a service even if the service account is set as trusted for Kerberos delegation
NotDelegated bool
// UseDESKeyOnly (0x200000) - Use DES encryption types for keys for this account
UseDESKeyOnly bool
// DontRequirePreauth (0x400000) - This account does not require Kerberos pre-authentication for logon
DontRequirePreauth bool
// PasswordExpired (0x800000) - The user password has expired
PasswordExpired bool
// TrustedToAuthenticateForDelegation (0x1000000) - The account is enabled for delegation; used with the Kerberos constrained delegation feature
TrustedToAuthenticateForDelegation bool
}
UAC represents the User Account Control flags for Active Directory user and computer accounts. These flags control various security settings and account behaviors.
Reference: https://learn.microsoft.com/en-us/windows/win32/adschema/a-useraccountcontrol
func UACFromUint32 ¶
UACFromUint32 creates a UAC struct from a uint32 userAccountControl value. This function decodes the bitmask flags from Active Directory's userAccountControl attribute.
Parameters:
- v: The uint32 value from the userAccountControl attribute
Returns:
- UAC: A UAC struct with boolean flags corresponding to the bitmask
Example:
// For a typical enabled user account (0x200 = ADS_UF_NORMAL_ACCOUNT) uac := UACFromUint32(512) // uac.NormalAccount will be true, AccountDisabled will be false
func (UAC) String ¶
String returns a human-readable representation of the UAC flags. Only flags that are set to true are included in the output string.
Returns:
- string: A comma-separated list of active UAC flag names
Example output: "NormalAccount, NoPasswordExpiration" If no flags are set, returns an empty string.
func (UAC) Uint32 ¶
Uint32 converts the UAC struct back to a uint32 userAccountControl value. This function encodes the boolean flags into the bitmask format expected by Active Directory.
Returns:
- uint32: The userAccountControl bitmask value suitable for Active Directory operations
This method is useful when creating or modifying user accounts and need to set the userAccountControl attribute with the appropriate flags.
type User ¶
type User struct {
Object
// Enabled indicates whether the user account is enabled (not disabled by userAccountControl).
Enabled bool
// SAMAccountName is the Security Account Manager account name (unique identifier for Windows authentication).
SAMAccountName string
// Description contains the user's description or notes.
Description string
// Mail contains the user's email address (nil if not set).
Mail *string
// Groups contains a list of distinguished names (DNs) of groups the user belongs to.
Groups []string
}
User represents an LDAP user object with common attributes.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
authentication
command
Package main demonstrates authentication operations using simple-ldap-go
|
Package main demonstrates authentication operations using simple-ldap-go |
|
basic-usage
command
Package main demonstrates basic LDAP operations using simple-ldap-go
|
Package main demonstrates basic LDAP operations using simple-ldap-go |
|
user-management
command
Package main demonstrates user management operations using simple-ldap-go
|
Package main demonstrates user management operations using simple-ldap-go |