This repository has been archived by the owner on Feb 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ldap.go
85 lines (73 loc) · 1.99 KB
/
ldap.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
82
83
84
85
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"github.com/pkg/errors"
"gopkg.in/ldap.v2"
)
func ConnectLDAP() (*ldap.Conn, error) {
config := LoadConfig()
tlsConfig := tls.Config{}
var l *ldap.Conn
if config.LDAP.IsTLS {
tlsConfig.ServerName = config.LDAP.ServerHost
if config.LDAP.CACertFilePath != "" {
caCert, err := ioutil.ReadFile(config.LDAP.CACertFilePath)
if err != nil {
return nil, errors.Wrap(err, "Failed to load CACert")
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
_l, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", config.LDAP.ServerHost, config.LDAP.ServerPort), &tlsConfig)
if err != nil {
return nil, errors.Wrap(err, "Failed to dial to LDAPS server")
}
l = _l
} else {
_l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", config.LDAP.ServerHost, config.LDAP.ServerPort))
if err != nil {
return nil, errors.Wrap(err, "Failed to dial to LDAP server")
}
l = _l
}
err := l.Bind(config.LDAP.BindDN, config.LDAP.BindPassword)
if err != nil {
l.Close()
return nil, errors.Wrap(err, "Failed to bind binding user")
}
return l, nil
}
func AuthLDAP(l *ldap.Conn, username string, password string) error {
config := LoadConfig()
searchRequest := ldap.NewSearchRequest(
config.LDAP.BaseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf(config.LDAP.SearchFilter, username),
[]string{"dn"}, nil,
)
result, err := l.Search(searchRequest)
if err != nil {
return errors.Wrap(err, "Failed to search")
}
count := len(result.Entries)
if count > 1 {
return errors.New("Unexpected user")
}
if count <= 0 {
return errors.New("No such user")
}
userDN := result.Entries[0].DN
err = l.Bind(userDN, password)
if err != nil {
return errors.Wrap(err, "Failed to bind normal user")
}
err = l.Bind(config.LDAP.BindDN, config.LDAP.BindPassword)
if err != nil {
return errors.Wrap(err, "Failed to re-bind")
}
return nil
}