-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathconn.go
81 lines (74 loc) · 2.41 KB
/
conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package auth
import (
"crypto/tls"
"errors"
"fmt"
ldap "github.com/go-ldap/ldap/v3"
)
//Conn represents an Active Directory connection.
type Conn struct {
Conn *ldap.Conn
Config *Config
}
//Connect returns an open connection to an Active Directory server or an error if one occurred.
func (c *Config) Connect() (*Conn, error) {
switch c.Security {
case SecurityNone:
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port))
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
return &Conn{Conn: conn, Config: c}, nil
case SecurityTLS:
conn, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port), &tls.Config{ServerName: c.Server, RootCAs: c.RootCAs})
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
return &Conn{Conn: conn, Config: c}, nil
case SecurityStartTLS:
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port))
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
err = conn.StartTLS(&tls.Config{ServerName: c.Server, RootCAs: c.RootCAs})
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
return &Conn{Conn: conn, Config: c}, nil
case SecurityInsecureTLS:
conn, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port), &tls.Config{ServerName: c.Server, InsecureSkipVerify: true})
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
return &Conn{Conn: conn, Config: c}, nil
case SecurityInsecureStartTLS:
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port))
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
err = conn.StartTLS(&tls.Config{ServerName: c.Server, InsecureSkipVerify: true})
if err != nil {
return nil, fmt.Errorf("Connection error: %w", err)
}
return &Conn{Conn: conn, Config: c}, nil
default:
return nil, errors.New("Configuration error: invalid SecurityType")
}
}
//Bind authenticates the connection with the given userPrincipalName and password
//and returns the result or an error if one occurred.
func (c *Conn) Bind(upn, password string) (bool, error) {
if password == "" {
return false, nil
}
err := c.Conn.Bind(upn, password)
if err != nil {
if e, ok := err.(*ldap.Error); ok {
if e.ResultCode == ldap.LDAPResultInvalidCredentials {
return false, nil
}
}
return false, fmt.Errorf("Bind error (%s): %w", upn, err)
}
return true, nil
}