Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
johnweldon committed Aug 15, 2021
2 parents a255f7f + d19d812 commit 0720fd4
Show file tree
Hide file tree
Showing 24 changed files with 663 additions and 13 deletions.
2 changes: 1 addition & 1 deletion bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
child := packet.Children[1].Children[1]
ntlmsspChallenge = child.ByteValue
// Check to make sure we got the right message. It will always start with NTLMSSP
if !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
return result, GetLDAPError(packet)
}
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
Expand Down
1 change: 1 addition & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type Client interface {
Del(*DelRequest) error
Modify(*ModifyRequest) error
ModifyDN(*ModifyDNRequest) error
ModifyWithResult(*ModifyRequest) (*ModifyResult, error)

Compare(dn, attribute, value string) (bool, error)
PasswordModify(*PasswordModifyRequest) (*PasswordModifyResult, error)
Expand Down
2 changes: 1 addition & 1 deletion conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ func (l *Conn) processMessages() {
// All reads will return immediately
if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
l.Debug.Printf("Receiving message timeout for %d", message.MessageID)
msgCtx.sendResponse(&PacketResponse{message.Packet, errors.New("ldap: connection timed out")})
msgCtx.sendResponse(&PacketResponse{message.Packet, NewError(ErrorNetwork, errors.New("ldap: connection timed out"))})
delete(l.messageContexts, message.MessageID)
close(msgCtx.responses)
}
Expand Down
11 changes: 10 additions & 1 deletion conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestUnresponsiveConnection(t *testing.T) {
if err == nil {
t.Fatalf("expected timeout error")
}
if err.Error() != "ldap: connection timed out" {
if !IsErrorWithCode(err, ErrorNetwork) || err.(*Error).Err.Error() != "ldap: connection timed out" {
t.Fatalf("unexpected error: %v", err)
}
}
Expand Down Expand Up @@ -104,6 +104,15 @@ func TestFinishMessage(t *testing.T) {
conn.Close()
}

// See: https://github.com/go-ldap/ldap/issues/332
func TestNilConnection(t *testing.T) {
var conn *Conn
_, err := conn.Search(&SearchRequest{})
if err != ErrNilConnection {
t.Fatalf("expected error to be ErrNilConnection, got %v", err)
}
}

func testSendRequest(t *testing.T, ptc *packetTranslatorConn, conn *Conn) (msgCtx *messageContext) {
var msgID int64
runWithTimeout(t, time.Second, func() {
Expand Down
36 changes: 36 additions & 0 deletions control.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@ const (
ControlTypeVChuPasswordWarning = "2.16.840.1.113730.3.4.5"
// ControlTypeManageDsaIT - https://tools.ietf.org/html/rfc3296
ControlTypeManageDsaIT = "2.16.840.1.113730.3.4.2"
// ControlTypeWhoAmI - https://tools.ietf.org/html/rfc4532
ControlTypeWhoAmI = "1.3.6.1.4.1.4203.1.11.3"

// ControlTypeMicrosoftNotification - https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx
ControlTypeMicrosoftNotification = "1.2.840.113556.1.4.528"
// ControlTypeMicrosoftShowDeleted - https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx
ControlTypeMicrosoftShowDeleted = "1.2.840.113556.1.4.417"
// ControlTypeMicrosoftServerLinkTTL - https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f4f523a8-abc0-4b3a-a471-6b2fef135481?redirectedfrom=MSDN
ControlTypeMicrosoftServerLinkTTL = "1.2.840.113556.1.4.2309"
)

// ControlTypeMap maps controls to text descriptions
Expand All @@ -32,6 +36,7 @@ var ControlTypeMap = map[string]string{
ControlTypeManageDsaIT: "Manage DSA IT",
ControlTypeMicrosoftNotification: "Change Notification - Microsoft",
ControlTypeMicrosoftShowDeleted: "Show Deleted Objects - Microsoft",
ControlTypeMicrosoftServerLinkTTL: "Return TTL-DNs for link values with associated expiry times - Microsoft",
}

// Control defines an interface controls provide to encode and describe themselves
Expand Down Expand Up @@ -305,6 +310,35 @@ func NewControlMicrosoftShowDeleted() *ControlMicrosoftShowDeleted {
return &ControlMicrosoftShowDeleted{}
}

// ControlMicrosoftServerLinkTTL implements the control described in https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f4f523a8-abc0-4b3a-a471-6b2fef135481?redirectedfrom=MSDN
type ControlMicrosoftServerLinkTTL struct{}

// GetControlType returns the OID
func (c *ControlMicrosoftServerLinkTTL) GetControlType() string {
return ControlTypeMicrosoftServerLinkTTL
}

// Encode returns the ber packet representation
func (c *ControlMicrosoftServerLinkTTL) Encode() *ber.Packet {
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeMicrosoftServerLinkTTL, "Control Type ("+ControlTypeMap[ControlTypeMicrosoftServerLinkTTL]+")"))

return packet
}

// String returns a human-readable description
func (c *ControlMicrosoftServerLinkTTL) String() string {
return fmt.Sprintf(
"Control Type: %s (%q)",
ControlTypeMap[ControlTypeMicrosoftServerLinkTTL],
ControlTypeMicrosoftServerLinkTTL)
}

// NewControlMicrosoftServerLinkTTL returns a ControlMicrosoftServerLinkTTL control
func NewControlMicrosoftServerLinkTTL() *ControlMicrosoftServerLinkTTL {
return &ControlMicrosoftServerLinkTTL{}
}

// FindControl returns the first control of the given type in the list, or nil
func FindControl(controls []Control, controlType string) Control {
for _, c := range controls {
Expand Down Expand Up @@ -449,6 +483,8 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
return NewControlMicrosoftNotification(), nil
case ControlTypeMicrosoftShowDeleted:
return NewControlMicrosoftShowDeleted(), nil
case ControlTypeMicrosoftServerLinkTTL:
return NewControlMicrosoftServerLinkTTL(), nil
default:
c := new(ControlString)
c.ControlType = ControlType
Expand Down
8 changes: 8 additions & 0 deletions control_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ func TestControlMicrosoftShowDeleted(t *testing.T) {
runControlTest(t, NewControlMicrosoftShowDeleted())
}

func TestControlMicrosoftServerLinkTTL(t *testing.T) {
runControlTest(t, NewControlMicrosoftServerLinkTTL())
}

func TestControlString(t *testing.T) {
runControlTest(t, NewControlString("x", true, "y"))
runControlTest(t, NewControlString("x", true, ""))
Expand Down Expand Up @@ -93,6 +97,10 @@ func TestDescribeControlMicrosoftShowDeleted(t *testing.T) {
runAddControlDescriptions(t, NewControlMicrosoftShowDeleted(), "Control Type (Show Deleted Objects - Microsoft)")
}

func TestDescribeControlMicrosoftServerLinkTTL(t *testing.T) {
runAddControlDescriptions(t, NewControlMicrosoftServerLinkTTL(), "Control Type (Return TTL-DNs for link values with associated expiry times - Microsoft)")
}

func TestDescribeControlString(t *testing.T) {
runAddControlDescriptions(t, NewControlString("x", true, "y"), "Control Type ()", "Criticality", "Control Value")
runAddControlDescriptions(t, NewControlString("x", true, ""), "Control Type ()", "Criticality")
Expand Down
63 changes: 63 additions & 0 deletions dn.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,66 @@ func (r *RelativeDN) hasAllAttributes(attrs []*AttributeTypeAndValue) bool {
func (a *AttributeTypeAndValue) Equal(other *AttributeTypeAndValue) bool {
return strings.EqualFold(a.Type, other.Type) && a.Value == other.Value
}

// Equal returns true if the DNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch).
// Returns true if they have the same number of relative distinguished names
// and corresponding relative distinguished names (by position) are the same.
// Case of the attribute type and value is not significant
func (d *DN) EqualFold(other *DN) bool {
if len(d.RDNs) != len(other.RDNs) {
return false
}
for i := range d.RDNs {
if !d.RDNs[i].EqualFold(other.RDNs[i]) {
return false
}
}
return true
}

// AncestorOfFold returns true if the other DN consists of at least one RDN followed by all the RDNs of the current DN.
// Case of the attribute type and value is not significant
func (d *DN) AncestorOfFold(other *DN) bool {
if len(d.RDNs) >= len(other.RDNs) {
return false
}
// Take the last `len(d.RDNs)` RDNs from the other DN to compare against
otherRDNs := other.RDNs[len(other.RDNs)-len(d.RDNs):]
for i := range d.RDNs {
if !d.RDNs[i].EqualFold(otherRDNs[i]) {
return false
}
}
return true
}

// Equal returns true if the RelativeDNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch).
// Case of the attribute type is not significant
func (r *RelativeDN) EqualFold(other *RelativeDN) bool {
if len(r.Attributes) != len(other.Attributes) {
return false
}
return r.hasAllAttributesFold(other.Attributes) && other.hasAllAttributesFold(r.Attributes)
}

func (r *RelativeDN) hasAllAttributesFold(attrs []*AttributeTypeAndValue) bool {
for _, attr := range attrs {
found := false
for _, myattr := range r.Attributes {
if myattr.EqualFold(attr) {
found = true
break
}
}
if !found {
return false
}
}
return true
}

// EqualFold returns true if the AttributeTypeAndValue is equivalent to the specified AttributeTypeAndValue
// Case of the attribute type and value is not significant
func (a *AttributeTypeAndValue) EqualFold(other *AttributeTypeAndValue) bool {
return strings.EqualFold(a.Type, other.Type) && strings.EqualFold(a.Value, other.Value)
}
44 changes: 44 additions & 0 deletions dn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,50 @@ func TestDNEqual(t *testing.T) {
}
}

func TestDNEqualFold(t *testing.T) {
testcases := []struct {
A string
B string
Equal bool
}{
// Match on case insensitive
{"o=A", "o=a", true},
{"o=A,o=b", "o=a,o=B", true},
{"o=a+o=B", "o=A+o=b", true},
{
"cn=users,ou=example,dc=com",
"cn=Users,ou=example,dc=com",
true,
},

// Match on case insensitive and case mismatch in type
{"o=A", "O=a", true},
{"o=A,o=b", "o=a,O=B", true},
{"o=a+o=B", "o=A+O=b", true},
}

for i, tc := range testcases {
a, err := ParseDN(tc.A)
if err != nil {
t.Errorf("%d: %v", i, err)
continue
}
b, err := ParseDN(tc.B)
if err != nil {
t.Errorf("%d: %v", i, err)
continue
}
if expected, actual := tc.Equal, a.EqualFold(b); expected != actual {
t.Errorf("%d: when comparing '%s' and '%s' expected %v, got %v", i, tc.A, tc.B, expected, actual)
continue
}
if expected, actual := tc.Equal, b.EqualFold(a); expected != actual {
t.Errorf("%d: when comparing '%s' and '%s' expected %v, got %v", i, tc.A, tc.B, expected, actual)
continue
}
}
}

func TestDNAncestor(t *testing.T) {
testcases := []struct {
A string
Expand Down
25 changes: 24 additions & 1 deletion examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ func ExampleConn_Modify() {
}
}

// This example shows how a typical application can verify a login attempt
// Example_userAuthentication shows how a typical application can verify a login attempt
// Refer to https://github.com/go-ldap/ldap/issues/93 for issues revolving around unauthenticated binds, with zero length passwords
func Example_userAuthentication() {
// The username and password we want to check
username := "someuser"
Expand Down Expand Up @@ -391,3 +392,25 @@ func ExampleConn_ExternalBind() {

// Conduct ldap queries
}

// ExampleConn_WhoAmI demonstrates how to run a whoami request according to https://tools.ietf.org/html/rfc4532
func ExampleConn_WhoAmI() {
conn, err := DialURL("ldap.example.org:389")
if err != nil {
log.Fatalf("Failed to connect: %s\n", err)
}

_, err = conn.SimpleBind(&SimpleBindRequest{
Username: "uid=someone,ou=people,dc=example,dc=org",
Password: "MySecretPass",
})
if err != nil {
log.Fatalf("Failed to bind: %s\n", err)
}

res, err := conn.WhoAmI(nil)
if err != nil {
log.Fatalf("Failed to call WhoAmI(): %s\n", err)
}
fmt.Printf("I am: %s\n", res.AuthzID)
}
45 changes: 45 additions & 0 deletions modify.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ldap

import (
"errors"
"log"

ber "github.com/go-asn1-ber/asn1-ber"
Expand Down Expand Up @@ -130,3 +131,47 @@ func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
}
return nil
}

// ModifyResult holds the server's response to a modify request
type ModifyResult struct {
// Controls are the returned controls
Controls []Control
}

// ModifyWithResult performs the ModifyRequest and returns the result
func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, error) {
msgCtx, err := l.doRequest(modifyRequest)
if err != nil {
return nil, err
}
defer l.finishMessage(msgCtx)

result := &ModifyResult{
Controls: make([]Control, 0),
}

l.Debug.Printf("%d: waiting for response", msgCtx.id)
packet, err := l.readPacket(msgCtx)
if err != nil {
return nil, err
}

switch packet.Children[1].Tag {
case ApplicationModifyResponse:
err := GetLDAPError(packet)
if err != nil {
return nil, err
}
if len(packet.Children) == 3 {
for _, child := range packet.Children[2].Children {
decodedChild, err := DecodeControl(child)
if err != nil {
return nil, errors.New("failed to decode child control: " + err.Error())
}
result.Controls = append(result.Controls, decodedChild)
}
}
}
l.Debug.Printf("%d: returning", msgCtx.id)
return result, nil
}
5 changes: 5 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
var (
errRespChanClosed = errors.New("ldap: response channel closed")
errCouldNotRetMsg = errors.New("ldap: could not retrieve message")
ErrNilConnection = errors.New("ldap: conn is nil, expected net.Conn")
)

type request interface {
Expand All @@ -22,6 +23,10 @@ func (f requestFunc) appendTo(p *ber.Packet) error {
}

func (l *Conn) doRequest(req request) (*messageContext, error) {
if l == nil || l.conn == nil {
return nil, ErrNilConnection
}

packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
if err := req.appendTo(packet); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion v3/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
child := packet.Children[1].Children[1]
ntlmsspChallenge = child.ByteValue
// Check to make sure we got the right message. It will always start with NTLMSSP
if !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
return result, GetLDAPError(packet)
}
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
Expand Down
1 change: 1 addition & 0 deletions v3/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type Client interface {
Del(*DelRequest) error
Modify(*ModifyRequest) error
ModifyDN(*ModifyDNRequest) error
ModifyWithResult(*ModifyRequest) (*ModifyResult, error)

Compare(dn, attribute, value string) (bool, error)
PasswordModify(*PasswordModifyRequest) (*PasswordModifyResult, error)
Expand Down
2 changes: 1 addition & 1 deletion v3/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ func (l *Conn) processMessages() {
// All reads will return immediately
if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
l.Debug.Printf("Receiving message timeout for %d", message.MessageID)
msgCtx.sendResponse(&PacketResponse{message.Packet, errors.New("ldap: connection timed out")})
msgCtx.sendResponse(&PacketResponse{message.Packet, NewError(ErrorNetwork, errors.New("ldap: connection timed out"))})
delete(l.messageContexts, message.MessageID)
close(msgCtx.responses)
}
Expand Down

0 comments on commit 0720fd4

Please sign in to comment.