|
|
@@ -2,8 +2,11 @@ package service
|
|
2
|
2
|
|
|
3
|
3
|
import (
|
|
4
|
4
|
"crypto/tls"
|
|
|
5
|
+ "crypto/x509"
|
|
5
|
6
|
"errors"
|
|
6
|
7
|
"fmt"
|
|
|
8
|
+ "net/url"
|
|
|
9
|
+ "os"
|
|
7
|
10
|
"strconv"
|
|
8
|
11
|
"strings"
|
|
9
|
12
|
|
|
|
@@ -14,6 +17,8 @@ import (
|
|
14
|
17
|
)
|
|
15
|
18
|
|
|
16
|
19
|
var (
|
|
|
20
|
+ ErrUrlParseFailed = errors.New("UrlParseFailed")
|
|
|
21
|
+ ErrFileReadFailed = errors.New("FileReadFailed")
|
|
17
|
22
|
ErrLdapNotEnabled = errors.New("LdapNotEnabled")
|
|
18
|
23
|
ErrLdapUserDisabled = errors.New("UserDisabledAtLdap")
|
|
19
|
24
|
ErrLdapUserNotFound = errors.New("UserNotFound")
|
|
|
@@ -67,21 +72,38 @@ func (lu *LdapUser) ToUser(u *model.User) *model.User {
|
|
67
|
72
|
|
|
68
|
73
|
// connectAndBind creates an LDAP connection, optionally starts TLS, and then binds using the provided credentials.
|
|
69
|
74
|
func (ls *LdapService) connectAndBind(cfg *config.Ldap, username, password string) (*ldap.Conn, error) {
|
|
70
|
|
- conn, err := ldap.DialURL(cfg.Url)
|
|
|
75
|
+ u, err := url.Parse(cfg.Url)
|
|
71
|
76
|
if err != nil {
|
|
72
|
|
- return nil, errors.Join(ErrLdapConnectFailed, err)
|
|
|
77
|
+ return nil, errors.Join(ErrUrlParseFailed, err)
|
|
73
|
78
|
}
|
|
74
|
79
|
|
|
75
|
|
- if cfg.TLS {
|
|
|
80
|
+ var conn *ldap.Conn
|
|
|
81
|
+ if u.Scheme == "ldaps" {
|
|
76
|
82
|
// WARNING: InsecureSkipVerify: true is not recommended for production
|
|
77
|
|
- if err = conn.StartTLS(&tls.Config{InsecureSkipVerify: !cfg.TlsVerify}); err != nil {
|
|
78
|
|
- conn.Close()
|
|
79
|
|
- return nil, errors.Join(ErrLdapTlsFailed, err)
|
|
|
83
|
+ tlsConfig := &tls.Config{InsecureSkipVerify: !cfg.TlsVerify}
|
|
|
84
|
+ if cfg.TlsCaFile != "" {
|
|
|
85
|
+ caCert, err := os.ReadFile(cfg.TlsCaFile)
|
|
|
86
|
+ if err != nil {
|
|
|
87
|
+ return nil, errors.Join(ErrFileReadFailed, err)
|
|
|
88
|
+ }
|
|
|
89
|
+ caCertPool := x509.NewCertPool()
|
|
|
90
|
+ if !caCertPool.AppendCertsFromPEM(caCert) {
|
|
|
91
|
+ return nil, errors.Join(ErrLdapTlsFailed, errors.New("failed to append CA certificate"))
|
|
|
92
|
+ }
|
|
|
93
|
+ tlsConfig.RootCAs = caCertPool
|
|
80
|
94
|
}
|
|
|
95
|
+ conn, err = ldap.DialURL(cfg.Url, ldap.DialWithTLSConfig(tlsConfig))
|
|
|
96
|
+ } else {
|
|
|
97
|
+ conn, err = ldap.DialURL(cfg.Url)
|
|
|
98
|
+ }
|
|
|
99
|
+
|
|
|
100
|
+ if err != nil {
|
|
|
101
|
+ return nil, errors.Join(ErrLdapConnectFailed, err)
|
|
81
|
102
|
}
|
|
82
|
103
|
|
|
83
|
104
|
// Bind as the "service" user
|
|
84
|
105
|
if err = conn.Bind(username, password); err != nil {
|
|
|
106
|
+ fmt.Println("Bind failed")
|
|
85
|
107
|
conn.Close()
|
|
86
|
108
|
return nil, errors.Join(ErrLdapBindService, err)
|
|
87
|
109
|
}
|