auth

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2024 License: MIT Imports: 10 Imported by: 0

README

pkg.go.dev

About

go-ad-auth is a simple wrapper around the great ldap library to help with Active Directory authentication.

Installing

Using Go Modules:

go get github.com/korylprince/go-ad-auth/v3

Using gopkg.in:

go get gopkg.in/korylprince/go-ad-auth.v3

Dependencies:

If you have any issues or questions create an issue.

API Versions

You should update to the v3 API when possible. The new API is cleaner, more idiomatic, exposes a lot more functionality, and is fully testable.

v3 was created to support Go Modules, so it is backwards compatible with v2. However, updates made to v3 are not backported to v2.

The v3 API is almost a complete rewrite of the older gopkg.in/korylprince/go-ad-auth.v1 API. There are similarities, but v3 is not backwards-compatible.

One notable difference to be careful of is that while v1's Login will return false if the user is not in the specified group, v3's AuthenticateExtended will return true if the user authenticated successfully, regardless if they were in any of the specified groups or not.

Usage

Example:

config := &auth.Config{
    Server:   "ldap.example.com",
    Port:     389,
    BaseDN:   "OU=Users,DC=example,DC=com",
    Security: auth.SecurityStartTLS,
}

username := "user"
password := "pass"

status, err := auth.Authenticate(config, username, password)

if err != nil {
    //handle err
    return
}

if !status {
    //handle failed authentication
    return
}

See more advanced examples on go.dev.

Testing

go test -v

Most tests will be skipped unless you supply the following environment variables to connect to an Active Directory server:

Name Description
ADTEST_SERVER Hostname or IP Address of an Active Directory server
ADTEST_PORT Port to use - defaults to 389
ADTEST_BIND_UPN userPrincipalName (user@domain.tld) of admin user
ADTEST_BIND_PASS Password of admin user
ADTEST_BIND_SECURITY NONE || TLS || STARTTLS || INSECURETLS || INSECURESTARTTLS - defaults to STARTTLS
ADTEST_BASEDN LDAP Base DN - for testing the root DN is recommended, e.g. DC=example,DC=com
ADTEST_PASSWORD_UPN userPrincipalName of a test user that will be used to test password changing functions

Nested Groups

Since v3.1.0, AuthenticateExtended and Conn.ObjectGroups will automatically search for nested groups. For example, if User A is a member of Group A, and Group A is a member of Group B, using Conn.ObjectGroups on User A will return both Group A and Group B.

Security

SQL Injection is a well known attack vector, and most SQL libraries provide mitigations such as prepared statements. Similarly, LDAP Injection, while not seen often in the wild, is something we should be concerned with.

Since v2.2.0, this library sanitizes inputs (with ldap.EscapeFilter) that are used to create LDAP filters in library functions, namely GetDN and GetAttributes. This means high level functions in this library are protected against malicious inputs. If you use Search or SearchOne, take care to sanitize any untrusted inputs you use in your LDAP filter.

Documentation

Index

Examples

Constants

View Source
const (
	SIDRevision    = 1
	SIDRevisionStr = "1"
)

The only valid SID revision is 1

View Source
const LDAPMatchingRuleInChain = "1.2.840.113556.1.4.1941"

Variables

View Source
var (
	ErrInvalidSIDHeader = errors.New("invalid sid header")
	ErrInvalidSID       = errors.New("invalid sid")
)

Functions

func Authenticate

func Authenticate(config *Config, username, password string) (bool, error)

Authenticate checks if the given credentials are valid, or returns an error if one occurred. username may be either the sAMAccountName or the userPrincipalName.

Example
package main

import (
	auth "github.com/korylprince/go-ad-auth/v3"
)

func main() {
	config := &auth.Config{
		Server:   "ldap.example.com",
		Port:     389,
		BaseDN:   "OU=Users,DC=example,DC=com",
		Security: auth.SecurityStartTLS,
	}

	username := "user"
	password := "pass"

	status, err := auth.Authenticate(config, username, password)

	if err != nil {
		//handle err
		return
	}

	if !status {
		//handle failed authentication
		return
	}
}
Output:

func AuthenticateExtended

func AuthenticateExtended(config *Config, username, password string, attrs, groups []string) (status bool, entry *ldap.Entry, userGroups []string, err error)

AuthenticateExtended checks if the given credentials are valid, or returns an error if one occurred. username may be either the sAMAccountName or the userPrincipalName. entry is the *ldap.Entry that holds the DN and any request attributes of the user. If groups is non-empty, userGroups will hold which of those groups the user is a member of. groups can be a list of groups referenced by DN or cn and the format provided will be the format returned.

Example
package main

import (
	"fmt"

	auth "github.com/korylprince/go-ad-auth/v3"
)

func main() {
	config := &auth.Config{
		Server:   "ldap.example.com",
		Port:     389,
		BaseDN:   "OU=Users,DC=example,DC=com", //make sure BaseDN includes any groups you'll be referencing
		Security: auth.SecurityStartTLS,
	}

	username := "user"
	password := "pass"

	status, entry, groups, err := auth.AuthenticateExtended(config, username, password, []string{"cn"}, []string{"Domain Admins"})

	if err != nil {
		//handle err
		return
	}

	if !status {
		//handle failed authentication
		return
	}

	if len(groups) == 0 {
		//handle user not being in any groups
		return
	}

	//get attributes
	cn := entry.GetAttributeValue("cn")

	fmt.Println(cn)
}
Output:

func UpdatePassword

func UpdatePassword(config *Config, username, oldPasswd, newPasswd string) error

UpdatePassword checks if the given credentials are valid and updates the password if they are, or returns an error if one occurred. UpdatePassword is used for users resetting their own password.

Example
package main

import (
	auth "github.com/korylprince/go-ad-auth/v3"
)

func main() {
	config := &auth.Config{
		Server:   "ldap.example.com",
		Port:     389,
		BaseDN:   "OU=Users,DC=example,DC=com",
		Security: auth.SecurityStartTLS, // Active Directory requires a secure connection to reset passwords
	}

	username := "user"
	password := "pass"
	newPassword := "Super$ecret"

	if err := auth.UpdatePassword(config, username, password, newPassword); err != nil {
		//handle err
	}
}
Output:

Types

type Config

type Config struct {
	Server   string
	Port     int
	BaseDN   string
	Security SecurityType
	RootCAs  *x509.CertPool
}

Config contains settings for connecting to an Active Directory server.

func (*Config) Connect

func (c *Config) Connect() (*Conn, error)

Connect returns an open connection to an Active Directory server or an error if one occurred.

func (*Config) Domain

func (c *Config) Domain() (string, error)

Domain returns the domain derived from BaseDN or an error if misconfigured.

func (*Config) UPN

func (c *Config) UPN(username string) (string, error)

UPN returns the userPrincipalName for the given username or an error if misconfigured.

type Conn

type Conn struct {
	Conn   *ldap.Conn
	Config *Config
}

Conn represents an Active Directory connection.

func (*Conn) Bind

func (c *Conn) Bind(upn, password string) (bool, error)

Bind authenticates the connection with the given userPrincipalName and password and returns the result or an error if one occurred.

func (*Conn) GetAttributes

func (c *Conn) GetAttributes(attr, value string, attrs []string) (*ldap.Entry, error)

GetAttributes returns the *ldap.Entry with the given attributes for the object with the given attribute value or an error if one occurred. attr and value are sanitized.

func (*Conn) GetDN

func (c *Conn) GetDN(attr, value string) (string, error)

GetDN returns the DN for the object with the given attribute value or an error if one occurred. attr and value are sanitized.

func (*Conn) GroupDN

func (c *Conn) GroupDN(group string) (string, error)

GroupDN returns the DN of the group with the given cn or an error if one occurred.

func (*Conn) ModifyDNPassword

func (c *Conn) ModifyDNPassword(dn, newPasswd string) error

ModifyDNPassword sets a new password for the given user or returns an error if one occurred. ModifyDNPassword is used for resetting user passwords using administrative privileges.

func (*Conn) ObjectGroups

func (c *Conn) ObjectGroups(attr, value string, groups []string) ([]string, error)

ObjectGroups returns which of the given groups (referenced by DN) the object with the given attribute value is in, if any, or an error if one occurred. Setting attr to "dn" and value to the DN of an object will avoid an extra LDAP search to get the object's DN.

func (*Conn) ObjectPrimaryGroup

func (c *Conn) ObjectPrimaryGroup(attr, value string) (string, error)

ObjectPrimaryGroup returns the DN of the primary group of the object with the given attribute value or an error if one occurred. Not all LDAP objects have a primary group.

func (*Conn) Search

func (c *Conn) Search(filter string, attrs []string, sizeLimit int) ([]*ldap.Entry, error)

Search returns the entries for the given search criteria or an error if one occurred.

func (*Conn) SearchOne

func (c *Conn) SearchOne(filter string, attrs []string) (*ldap.Entry, error)

SearchOne returns the single entry for the given search criteria or an error if one occurred. An error is returned if exactly one entry is not returned.

type SID

type SID struct {
	Revision            byte
	SubAuthorityLength  byte
	IdentifierAuthority uint64   // 6 bytes, big endian
	SubAuthoritys       []uint32 // little endian
}

SID represents the structure of a security identifier, described at https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid

func ParseSID

func ParseSID(s string) (*SID, error)

ParseSID parses a string representation of an SID, e.g. what *SID.String returns

func (*SID) Equal

func (sid *SID) Equal(other *SID) bool

Equal returns true if sid == other

func (*SID) FilterString

func (sid *SID) FilterString() string

FilterString returns an escaped binary representation of sid suitable for use in ldap filters. e.g. filter := fmt.Sprintf("(objectSid=%s)", sid.FilterString())

func (*SID) MarshalBinary

func (sid *SID) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface

func (*SID) RID

func (sid *SID) RID() uint32

RID returns the relative identifier for sid. If RID returns 0, the caller should verify sid actually has sub authorities before using 0 as an actual RID

func (*SID) String

func (sid *SID) String() string

String returns the string representation of sid, e.g. "S-1-5-..."

func (*SID) UnmarshalBinary

func (sid *SID) UnmarshalBinary(buf []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface

type SecurityType

type SecurityType int

SecurityType specifies the type of security to use when connecting to an Active Directory Server.

const (
	SecurityNone SecurityType = iota
	SecurityTLS
	SecurityStartTLS
	SecurityInsecureTLS
	SecurityInsecureStartTLS
)

Security will default to SecurityNone if not given.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL