Files
go-authcheck/main.go
Nathan Coad 4bd71d8099
All checks were successful
continuous-integration/drone/push Build is passing
improve version string
2023-07-26 08:43:03 +10:00

269 lines
6.7 KiB
Go

package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/go-ldap/ldap/v3"
)
type Output struct {
Server string
AuthSuccess bool
Error string
CertLoaded bool
Results string
Groups string
Version string
}
// For build numbers, from https://blog.kowalczyk.info/article/vEja/embedding-build-number-in-go-executable.html
var sha1ver string // sha1 revision used to build the program
var buildTime string // when the executable was built
func GetFilePath(path string) string {
// Check for empty filename
if len(path) == 0 {
return ""
}
// check if filename exists
if _, err := os.Stat(path); os.IsNotExist((err)) {
fmt.Printf("File '%s' not found, searching in same directory as binary\n", path)
// if not, check that it exists in the same directory as the currently executing binary
ex, err2 := os.Executable()
if err2 != nil {
//log.Printf("Error determining binary path : '%s'", err)
return ""
}
binaryPath := filepath.Dir(ex)
path = filepath.Join(binaryPath, path)
}
return path
}
func isFlagPassed(name string) bool {
found := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
// GetGroupsOfUser returns the group for a user.
// Taken from https://github.com/jtblin/go-ldap-client/issues/13#issuecomment-456090979
func GetGroupsOfUser(username string, baseDN string, conn *ldap.Conn) ([]string, error) {
var samAccountName string
var groups []string
if strings.Contains(username, "@") {
s := strings.Split(username, "@")
samAccountName = s[0]
} else if strings.Contains(username, "\\") {
s := strings.Split(username, "\\")
samAccountName = s[len(s)-1]
} else {
samAccountName = username
}
// Get the users DN
// Search for the given username
searchRequest := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(CN=%s)", ldap.EscapeFilter(samAccountName)),
[]string{},
nil,
)
sr, err := conn.Search(searchRequest)
if err != nil {
return nil, err
}
if len(sr.Entries) != 1 {
return nil, fmt.Errorf("user '%s' does not exist", samAccountName)
} else {
// Get the groups of the first result
groups = sr.Entries[0].GetAttributeValues("memberOf")
/*
for _, entry := range sr.Entries {
entry.PrettyPrint(2)
}
*/
}
/*
userdn := sr.Entries[0].DN
fmt.Printf("userdn is '%s' from CN '%s'", userdn, samAccountName)
searchRequest = ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(memberUid=%s)", userdn),
[]string{}, // can it be something else than "cn"?
nil,
)
sr, err = conn.Search(searchRequest)
if err != nil {
return nil, err
}
for _, entry := range sr.Entries {
fmt.Println(entry.GetAttributeValue("cn"))
groups = append(groups, entry.GetAttributeValue("cn"))
}
*/
return groups, nil
}
// Some good ideas at https://gist.github.com/tboerger/4840e1b5464fc26fbb165b168be23345
func main() {
var output Output
// Process command line arguments
server := flag.String("server", "ldap.example.com", "LDAP server to bind to")
baseDN := flag.String("baseDN", "OU=Users,DC=example,DC=com", "Base DN to use when attempting to bind to AD")
username := flag.String("username", "user", "Username to use when attempting to bind to AD")
password := flag.String("password", "pass", "Password to use when attempting to bind to AD")
certFile := flag.String("cert-file", "rootca.pem", "Filename to load trusted certificate from")
flag.Parse()
output.Server = *server
output.Version = fmt.Sprintf("Built %s from %s", buildTime, sha1ver)
// Get a copy of the system defined CA's
system, err := x509.SystemCertPool()
if err != nil {
output.AuthSuccess = false
output.Error = "failed to access system CA list"
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
// only try to load certificate from file if the command line argument was specified
if isFlagPassed("cert-file") {
// Try to read the file
cf, err := os.ReadFile(GetFilePath(*certFile))
if err != nil {
output.AuthSuccess = false
output.Error = err.Error()
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
// Get the certificate from the file
cpb, _ := pem.Decode(cf)
crt, err := x509.ParseCertificate(cpb.Bytes)
//fmt.Printf("Loaded certificate with subject %s\n", crt.Subject)
if err != nil {
output.AuthSuccess = false
output.Error = err.Error()
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
// Add custom certificate to the system cert pool
system.AddCert(crt)
/*
ok := system.AppendCertsFromPEM(crt)
if !ok {
output.AuthSuccess = false
output.Error = "failed to parse WSDC intermediate certificate"
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
*/
output.CertLoaded = true
}
// Start trying to use ldap package
// Set up TLS to use our custom certificate authority passed in cli argument
tlsConfig := &tls.Config{
RootCAs: system,
}
// try connecting to AD via TLS and our custom certificate authority
ldaps, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:636", *server), tlsConfig)
if err != nil {
output.AuthSuccess = false
output.Error = fmt.Sprintf("Dial Error: %s", err)
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
defer ldaps.Close()
// try to bind to AD
err = ldaps.Bind(*username, *password)
if err != nil {
output.AuthSuccess = false
output.Error = fmt.Sprintf("Bind Error: %s", err)
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
searchReq := ldap.NewSearchRequest(
*baseDN,
ldap.ScopeBaseObject, // you can also use ldap.ScopeWholeSubtree
ldap.NeverDerefAliases,
0,
0,
false,
"(objectClass=*)",
[]string{},
nil,
)
result, err := ldaps.Search(searchReq)
if err != nil {
output.AuthSuccess = false
output.Error = fmt.Sprintf("Search Error: %s", err)
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
if len(result.Entries) == 0 {
output.AuthSuccess = false
output.Error = "No search results"
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
} else {
output.AuthSuccess = true
output.Results = fmt.Sprintf("Search result count: %d; %s", len(result.Entries), result.Entries[0].DN)
// Since we have a successful connection, try getting group membership
groups, err := GetGroupsOfUser(*username, *baseDN, ldaps)
if err != nil {
output.AuthSuccess = false
output.Results = fmt.Sprintf("Group search Error: %s", err)
} else {
output.Groups = strings.Join(groups[:], ";")
}
b, _ := json.Marshal(output)
fmt.Println(string(b))
return
}
}