Documentation
¶
Index ¶
- Constants
- func ConvertLDAPDurationToSeconds(value string) (int64, error)
- func ConvertLDAPTimeStampToUnixTimeStamp(value string) (int64, error)
- func ConvertSecondsToLDAPDuration(value int64) string
- func ConvertUnixTimeStampToLDAPTimeStamp(value time.Time) int64
- func GetDomainFromDistinguishedName(distinguishedName string) string
- func NewControlsWithOIDs(oids []string, criticality bool) []goldapv3.Control
- type Action
- type Control
- type ControlMicrosoftSDFlags
- type DNWithBinary
- type Entry
- type ModifyRequest
- func (req *ModifyRequest) Add(attrType string, attrVals []string)
- func (req *ModifyRequest) AddControl(control goldapv3.Control)
- 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 Session
- func (ldapSession *Session) AddStringToAttributeList(distinguishedName string, attributeName string, valueToAdd string) error
- func (s *Session) Close()
- func (s *Session) Connect() (bool, error)
- func (ldapSession *Session) DistinguishedNameExists(distinguishedName string) (bool, error)
- func (ldapSession *Session) FindObjectSIDByRID(domain string, RID int) (string, error)
- func (ldapSession *Session) FlushAttributeValues(distinguishedName string, attributeName string) error
- func (ldapSession *Session) GetAllCertificates() ([]string, error)
- func (ldapSession *Session) GetAllDomainControllers() (map[string][]string, error)
- func (ldapSession *Session) GetAllDomains() (map[string]*objects.Domain, error)
- func (ldapSession *Session) GetAllNamingContexts() ([]string, error)
- func (ldapSession *Session) GetAllReadOnlyDomainControllers() (map[string][]string, error)
- func (ldapSession *Session) GetDistinguishedNamesOfAllEnabledCertificates() ([]string, error)
- func (ldapSession *Session) GetDomain(domain string) (*objects.Domain, error)
- func (ldapSession *Session) GetDomainDNSServers() ([]string, error)
- func (ldapSession *Session) GetNamesOfAllEnabledCertificates() ([]string, error)
- func (s *Session) GetNtSecurityDescriptorOf(distinguishedName string) (string, error)
- func (ldapSession *Session) GetPrincipalDomainController(domainName string) (string, error)
- func (ldapSession *Session) GetRootDSE() (*Entry, error)
- func (ldapSession *Session) Modify(modifyRequest *ModifyRequest) error
- func (ldapSession *Session) OverwriteAttributeValue(distinguishedName string, attrName string, attrVal string) error
- func (ldapSession *Session) OverwriteAttributeValues(distinguishedName string, attrName string, attrVals []string) error
- func (ldapSession *Session) Query(searchBase string, query string, attributes []string, scope int) ([]*ldap.Entry, error)
- func (ldapSession *Session) QueryAllNamingContexts(query string, attributes []string, scope int) ([]*ldap.Entry, error)
- func (ldapSession *Session) QueryBaseObject(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
- func (ldapSession *Session) QueryChildren(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
- func (ldapSession *Session) QuerySingleLevel(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
- func (ldapSession *Session) QueryWholeSubtree(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
- func (s *Session) ReConnect() (bool, error)
Constants ¶
const ( StringFormatPrefix = "B:" StringFormatSeparator = ":" )
const ( ScopeBaseObject = goldapv3.ScopeBaseObject ScopeSingleLevel = goldapv3.ScopeSingleLevel ScopeChildren = goldapv3.ScopeChildren ScopeWholeSubtree = goldapv3.ScopeWholeSubtree )
const ( // LDAP_PAGED_RESULT_OID_STRING is the OID for the LDAP paged results control // which allows clients to control the rate at which an LDAP server returns the // results of a search operation. LDAP_PAGED_RESULT_OID_STRING = "1.2.840.113556.1.4.319" // LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID is the OID for the LDAP cross-domain move target control // which is used during cross-domain move operations. LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID = "1.2.840.113556.1.4.521" // LDAP_SERVER_DIRSYNC_OID is the OID for the LDAP directory synchronization control // which is used to maintain directory synchronization. LDAP_SERVER_DIRSYNC_OID = "1.2.840.113556.1.4.841" // LDAP_SERVER_DOMAIN_SCOPE_OID is the OID for the LDAP domain scope control // which limits the scope of an operation to a single domain. LDAP_SERVER_DOMAIN_SCOPE_OID = "1.2.840.113556.1.4.1339" // LDAP_SERVER_EXTENDED_DN_OID is the OID for the LDAP extended DN control // which requests that the LDAP server return extended DNs with additional information. LDAP_SERVER_EXTENDED_DN_OID = "1.2.840.113556.1.4.529" // LDAP_SERVER_GET_STATS_OID is the OID for the LDAP get stats control // which retrieves statistics from the LDAP server. LDAP_SERVER_GET_STATS_OID = "1.2.840.113556.1.4.970" // LDAP_SERVER_LAZY_COMMIT_OID is the OID for the LDAP lazy commit control // which allows for delayed commitment of changes to the directory. LDAP_SERVER_LAZY_COMMIT_OID = "1.2.840.113556.1.4.619" // LDAP_SERVER_PERMISSIVE_MODIFY_OID is the OID for the LDAP permissive modify control // which allows modify operations to succeed when they would otherwise fail due to // attempts to add existing attributes or delete non-existent attributes. LDAP_SERVER_PERMISSIVE_MODIFY_OID = "1.2.840.113556.1.4.1413" // LDAP_SERVER_NOTIFICATION_OID is the OID for the LDAP notification control // which enables event notification for changes to the directory. LDAP_SERVER_NOTIFICATION_OID = "1.2.840.113556.1.4.528" // LDAP_SERVER_RESP_SORT_OID is the OID for the LDAP response sort control // which is used in the server's response to a sort request control. LDAP_SERVER_RESP_SORT_OID = "1.2.840.113556.1.4.474" // LDAP_SERVER_SD_FLAGS_OID is the OID for the LDAP security descriptor flags control // which specifies which portions of a security descriptor to retrieve. LDAP_SERVER_SD_FLAGS_OID = "1.2.840.113556.1.4.801" // LDAP_SERVER_SEARCH_OPTIONS_OID is the OID for the LDAP search options control // which provides additional options for search operations. LDAP_SERVER_SEARCH_OPTIONS_OID = "1.2.840.113556.1.4.1340" // LDAP_SERVER_SORT_OID is the OID for the LDAP sort control // which requests that the LDAP server sort search results before returning them. LDAP_SERVER_SORT_OID = "1.2.840.113556.1.4.473" // LDAP_SERVER_SHOW_DELETED_OID is the OID for the LDAP show deleted control // which requests that the LDAP server return deleted objects in search results. LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417" // LDAP_SERVER_TREE_DELETE_OID is the OID for the LDAP tree delete control // which requests that the LDAP server delete an entire subtree in a single operation. LDAP_SERVER_TREE_DELETE_OID = "1.2.840.113556.1.4.805" // LDAP_SERVER_VERIFY_NAME_OID is the OID for the LDAP verify name control // which verifies the name of the target object for an operation. LDAP_SERVER_VERIFY_NAME_OID = "1.2.840.113556.1.4.1338" // LDAP_CONTROL_VLVREQUEST is the OID for the LDAP virtual list view request control // which allows clients to retrieve a subset of search results based on positional information. LDAP_CONTROL_VLVREQUEST = "2.16.840.1.113730.3.4.9" // LDAP_CONTROL_VLVRESPONSE is the OID for the LDAP virtual list view response control // which is used in the server's response to a virtual list view request control. LDAP_CONTROL_VLVRESPONSE = "2.16.840.1.113730.3.4.10" // LDAP_SERVER_ASQ_OID is the OID for the LDAP attribute scoped query control // which allows searching based on values of attributes in a specific entry. LDAP_SERVER_ASQ_OID = "1.2.840.113556.1.4.1504" // LDAP_SERVER_QUOTA_CONTROL_OID is the OID for the LDAP quota control // which is used to manage directory quotas. LDAP_SERVER_QUOTA_CONTROL_OID = "1.2.840.113556.1.4.1852" // LDAP_SERVER_RANGE_OPTION_OID is the OID for the LDAP range option control // which is used to retrieve large multi-valued attributes in chunks. LDAP_SERVER_RANGE_OPTION_OID = "1.2.840.113556.1.4.802" // LDAP_SERVER_SHUTDOWN_NOTIFY_OID is the OID for the LDAP shutdown notification control // which notifies clients of server shutdown. LDAP_SERVER_SHUTDOWN_NOTIFY_OID = "1.2.840.113556.1.4.1907" // LDAP_SERVER_FORCE_UPDATE_OID is the OID for the LDAP force update control // which forces updates to the directory even when they would normally be rejected. LDAP_SERVER_FORCE_UPDATE_OID = "1.2.840.113556.1.4.1974" // LDAP_SERVER_RANGE_RETRIEVAL_NOERR_OID is the OID for the LDAP range retrieval no error control // which suppresses errors during range retrieval operations. LDAP_SERVER_RANGE_RETRIEVAL_NOERR_OID = "1.2.840.113556.1.4.1948" // LDAP_SERVER_RODC_DCPROMO_OID is the OID for the LDAP RODC DCPromo control // which is used during the promotion of a read-only domain controller. LDAP_SERVER_RODC_DCPROMO_OID = "1.2.840.113556.1.4.1341" // LDAP_SERVER_DN_INPUT_OID is the OID for the LDAP DN input control // which specifies the format of distinguished names in the request. LDAP_SERVER_DN_INPUT_OID = "1.2.840.113556.1.4.2026" // LDAP_SERVER_SHOW_DEACTIVATED_LINK_OID is the OID for the LDAP show deactivated link control // which requests that the LDAP server return deactivated links in search results. LDAP_SERVER_SHOW_DEACTIVATED_LINK_OID = "1.2.840.113556.1.4.2065" // LDAP_SERVER_SHOW_RECYCLED_OID is the OID for the LDAP show recycled control // which requests that the LDAP server return recycled objects in search results. LDAP_SERVER_SHOW_RECYCLED_OID = "1.2.840.113556.1.4.2064" // LDAP_SERVER_POLICY_HINTS_DEPRECATED_OID is the OID for the deprecated LDAP policy hints control // which provided hints about policy enforcement to the LDAP server. LDAP_SERVER_POLICY_HINTS_DEPRECATED_OID = "1.2.840.113556.1.4.2066" // LDAP_SERVER_DIRSYNC_EX_OID is the OID for the LDAP extended directory synchronization control // which provides enhanced directory synchronization capabilities. LDAP_SERVER_DIRSYNC_EX_OID = "1.2.840.113556.1.4.2090" // LDAP_SERVER_UPDATE_STATS_OID is the OID for the LDAP update stats control // which updates statistics on the LDAP server. LDAP_SERVER_UPDATE_STATS_OID = "1.2.840.113556.1.4.2205" // LDAP_SERVER_TREE_DELETE_EX_OID is the OID for the LDAP extended tree delete control // which provides enhanced capabilities for deleting entire subtrees. LDAP_SERVER_TREE_DELETE_EX_OID = "1.2.840.113556.1.4.2204" // LDAP_SERVER_SEARCH_HINTS_OID is the OID for the LDAP search hints control // which provides hints to optimize search operations. LDAP_SERVER_SEARCH_HINTS_OID = "1.2.840.113556.1.4.2206" // LDAP_SERVER_EXPECTED_ENTRY_COUNT_OID is the OID for the LDAP expected entry count control // which specifies the expected number of entries in a search result. LDAP_SERVER_EXPECTED_ENTRY_COUNT_OID = "1.2.840.113556.1.4.2211" // LDAP_SERVER_POLICY_HINTS_OID is the OID for the LDAP policy hints control // which provides hints about policy enforcement to the LDAP server. LDAP_SERVER_POLICY_HINTS_OID = "1.2.840.113556.1.4.2239" // LDAP_SERVER_SET_OWNER_OID is the OID for the LDAP set owner control // which sets the owner of an object during creation or modification. LDAP_SERVER_SET_OWNER_OID = "1.2.840.113556.1.4.2255" // LDAP_SERVER_BYPASS_QUOTA_OID is the OID for the LDAP bypass quota control // which allows operations to bypass quota restrictions. LDAP_SERVER_BYPASS_QUOTA_OID = "1.2.840.113556.1.4.2256" // LDAP_SERVER_LINK_TTL_OID is the OID for the LDAP link TTL control // which specifies the time-to-live for linked attributes. LDAP_SERVER_LINK_TTL_OID = "1.2.840.113556.1.4.2309" // LDAP_SERVER_SET_CORRELATION_ID_OID is the OID for the LDAP set correlation ID control // which sets a correlation ID for tracking operations across multiple requests. LDAP_SERVER_SET_CORRELATION_ID_OID = "1.2.840.113556.1.4.2330" // LDAP_SERVER_THREAD_TRACE_OVERRIDE_OID is the OID for the LDAP thread trace override control // which overrides thread tracing settings for diagnostic purposes. LDAP_SERVER_THREAD_TRACE_OVERRIDE_OID = "1.2.840.113556.1.4.2354" )
OID constants for LDAP controls Source: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/3c5e87db-4728-4f29-b164-01dd7d7391ea
const UnixTimestampStart int64 = 116444736000000000
Monday, January 1, 1601 12:00:00 AM in 100-nanosecond intervals
Variables ¶
This section is empty.
Functions ¶
func ConvertLDAPDurationToSeconds ¶
ConvertLDAPDurationToSeconds converts an LDAP duration to seconds. LDAP durations are represented as the number of 100-nanosecond intervals.
Parameters:
value (string): The LDAP duration to be converted.
Returns:
int64: The converted duration in seconds. error: An error object if the conversion fails, otherwise nil.
Example:
ldapDuration := "864000000000"
seconds, err := ConvertLDAPDurationToSeconds(ldapDuration)
if err != nil {
logger.Warn(fmt.Sprintf("Error converting LDAP duration to seconds: %s", err))
return
}
// seconds will be 86400 (corresponding to 1 day)
Note:
If the LDAP duration is invalid or cannot be converted, the function returns 0 and an error.
func ConvertLDAPTimeStampToUnixTimeStamp ¶
ConvertLDAPTimeStampToUnixTimeStamp converts an LDAP timestamp to a Unix timestamp. LDAP timestamps are represented as the number of 100-nanosecond intervals since January 1, 1601 (UTC). Unix timestamps are represented as the number of seconds since January 1, 1970 (UTC).
Parameters:
value (string): The LDAP timestamp to be converted.
Returns:
int64: The converted Unix timestamp. error: An error object if the conversion fails, otherwise nil.
Example:
ldapTimestamp := "132537600000000000"
unixTimestamp, err := ConvertLDAPTimeStampToUnixTimeStamp(ldapTimestamp)
if err != nil {
logger.Warn(fmt.Sprintf("Error converting LDAP timestamp to Unix timestamp: %s", err))
return
}
// unixTimestamp will be 1640995200 (corresponding to January 1, 2022)
Note:
If the LDAP timestamp is invalid or cannot be converted, the function returns 0 and an error.
func ConvertSecondsToLDAPDuration ¶
ConvertSecondsToLDAPDuration converts a duration in seconds to an LDAP duration. LDAP durations are represented as the number of 100-nanosecond intervals.
Parameters:
value (int64): The duration in seconds to be converted.
Returns:
string: The converted duration as an LDAP duration string.
Example:
seconds := int64(86400) // 1 day
ldapDuration := ConvertSecondsToLDAPDuration(seconds)
if err != nil {
logger.Warn(fmt.Sprintf("Error converting seconds to LDAP duration: %s", err))
return
}
// ldapDuration will be "864000000000" (corresponding to 1 day)
Note:
If the input value is negative, the function will still convert it to an LDAP duration.
func ConvertUnixTimeStampToLDAPTimeStamp ¶
ConvertUnixTimeStampToLDAPTimeStamp converts a Unix timestamp to an LDAP timestamp. LDAP timestamps are represented as the number of 100-nanosecond intervals since January 1, 1601 (UTC).
Parameters:
value (time.Time): The Unix timestamp to be converted.
Returns:
int64: The converted timestamp as an LDAP timestamp.
Example:
unixTime := time.Now() ldapTime := ConvertUnixTimeStampToLDAPTimeStamp(unixTime) // ldapTime will be the corresponding LDAP timestamp for the current time.
Note:
The function multiplies the Unix timestamp by 10,000,000 to convert seconds to 100-nanosecond intervals and then adds the number of 100-nanosecond intervals between January 1, 1601, and January 1, 1970.
func GetDomainFromDistinguishedName ¶
GetDomainFromDistinguishedName extracts the domain name from a distinguished name (DN). A distinguished name is a string that uniquely identifies an entry in the LDAP directory. The function splits the DN into its components and concatenates the domain components (DC) to form the domain name.
Parameters:
distinguishedName (string): The distinguished name from which to extract the domain name.
Returns:
string: The extracted domain name.
Example:
distinguishedName := "CN=John Doe,OU=Users,DC=example,DC=com" domain := GetDomainFromDistinguishedName(distinguishedName) // domain will be "example.com"
Note:
The function assumes that the distinguished name is well-formed and contains domain components (DC).
func NewControlsWithOIDs ¶ added in v1.0.1
NewControlsWithOIDs creates multiple controls with the specified OIDs. This function returns a slice of structs that implement the goldapv3.Control interface.
Parameters:
- oids: A slice of strings representing the Object Identifiers for the controls.
- criticality: A boolean indicating whether the controls are critical.
Returns:
- A slice of goldapv3.Control that can be used with LDAP operations.
Example usage:
controls := NewControlsWithOIDs([]string{LDAP_SERVER_PERMISSIVE_MODIFY_OID}, false)
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
for _, control := range controls {
modifyRequest.AddControl(control)
}
Types ¶
type ControlMicrosoftSDFlags ¶ added in v1.0.3
func NewControlMicrosoftSDFlags ¶ added in v1.0.3
func NewControlMicrosoftSDFlags() *ControlMicrosoftSDFlags
NewControlMicrosoftSDFlags returns a ControlMicrosoftSDFlags control
func (*ControlMicrosoftSDFlags) Encode ¶ added in v1.0.3
func (c *ControlMicrosoftSDFlags) Encode() *ber.Packet
func (*ControlMicrosoftSDFlags) GetControlType ¶ added in v1.0.3
func (c *ControlMicrosoftSDFlags) GetControlType() string
func (*ControlMicrosoftSDFlags) String ¶ added in v1.0.3
func (c *ControlMicrosoftSDFlags) String() string
type DNWithBinary ¶ added in v1.0.3
func (*DNWithBinary) Describe ¶ added in v1.0.3
func (d *DNWithBinary) Describe(indent int)
Describe prints a detailed description of the DNWithBinary structure.
Parameters: - indent: An integer value specifying the indentation level for the output.
func (*DNWithBinary) Marshal ¶ added in v1.0.5
func (d *DNWithBinary) Marshal() ([]byte, error)
func (*DNWithBinary) String ¶ added in v1.0.3
func (d *DNWithBinary) String() string
type ModifyRequest ¶
type ModifyRequest struct {
// Distinguished names
DistinguishedName string
// Actions to perform on attributes
Attributes []*Action
// LDAP controls
Controls []goldapv3.Control
}
func NewModifyRequest ¶
func NewModifyRequest(distinguishedName string) *ModifyRequest
NewModifyRequest creates a new instance of ModifyRequest with the specified distinguished name.
Parameters:
- distinguishedName: A string representing the distinguished name (DN) of the LDAP entry to be modified.
Returns:
- A pointer to a newly created ModifyRequest instance with the specified distinguished name and an empty list of attributes.
The function initializes the ModifyRequest struct with the provided distinguished name and an empty slice of attributes. This struct can then be used to add, delete, increment, or replace attributes for the specified LDAP entry.
Example usage:
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
modifyRequest.Add("description", []string{"New description"})
modifyRequest.Delete("telephoneNumber", []string{"123-456-7890"})
modifyRequest.Replace("mail", []string{"john.doe@example.com"})
err := ldapSession.Modify("cn=John Doe,dc=example,dc=com", modifyRequest)
if err != nil {
log.Fatalf("Failed to modify LDAP entry: %s", err)
}
func (*ModifyRequest) Add ¶
func (req *ModifyRequest) Add(attrType string, attrVals []string)
Add adds a new attribute and its values to the ModifyRequest.
Parameters:
- attrType: A string representing the type of the attribute to be added.
- attrVals: A slice of strings representing the values of the attribute to be added.
The function appends a new Attribute struct to the Attributes slice of the ModifyRequest. The Attribute struct contains the provided attribute type and values. This function can be used to add new attributes to an LDAP entry as part of a modify operation.
Example usage:
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
modifyRequest.Add("description", []string{"New description"})
modifyRequest.Add("telephoneNumber", []string{"123-456-7890"})
In this example, the modifyRequest will contain two attributes to be added to the LDAP entry with the distinguished name "cn=John Doe,dc=example,dc=com". The first attribute is "description" with the value "New description", and the second attribute is "telephoneNumber" with the value "123-456-7890".
func (*ModifyRequest) AddControl ¶ added in v1.0.1
func (req *ModifyRequest) AddControl(control goldapv3.Control)
AddControl adds a control to the ModifyRequest.
Parameters:
- control: A goldapv3.Control interface representing the control to be added.
func (*ModifyRequest) Delete ¶
func (req *ModifyRequest) Delete(attrType string, attrVals []string)
Delete removes an attribute and its values from the ModifyRequest.
Parameters:
- attrType: A string representing the type of the attribute to be removed.
- attrVals: A slice of strings representing the values of the attribute to be removed.
The function appends a new Attribute struct to the Attributes slice of the ModifyRequest. The Attribute struct contains the provided attribute type and values. This function can be used to remove attributes from an LDAP entry as part of a modify operation.
Example usage:
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
modifyRequest.Delete("description", []string{"Old description"})
modifyRequest.Delete("telephoneNumber", []string{"123-456-7890"})
In this example, the modifyRequest will contain two attributes to be removed from the LDAP entry with the distinguished name "cn=John Doe,dc=example,dc=com". The first attribute is "description" with the value "Old description", and the second attribute is "telephoneNumber" with the value "123-456-7890".
Note:
- If the specified attribute and values do not exist in the LDAP entry, the delete operation will have no effect.
func (*ModifyRequest) Increment ¶
func (req *ModifyRequest) Increment(attrType string, attrVal string)
Increment adds an increment operation for an attribute to the ModifyRequest.
Parameters:
- attrType: A string representing the type of the attribute to be incremented.
- attrVal: A string representing the value to increment the attribute by.
The function appends a new Attribute struct to the Attributes slice of the ModifyRequest. The Attribute struct contains the provided attribute type and the increment value. This function can be used to increment the value of an attribute in an LDAP entry as part of a modify operation.
Example usage:
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
modifyRequest.Increment("loginCount", "1")
In this example, the modifyRequest will contain an increment operation for the "loginCount" attribute with the increment value "1". This means that the "loginCount" attribute of the LDAP entry with the distinguished name "cn=John Doe,dc=example,dc=com" will be incremented by 1.
Note:
- The attribute type must support increment operations for this function to have an effect.
- The increment value should be a valid string representation of the increment amount.
func (*ModifyRequest) Replace ¶
func (req *ModifyRequest) Replace(attrType string, attrVals []string)
Replace sets a replace operation for an attribute in the ModifyRequest.
Parameters:
- attrType: A string representing the type of the attribute to be replaced.
- attrVals: A slice of strings representing the new values for the attribute.
The function appends a new Attribute struct to the Attributes slice of the ModifyRequest. The Attribute struct contains the provided attribute type and the new values. This function can be used to replace the values of an attribute in an LDAP entry as part of a modify operation.
Example usage:
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
modifyRequest.Replace("description", []string{"New description"})
In this example, the modifyRequest will contain a replace operation for the "description" attribute with the new value "New description". This means that the "description" attribute of the LDAP entry with the distinguished name "cn=John Doe,dc=example,dc=com" will be replaced with the new value.
Note:
- If the specified attribute does not exist in the LDAP entry, the replace operation will add the attribute with the provided values.
- The replace operation will remove any existing values for the specified attribute and set the new values.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents an LDAP session with configuration and connection details.
Fields:
host (string): The hostname or IP address of the LDAP server. port (int): The port number to connect to on the LDAP server. connection (*ldap.Conn): The LDAP connection object. domain (string): The domain name for the LDAP server. username (string): The username for authentication. password (string): The password for authentication. debug (bool): A flag indicating whether to enable debug mode. useldaps (bool): A flag indicating whether to use LDAPS (LDAP over SSL). usekerberos (bool): A flag indicating whether to use Kerberos for authentication.
Example:
session := &Session{}
err := session.InitSession("ldap.example.com", 389, false, true, "EXAMPLE", "user", "password", false)
if err != nil {
log.Fatalf("Failed to initialize session: %s", err)
}
success := session.Connect()
if !success {
log.Fatalf("Failed to connect to LDAP server")
}
func NewSession ¶ added in v1.0.5
func NewSession(host string, port int, credentials *credentials.Credentials, useldaps bool, usekerberos bool) (*Session, error)
NewSession creates a new LDAP session with the provided configuration and credentials.
Parameters:
host (string): The hostname or IP address of the LDAP server. port (int): The port number to connect to on the LDAP server. Must be in the range 1-65535. credentials (*credentials.Credentials): The credentials to use for authentication. useldaps (bool): A flag indicating whether to use LDAPS (LDAP over SSL). usekerberos (bool): A flag indicating whether to use Kerberos for authentication.
Returns:
*Session: A new LDAP session object. error: An error object if the creation fails, otherwise nil.
Example:
session, err := NewSession("ldap.example.com", 389, credentials, false, false)
if err != nil {
logger.Warn(fmt.Sprintf("Error creating LDAP session: %s", err))
return
}
func (*Session) AddStringToAttributeList ¶
func (ldapSession *Session) AddStringToAttributeList(distinguishedName string, attributeName string, valueToAdd string) error
AddStringToAttributeList adds a string to an attribute list
Parameters:
- dn: A string representing the distinguished name (DN) of the LDAP entry to be modified.
- attributeName: A string representing the name of the attribute to be modified.
- valueToAdd: A string representing the value to be added to the attribute.
Returns:
- An error object if the add operation fails, otherwise nil.
func (*Session) Close ¶
func (s *Session) Close()
Close terminates the LDAP session by closing the current connection.
Example:
session := &Session{}
session.Close()
Note:
This function assumes that the Session struct has a valid connection object.
func (*Session) Connect ¶
Connect establishes a connection to the LDAP server. It supports both regular LDAP and LDAPS connections, and can optionally use Kerberos for authentication.
Returns:
bool: True if the connection is successful, false otherwise.
Example:
session, err := NewSession("ldap.example.com", 389, credentials, false, false)
if err != nil {
logger.Warn(fmt.Sprintf("Error creating LDAP session: %s", err))
return
}
success := session.Connect()
if success {
logger.Info(fmt.Sprintf("Successfully connected to LDAP server: %s", s.host))
} else {
logger.Warn(fmt.Sprintf("Error connecting to LDAP server: %s", err))
}
func (*Session) DistinguishedNameExists ¶ added in v1.0.2
DistinguishedNameExists checks if a given base distinguished name (baseDN) exists in the LDAP directory.
This function performs an LDAP search with a base scope to determine if the specified baseDN exists. It constructs an LDAP search request with the provided baseDN and a search filter of "(objectClass=*)", and attempts to retrieve the "distinguishedName" attribute. If the search returns an error indicating that the baseDN does not exist (LDAPResultNoSuchObject), the function returns false. Otherwise, it returns true.
Parameters:
- baseDN (string): The base distinguished name to check for existence in the LDAP directory.
Returns:
- bool: True if the baseDN exists, false if it does not exist or if an error occurs.
- error: An error if the search fails.
Example usage:
ldapSession := &Session{}
exists, err := ldapSession.DistinguishedNameExists("DC=example,DC=com")
if err != nil {
fmt.Println("Error checking if baseDN exists:", err)
return
}
if exists {
fmt.Println("The baseDN exists in the LDAP directory.")
} else {
fmt.Println("The baseDN does not exist in the LDAP directory.")
}
Note:
- This function assumes that the Session struct has a valid connection object and that the ldap package is correctly imported and used.
func (*Session) FindObjectSIDByRID ¶
FindObjectSIDByRID searches for an LDAP object based on the provided domain and RID (Relative Identifier).
Parameters:
- domain: A string representing the domain name where the search should be performed.
- RID: An integer representing the Relative Identifier of the object to be found.
Returns:
- A string representing the SID (Security Identifier) of the found object. If no object is found, an empty string is returned.
The function first retrieves the domain object using the provided domain name. It then constructs an LDAP query to search for the object with the specified RID. The query is created differently for local RIDs and domain RIDs. If the RID matches a local RID, the query is constructed using the local RID format. Otherwise, the query is constructed using the domain SID and the provided RID.
The function performs an LDAP search using the constructed query and retrieves the distinguished name and object SID of the found object. If more than one result is found, a warning is logged. If exactly one result is found, the function parses the object SID from the raw attribute value and returns it.
Example usage:
ldapSession := &Session{}
objectSID := ldapSession.FindObjectSIDByRID("example.com", 500)
fmt.Println("Found object SID:", objectSID)
func (*Session) FlushAttributeValues ¶ added in v1.0.2
func (ldapSession *Session) FlushAttributeValues(distinguishedName string, attributeName string) error
FlushAttributeValues flushes the attribute by deleting it
Parameters:
- dn: A string representing the distinguished name (DN) of the LDAP entry to be modified.
- attributeName: A string representing the name of the attribute to be flushed.
Returns:
- An error object if the flush operation fails, otherwise nil.
func (*Session) GetAllCertificates ¶
GetAllCertificates retrieves the distinguished names of all certificate templates from the LDAP server. It searches for objects of category 'pKICertificateTemplate' and extracts the 'distinguishedName' attribute values from them.
Returns: - A slice of strings containing the distinguished names of all certificate templates.
func (*Session) GetAllDomainControllers ¶
GetAllDomainControllers retrieves a map of all domain controllers in the LDAP directory. It constructs an LDAP query to search for computer objects that represent domain controllers by using the userAccountControl attribute to filter for server trust accounts.
Parameters: - ldapSession: A pointer to the LDAP session.
Returns:
- A map where the keys are the distinguished names of the domain controllers and the values are slices of strings containing the DNS hostnames of the domain controllers.
func (*Session) GetAllDomains ¶
GetAllDomains retrieves all domain objects from the LDAP directory.
This function performs an LDAP search to find all objects with the objectClass "domain" within the domain's distinguished name. It retrieves the distinguished name and objectSid attributes for each domain object and constructs a map of Domain objects.
Returns:
- A map where the keys are the distinguished names of the domain objects and the values are pointers to Domain objects representing the retrieved domain objects.
func (*Session) GetAllNamingContexts ¶
GetAllNamingContexts retrieves all naming contexts from the LDAP server.
This function fetches the RootDSE entry from the LDAP server and retrieves the "namingContexts" attribute, which contains a list of all naming contexts available in the LDAP directory.
Returns:
- A slice of strings containing the naming contexts if found, otherwise nil.
Example usage:
ldapSession := &Session{}
namingContexts := ldapSession.GetAllNamingContexts()
if namingContexts != nil {
for _, context := range namingContexts {
fmt.Printf("Naming Context: %s\n", context)
}
} else {
fmt.Println("No naming contexts found.")
}
Note:
- This function assumes that the Session struct has a valid connection object and that the GetRootDSE method is implemented correctly.
func (*Session) GetAllReadOnlyDomainControllers ¶
GetAllReadOnlyDomainControllers retrieves a map of all read-only domain controllers (RODCs) in the LDAP directory. It constructs an LDAP query to search for computer objects that represent read-only domain controllers by using the userAccountControl attribute to filter for partial secrets accounts.
Parameters: - ldapSession: A pointer to the LDAP session.
Returns:
- A map where the keys are the distinguished names of the read-only domain controllers and the values are slices of strings containing the DNS hostnames of the read-only domain controllers.
func (*Session) GetDistinguishedNamesOfAllEnabledCertificates ¶
GetDistinguishedNamesOfAllEnabledCertificates retrieves the distinguished names of all enabled certificate templates from the LDAP server. It first fetches the names of all enabled certificate templates using the GetNamesOfAllEnabledCertificates function, and then queries the LDAP server for each certificate template name to get their distinguished names.
Returns: - A slice of strings containing the distinguished names of all enabled certificate templates.
func (*Session) GetDomain ¶
GetDomain retrieves the domain object from the LDAP server.
This function searches for the domain object in the LDAP server and returns the domain object.
Parameters:
- domain (string): The domain to search for.
Returns:
- *objects.Domain: The domain object if found, otherwise nil.
func (*Session) GetDomainDNSServers ¶
GetDomainDNSServers retrieves the IP addresses of DNS servers from both read-only domain controllers and domain controllers in the LDAP session. It attempts to establish a TCP connection to port 53 (DNS service) on each hostname found in the domain controllers. If the connection is successful, it extracts the IP address of the DNS server and adds it to the list of DNS servers.
Returns: - A slice of strings containing the IP addresses of the DNS servers. - An error if any issues occur during the retrieval process.
func (*Session) GetNamesOfAllEnabledCertificates ¶
GetNamesOfAllEnabledCertificates retrieves the names of all enabled certificate templates from the LDAP server. It searches for objects of category 'pKIEnrollmentService' and extracts the 'certificateTemplates' attribute values from them.
Returns: - A slice of strings containing the names of all enabled certificate templates.
func (*Session) GetNtSecurityDescriptorOf ¶ added in v1.0.3
GetNtSecurityDescriptorOf retrieves the NT Security Descriptor of an LDAP entry.
Parameters:
- dn: A string representing the distinguished name (DN) of the LDAP entry to retrieve the NT Security Descriptor from.
Returns:
- A string representing the NT Security Descriptor of the LDAP entry.
- An error if the search operation fails.
func (*Session) GetPrincipalDomainController ¶
GetPrincipalDomainController retrieves the DNS hostname of the principal domain controller (PDC) for a given domain. It constructs an LDAP query to search for the computer object that represents the PDC by using the primaryGroupID attribute and the specified domain name.
Parameters: - domainName: A string representing the name of the domain for which the PDC is to be found.
Returns: - A string containing the DNS hostname of the principal domain controller. If no PDC is found, an empty string is returned.
func (*Session) GetRootDSE ¶
GetRootDSE retrieves the Root DSE (Directory Service Entry) from the LDAP server. The Root DSE provides information about the LDAP server, including its capabilities, naming contexts, and supported controls.
This function performs a base object search with a filter of "(objectClass=*)" to retrieve all attributes of the Root DSE.
Returns: - A pointer to an ldap.Entry object representing the Root DSE. - If an error occurs during the search, the function logs a warning and returns nil.
Example usage:
rootDSE := ldapSession.GetRootDSE()
if rootDSE != nil {
fmt.Println("Root DSE retrieved successfully")
} else {
fmt.Println("Failed to retrieve Root DSE")
}
func (*Session) Modify ¶
func (ldapSession *Session) Modify(modifyRequest *ModifyRequest) error
Modify performs an LDAP modify operation on the specified distinguished name (DN) using the provided ModifyRequest.
Parameters:
- distinguishedName: A string representing the distinguished name (DN) of the LDAP entry to be modified.
- modifyRequest: A pointer to a ModifyRequest struct containing the modifications to be applied.
Returns:
- An error object if the modify operation fails, otherwise nil.
The function creates a new LDAP modify request using the provided distinguished name and the attributes from the ModifyRequest. It then performs the modify operation using the established LDAP connection in the Session struct.
Example usage:
session := &Session{}
err := session.InitSession("ldap.example.com", 389, false, true, "EXAMPLE", "user", "password", false)
if err != nil {
logger.Error(fmt.Sprintf("Failed to initialize session: %s", err))
return
}
success, err := session.Connect()
if !success {
logger.Warn(fmt.Sprintf("Failed to connect to LDAP server: %s", err))
return
}
modifyRequest := NewModifyRequest("cn=John Doe,dc=example,dc=com")
modifyRequest.Replace("description", []string{"New description"})
err = session.Modify("cn=John Doe,dc=example,dc=com", modifyRequest)
if err != nil {
logger.Error(fmt.Sprintf("Failed to modify LDAP entry: %s", err))
} else {
logger.Info("Successfully modified LDAP entry")
}
Note:
- The ModifyRequest struct should contain the desired modifications, such as add, delete, or replace operations for specific attributes.
- Ensure that the LDAP connection is properly established before calling this function.
func (*Session) OverwriteAttributeValue ¶ added in v1.0.1
func (ldapSession *Session) OverwriteAttributeValue(distinguishedName string, attrName string, attrVal string) error
OverwriteAttributeValue sets an overwrite operation for an attribute in the ModifyRequest.
Parameters:
- distinguishedName: A string representing the distinguished name (DN) of the LDAP entry to be modified.
- attrName: A string representing the name of the attribute to be overwritten.
- attrVal: A string representing the new value for the attribute.
func (*Session) OverwriteAttributeValues ¶ added in v1.0.1
func (ldapSession *Session) OverwriteAttributeValues(distinguishedName string, attrName string, attrVals []string) error
OverwriteAttributeValues sets an overwrite operation for an attribute in the ModifyRequest.
Parameters:
- distinguishedName: A string representing the distinguished name (DN) of the LDAP entry to be modified.
- attrName: A string representing the name of the attribute to be overwritten.
- attrVals: A slice of strings representing the new values for the attribute.
func (*Session) Query ¶
func (ldapSession *Session) Query(searchBase string, query string, attributes []string, scope int) ([]*ldap.Entry, error)
Query performs an LDAP search operation based on the provided parameters.
Parameters:
- searchBase: A string representing the base DN (Distinguished Name) from which the search should start. Special values "defaultNamingContext", "configurationNamingContext", and "schemaNamingContext" will be replaced with the corresponding values from the root DSE.
- query: A string representing the LDAP search filter.
- attributes: A slice of strings specifying the attributes to retrieve from the search results.
- scope: An integer representing the scope of the search. Valid values are:
- ScopeBaseObject: Search only the base object.
- ScopeSingleLevel: Search one level under the base object.
- ScopeWholeSubtree: Search the entire subtree under the base object.
Returns: - A slice of pointers to ldap.Entry objects representing the search results.
The function first determines the appropriate search base by checking if the provided searchBase matches any of the special values. If it does, it retrieves the corresponding value from the root DSE. It then constructs an LDAP search request with the specified parameters and performs the search. If the search is successful, it returns the search results. If an error occurs, it logs a warning and returns an empty slice.
func (*Session) QueryAllNamingContexts ¶
func (ldapSession *Session) QueryAllNamingContexts(query string, attributes []string, scope int) ([]*ldap.Entry, error)
QueryAllNamingContexts performs an LDAP query across all naming contexts.
This function retrieves the RootDSE entry to obtain the naming contexts and then performs the specified query on each naming context. The results from all naming contexts are combined and returned as a single slice of entries.
Parameters:
- query (string): The LDAP query to be executed.
- attributes ([]string): The list of attributes to retrieve for each entry.
- scope (int): The scope of the query (e.g., ldap.ScopeBaseObject, ldap.ScopeSingleLevel, ldap.ScopeWholeSubtree).
Returns:
- []*ldap.Entry: A slice of LDAP entries that match the query across all naming contexts. If no entries are found or if an error occurs, the function returns nil.
Example:
ldapSession := &Session{}
query := "(objectClass=person)"
attributes := []string{"cn", "sn", "mail"}
scope := ldap.ScopeWholeSubtree
entries := ldapSession.QueryAllNamingContexts(query, attributes, scope)
for _, entry := range entries {
fmt.Println(entry.GetAttributeValue("cn"))
}
Note:
- This function assumes that the Session struct has a valid connection object and that the GetRootDSE and Query methods are implemented correctly.
- The function logs warnings if the RootDSE entry cannot be retrieved or if no naming contexts are found.
func (*Session) QueryBaseObject ¶
func (ldapSession *Session) QueryBaseObject(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
QueryBaseObject performs an LDAP query with a scope of Base Object.
This function executes the specified query on the given search base with a scope of Base Object, meaning it searches only the base object itself.
Parameters:
- searchBase (string): The base DN (Distinguished Name) from which the search should start.
- query (string): The LDAP query to be executed.
- attributes ([]string): The list of attributes to retrieve for each entry.
Returns:
- []*ldap.Entry: A slice of LDAP entries that match the query within the base object. If no entries are found or if an error occurs, the function returns nil.
Example:
ldapSession := &Session{}
searchBase := "cn=admin,dc=example,dc=com"
query := "(objectClass=*)"
attributes := []string{"cn", "sn", "mail"}
entries := ldapSession.QueryBaseObject(searchBase, query, attributes)
for _, entry := range entries {
fmt.Println(entry.GetAttributeValue("cn"))
}
Note:
- This function assumes that the Session struct has a valid connection object and that the Query method is implemented correctly.
- The function logs warnings if the search fails or if no entries are found.
func (*Session) QueryChildren ¶
func (ldapSession *Session) QueryChildren(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
QueryChildren performs an LDAP query with a scope of Children.
This function executes the specified query on the given search base with a scope of Children, meaning it searches only the immediate children of the base object.
Parameters:
- searchBase (string): The base DN (Distinguished Name) from which the search should start.
- query (string): The LDAP query to be executed.
- attributes ([]string): The list of attributes to retrieve for each entry.
Returns:
- []*ldap.Entry: A slice of LDAP entries that match the query within the immediate children. If no entries are found or if an error occurs, the function returns nil.
Example:
ldapSession := &Session{}
searchBase := "ou=users,dc=example,dc=com"
query := "(objectClass=person)"
attributes := []string{"cn", "sn", "mail"}
entries := ldapSession.QueryChildren(searchBase, query, attributes)
for _, entry := range entries {
fmt.Println(entry.GetAttributeValue("cn"))
}
Note:
- This function assumes that the Session struct has a valid connection object and that the Query method is implemented correctly.
- The function logs warnings if the search fails or if no entries are found.
func (*Session) QuerySingleLevel ¶
func (ldapSession *Session) QuerySingleLevel(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
QuerySingleLevel performs an LDAP query with a scope of Single Level.
This function executes the specified query on the given search base with a scope of Single Level, meaning it searches only the immediate children of the base object, but not the base object itself.
Parameters:
- searchBase (string): The base DN (Distinguished Name) from which the search should start.
- query (string): The LDAP query to be executed.
- attributes ([]string): The list of attributes to retrieve for each entry.
Returns:
- []*ldap.Entry: A slice of LDAP entries that match the query within the single level. If no entries are found or if an error occurs, the function returns nil.
Example:
ldapSession := &Session{}
searchBase := "ou=users,dc=example,dc=com"
query := "(objectClass=person)"
attributes := []string{"cn", "sn", "mail"}
entries := ldapSession.QuerySingleLevel(searchBase, query, attributes)
for _, entry := range entries {
fmt.Println(entry.GetAttributeValue("cn"))
}
Note:
- This function assumes that the Session struct has a valid connection object and that the Query method is implemented correctly.
- The function logs warnings if the search fails or if no entries are found.
func (*Session) QueryWholeSubtree ¶
func (ldapSession *Session) QueryWholeSubtree(searchBase string, query string, attributes []string) ([]*ldap.Entry, error)
QueryWholeSubtree performs an LDAP query with a scope of Whole Subtree.
This function executes the specified query on the given search base with a scope of Whole Subtree, meaning it searches the entire subtree, including the base object and all its descendants.
Parameters:
- searchBase (string): The base DN (Distinguished Name) from which the search should start.
- query (string): The LDAP query to be executed.
- attributes ([]string): The list of attributes to retrieve for each entry.
Returns:
- []*ldap.Entry: A slice of LDAP entries that match the query within the whole subtree. If no entries are found or if an error occurs, the function returns nil.
Example:
ldapSession := &Session{}
searchBase := "dc=example,dc=com"
query := "(objectClass=person)"
attributes := []string{"cn", "sn", "mail"}
entries := ldapSession.QueryWholeSubtree(searchBase, query, attributes)
for _, entry := range entries {
fmt.Println(entry.GetAttributeValue("cn"))
}
Note:
- This function assumes that the Session struct has a valid connection object and that the Query method is implemented correctly.
- The function logs warnings if the search fails or if no entries are found.
func (*Session) ReConnect ¶
ReConnect attempts to re-establish the LDAP connection by closing the current connection and calling the Connect method again.
Returns:
bool: True if the reconnection is successful, false otherwise.
Example:
session := &Session{}
success := session.ReConnect()
if success {
fmt.Println("Reconnected successfully")
} else {
fmt.Println("Failed to reconnect")
}
Note:
This function assumes that the Session struct has a valid connection object and that the Connect method is implemented correctly.