Skip to content

Instantly share code, notes, and snippets.

@rusco
Created December 5, 2024 16:09
Show Gist options
  • Save rusco/a09862519584054b07509c356cebc2cf to your computer and use it in GitHub Desktop.
Save rusco/a09862519584054b07509c356cebc2cf to your computer and use it in GitHub Desktop.
ActiveDirectory Access in Go
package main
import (
"fmt"
"strings"
"unicode"
"github.com/go-ldap/ldap/v3"
auth "github.com/korylprince/go-ad-auth/v3"
)
func isBinary(s string) bool {
for _, r := range s {
if !unicode.IsPrint(r) && !unicode.IsSpace(r) {
return true
}
}
return false
}
func searchLDAP(name string) (*ldap.SearchResult, error) {
config := &auth.Config{
Server: "ldap.my.company.com",
Port: 389,
BaseDN: "DC=my,DC=company,DC=com",
Security: auth.SecurityStartTLS,
}
usr, pwd := "someusr", "somepass"
upn, err := config.UPN(usr)
if err != nil {
return nil, err
}
conn, err := config.Connect()
if err != nil {
return nil, err
}
defer conn.Conn.Close()
result, err2 := conn.Bind(upn, pwd)
if err2 != nil {
return nil, err2
}
_ = result //check if ok
searchRequest := ldap.NewSearchRequest(
"DC=my,DC=company,DC=com",
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0,
0,
false,
//fmt.Sprintf("(&(objectCategory=person)(objectClass=user)(displayname=%s))", name), //name is exactly match of displayname, is case insensitive
fmt.Sprintf("(&(objectCategory=person)(objectClass=user)(displayname=*%s*))", name), //name is substring of displayname, is case insensitive
[]string{}, //"samaccountname", "displayname", "mail", "telephoneNumber", "mobilenumber", "ExtensionAttribute2", "ExtensionAttribute3"},
nil,
)
sr, err := conn.Conn.Search(searchRequest)
if err != nil {
return nil, err
}
return sr, nil
}
func ADInfo() {
//Powershell equipvalent: Get-ADUser -Identity "iwantu" -Properties *
name := "iwantu"
results, err := searchLDAP(name)
if err != nil {
fmt.Println("Error:", err)
return
}
for _, entry := range results.Entries {
for _, attr := range entry.Attributes {
for _, value := range attr.Values {
if !isBinary(value) && attr.Name != "msExchSafeRecipientsHash" && attr.Name != "logonHours" {
fmt.Printf("%-40s", attr.Name)
fmt.Printf("%-80s\n", value)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment