use LDAP config from minio/pkg to share with console (#15810)

This commit is contained in:
Aditya Manthramurthy 2022-10-07 22:12:36 -07:00 committed by GitHub
parent 927a879052
commit 64cf887b28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 107 additions and 696 deletions

View File

@ -657,7 +657,7 @@ func (a adminAPIHandlers) AddServiceAccount(w http.ResponseWriter, r *http.Reque
// In case of LDAP we need to resolve the targetUser to a DN and // In case of LDAP we need to resolve the targetUser to a DN and
// query their groups: // query their groups:
if globalLDAPConfig.Enabled { if globalLDAPConfig.Enabled() {
opts.claims[ldapUserN] = targetUser // simple username opts.claims[ldapUserN] = targetUser // simple username
targetUser, targetGroups, err = globalLDAPConfig.LookupUserDN(targetUser) targetUser, targetGroups, err = globalLDAPConfig.LookupUserDN(targetUser)
if err != nil { if err != nil {
@ -2086,7 +2086,7 @@ func (a adminAPIHandlers) ImportIAM(w http.ResponseWriter, r *http.Request) {
// In case of LDAP we need to resolve the targetUser to a DN and // In case of LDAP we need to resolve the targetUser to a DN and
// query their groups: // query their groups:
if globalLDAPConfig.Enabled { if globalLDAPConfig.Enabled() {
opts.claims[ldapUserN] = svcAcctReq.AccessKey // simple username opts.claims[ldapUserN] = svcAcctReq.AccessKey // simple username
targetUser, _, err := globalLDAPConfig.LookupUserDN(svcAcctReq.AccessKey) targetUser, _, err := globalLDAPConfig.LookupUserDN(svcAcctReq.AccessKey)
if err != nil { if err != nil {

View File

@ -1798,8 +1798,8 @@ func getServerInfo(ctx context.Context, r *http.Request) madmin.InfoMessage {
kmsStat := fetchKMSStatus() kmsStat := fetchKMSStatus()
ldap := madmin.LDAP{} ldap := madmin.LDAP{}
if globalLDAPConfig.Enabled { if globalLDAPConfig.Enabled() {
ldapConn, err := globalLDAPConfig.Connect() ldapConn, err := globalLDAPConfig.LDAP.Connect()
//nolint:gocritic //nolint:gocritic
if err != nil { if err != nil {
ldap.Status = string(madmin.ItemOffline) ldap.Status = string(madmin.ItemOffline)

View File

@ -202,7 +202,7 @@ func minioConfigToConsoleFeatures() {
} }
} }
// Enable if LDAP is enabled. // Enable if LDAP is enabled.
if globalLDAPConfig.Enabled { if globalLDAPConfig.Enabled() {
os.Setenv("CONSOLE_LDAP_ENABLED", config.EnableOn) os.Setenv("CONSOLE_LDAP_ENABLED", config.EnableOn)
} }
os.Setenv("CONSOLE_MINIO_REGION", globalSite.Region) os.Setenv("CONSOLE_MINIO_REGION", globalSite.Region)

View File

@ -335,12 +335,12 @@ func validateSubSysConfig(s config.Config, subSys string, objAPI ObjectLayer) er
return err return err
} }
case config.IdentityLDAPSubSys: case config.IdentityLDAPSubSys:
cfg, err := xldap.Lookup(s[config.IdentityLDAPSubSys][config.Default], globalRootCAs) cfg, err := xldap.Lookup(s, globalRootCAs)
if err != nil { if err != nil {
return err return err
} }
if cfg.Enabled { if cfg.Enabled() {
conn, cerr := cfg.Connect() conn, cerr := cfg.LDAP.Connect()
if cerr != nil { if cerr != nil {
return cerr return cerr
} }

View File

@ -855,5 +855,5 @@ type serverConfigV33 struct {
// Add new external policy enforcements here. // Add new external policy enforcements here.
} `json:"policy"` } `json:"policy"`
LDAPServerConfig xldap.Config `json:"ldapserverconfig"` LDAPServerConfig xldap.LegacyConfig `json:"ldapserverconfig"`
} }

View File

@ -163,7 +163,7 @@ func (sys *IAMSys) LoadServiceAccount(ctx context.Context, accessKey string) err
// initStore initializes IAM stores // initStore initializes IAM stores
func (sys *IAMSys) initStore(objAPI ObjectLayer, etcdClient *etcd.Client) { func (sys *IAMSys) initStore(objAPI ObjectLayer, etcdClient *etcd.Client) {
if sys.ldapConfig.Enabled { if sys.ldapConfig.Enabled() {
sys.SetUsersSysType(LDAPUsersSysType) sys.SetUsersSysType(LDAPUsersSysType)
} }
@ -222,8 +222,6 @@ func (sys *IAMSys) Init(ctx context.Context, objAPI ObjectLayer, etcdClient *etc
s := globalServerConfig s := globalServerConfig
globalServerConfigMu.RUnlock() globalServerConfigMu.RUnlock()
ldapCfg := s[config.IdentityLDAPSubSys][config.Default]
var err error var err error
globalOpenIDConfig, err = openid.LookupConfig(s, globalOpenIDConfig, err = openid.LookupConfig(s,
NewGatewayHTTPTransport(), xhttp.DrainBody, globalSite.Region) NewGatewayHTTPTransport(), xhttp.DrainBody, globalSite.Region)
@ -232,7 +230,7 @@ func (sys *IAMSys) Init(ctx context.Context, objAPI ObjectLayer, etcdClient *etc
} }
// Initialize if LDAP is enabled // Initialize if LDAP is enabled
globalLDAPConfig, err = xldap.Lookup(ldapCfg, globalRootCAs) globalLDAPConfig, err = xldap.Lookup(s, globalRootCAs)
if err != nil { if err != nil {
logger.LogIf(ctx, fmt.Errorf("Unable to parse LDAP configuration: %w", err)) logger.LogIf(ctx, fmt.Errorf("Unable to parse LDAP configuration: %w", err))
} }
@ -347,7 +345,7 @@ func (sys *IAMSys) Init(ctx context.Context, objAPI ObjectLayer, etcdClient *etc
} }
} }
}() }()
case sys.ldapConfig.Enabled: case sys.ldapConfig.Enabled():
go func() { go func() {
timer := time.NewTimer(refreshInterval) timer := time.NewTimer(refreshInterval)
defer timer.Stop() defer timer.Stop()

View File

@ -577,11 +577,11 @@ func (c *SiteReplicationSys) PeerJoinReq(ctx context.Context, arg madmin.SRPeerJ
func (c *SiteReplicationSys) GetIDPSettings(ctx context.Context) madmin.IDPSettings { func (c *SiteReplicationSys) GetIDPSettings(ctx context.Context) madmin.IDPSettings {
s := madmin.IDPSettings{} s := madmin.IDPSettings{}
s.LDAP = madmin.LDAPSettings{ s.LDAP = madmin.LDAPSettings{
IsLDAPEnabled: globalLDAPConfig.Enabled, IsLDAPEnabled: globalLDAPConfig.Enabled(),
LDAPUserDNSearchBase: globalLDAPConfig.UserDNSearchBaseDistName, LDAPUserDNSearchBase: globalLDAPConfig.LDAP.UserDNSearchBaseDistName,
LDAPUserDNSearchFilter: globalLDAPConfig.UserDNSearchFilter, LDAPUserDNSearchFilter: globalLDAPConfig.LDAP.UserDNSearchFilter,
LDAPGroupSearchBase: globalLDAPConfig.GroupSearchBaseDistName, LDAPGroupSearchBase: globalLDAPConfig.LDAP.GroupSearchBaseDistName,
LDAPGroupSearchFilter: globalLDAPConfig.GroupSearchFilter, LDAPGroupSearchFilter: globalLDAPConfig.LDAP.GroupSearchFilter,
} }
s.OpenID = globalOpenIDConfig.GetSettings() s.OpenID = globalOpenIDConfig.GetSettings()
if s.OpenID.Enabled { if s.OpenID.Enabled {

2
go.mod
View File

@ -50,7 +50,7 @@ require (
github.com/minio/kes v0.21.0 github.com/minio/kes v0.21.0
github.com/minio/madmin-go v1.5.3 github.com/minio/madmin-go v1.5.3
github.com/minio/minio-go/v7 v7.0.40-0.20220928095841-8848d8affe8a github.com/minio/minio-go/v7 v7.0.40-0.20220928095841-8848d8affe8a
github.com/minio/pkg v1.4.5 github.com/minio/pkg v1.5.0
github.com/minio/selfupdate v0.5.0 github.com/minio/selfupdate v0.5.0
github.com/minio/sha256-simd v1.0.0 github.com/minio/sha256-simd v1.0.0
github.com/minio/simdjson-go v0.4.2 github.com/minio/simdjson-go v0.4.2

4
go.sum
View File

@ -662,8 +662,8 @@ github.com/minio/minio-go/v7 v7.0.23/go.mod h1:ei5JjmxwHaMrgsMrn4U/+Nmg+d8MKS1U2
github.com/minio/minio-go/v7 v7.0.40-0.20220928095841-8848d8affe8a h1:COFh7S3tOKmJNYtKKFAuHQFH7MAaXxg4aAluXC9KQgc= github.com/minio/minio-go/v7 v7.0.40-0.20220928095841-8848d8affe8a h1:COFh7S3tOKmJNYtKKFAuHQFH7MAaXxg4aAluXC9KQgc=
github.com/minio/minio-go/v7 v7.0.40-0.20220928095841-8848d8affe8a/go.mod h1:nCrRzjoSUQh8hgKKtu3Y708OLvRLtuASMg2/nvmbarw= github.com/minio/minio-go/v7 v7.0.40-0.20220928095841-8848d8affe8a/go.mod h1:nCrRzjoSUQh8hgKKtu3Y708OLvRLtuASMg2/nvmbarw=
github.com/minio/pkg v1.1.20/go.mod h1:Xo7LQshlxGa9shKwJ7NzQbgW4s8T/Wc1cOStR/eUiMY= github.com/minio/pkg v1.1.20/go.mod h1:Xo7LQshlxGa9shKwJ7NzQbgW4s8T/Wc1cOStR/eUiMY=
github.com/minio/pkg v1.4.5 h1:XE3o8XWc+oQSs9LXLtImfRrAfxRfI3dq9tJ0PerhOk8= github.com/minio/pkg v1.5.0 h1:517jxphvCLSNE8vbctMY4avaRDZXiGT7lX+cXPXFb98=
github.com/minio/pkg v1.4.5/go.mod h1:mxCLAG+fOGIQr6odQ5Ukqc6qv9Zj6v1d6TD3NP82B7Y= github.com/minio/pkg v1.5.0/go.mod h1:koF2J2Ep/zpd//k+3UYdh6ySZKjqzy9C6RCZRX7uRY8=
github.com/minio/selfupdate v0.5.0 h1:0UH1HlL49+2XByhovKl5FpYTjKfvrQ2sgL1zEXK6mfI= github.com/minio/selfupdate v0.5.0 h1:0UH1HlL49+2XByhovKl5FpYTjKfvrQ2sgL1zEXK6mfI=
github.com/minio/selfupdate v0.5.0/go.mod h1:mcDkzMgq8PRcpCRJo/NlPY7U45O5dfYl2Y0Rg7IustY= github.com/minio/selfupdate v0.5.0/go.mod h1:mcDkzMgq8PRcpCRJo/NlPY7U45O5dfYl2Y0Rg7IustY=
github.com/minio/sha256-simd v0.1.1/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM= github.com/minio/sha256-simd v0.1.1/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM=

View File

@ -1069,7 +1069,7 @@ func getEnvVarName(subSys, target, param string) string {
Default, target) Default, target)
} }
var resolvableSubsystems = set.CreateStringSet(IdentityOpenIDSubSys) var resolvableSubsystems = set.CreateStringSet(IdentityOpenIDSubSys, IdentityLDAPSubSys)
// ValueSource represents the source of a config parameter value. // ValueSource represents the source of a config parameter value.
type ValueSource uint8 type ValueSource uint8

View File

@ -1,271 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package ldap
import (
"fmt"
"strings"
)
// Result - type for high-level names for the validation status of the config.
type Result string
// Constant values for Result type.
const (
ConfigOk Result = "Config OK"
ConnectivityError Result = "LDAP Server Connection Error"
LookupBindError Result = "LDAP Lookup Bind Error"
UserSearchParamsMisconfigured Result = "User Search Parameters Misconfigured"
GroupSearchParamsMisconfigured Result = "Group Search Parameters Misconfigured"
UserDNLookupError Result = "User DN Lookup Error"
GroupMembershipsLookupError Result = "Group Memberships Lookup Error"
)
// Validation returns feedback on the configuration. The `Suggestion` field
// needs to be "printed" for friendly display (it can contain escaped newlines
// `\n`).
type Validation struct {
Result Result
Detail string
Suggestion string
ErrCause error
}
// Error instance for Validation.
func (v Validation) Error() string {
if v.Result == ConfigOk {
return ""
}
return fmt.Sprintf("%s: %s", string(v.Result), v.Detail)
}
// IsOk - returns if the validation succeeded.
func (v Validation) IsOk() bool {
return v.Result == ConfigOk
}
// UserLookupResult returns the DN found for the test user and their group
// memberships.
type UserLookupResult struct {
DN string
GroupDNMemberships []string
}
// Validate validates the LDAP configuration. It can be called with any subset
// of configuration parameters provided by the user - it will return
// information on what needs to be done to fix the problem if any.
//
// This function updates the UserDNSearchBaseDistNames and
// GroupSearchBaseDistNames fields of the Config - however this an idempotent
// operation. This is done to support configuration validation in Console/mc and
// for tests.
func (l *Config) Validate() Validation {
if !l.Enabled {
return Validation{Result: ConfigOk, Detail: "Config is not enabled"}
}
if l.ServerAddr == "" {
return Validation{
Result: ConnectivityError,
Detail: "Address is empty",
Suggestion: "Set a server address.",
}
}
conn, err := l.Connect()
if err != nil {
return Validation{
Result: ConnectivityError,
Detail: fmt.Sprintf("Could not connect to LDAP server: %v", err),
ErrCause: err,
Suggestion: `Check:
(1) server address
(2) TLS parameters, and
(3) LDAP server's TLS certificate is trusted by MinIO (when using TLS - highly recommended)`,
}
}
defer conn.Close()
if l.LookupBindDN == "" {
return Validation{
Result: LookupBindError,
Detail: "Lookup Bind UserDN not specified",
Suggestion: "Specify LDAP service account credentials for performing lookups.",
}
}
if err := l.lookupBind(conn); err != nil {
return Validation{
Result: LookupBindError,
ErrCause: err,
Detail: fmt.Sprintf("Error connecting as LDAP Lookup Bind user: %v", err),
Suggestion: "Check LDAP Lookup Bind user credentials and if user is allowed to login",
}
}
// Validate User Lookup parameters
if l.UserDNSearchBaseDistName == "" {
return Validation{
Result: UserSearchParamsMisconfigured,
Detail: "UserDN search base is empty",
Suggestion: "Set the UserDN search base to the DN of the directory subtree where users are present",
}
}
l.UserDNSearchBaseDistNames = strings.Split(l.UserDNSearchBaseDistName, dnDelimiter)
if l.UserDNSearchFilter == "" {
return Validation{
Result: UserSearchParamsMisconfigured,
Detail: "UserDN search filter is empty",
Suggestion: `Set the UserDN search filter template:
Use "%s" - it will be replaced by the login user name and sent to the LDAP server.
For example: "(uid=%s)"`,
}
}
if strings.Contains(l.UserDNSearchFilter, "%d") {
return Validation{
Result: UserSearchParamsMisconfigured,
Detail: "User DN search filter contains `%d`",
Suggestion: `User DN search filter is a template where "%s" is replaced by the login username.
"%d" is not supported here.
Please provide a search filter containing "%s"`,
}
}
if !strings.Contains(l.UserDNSearchFilter, "%s") {
return Validation{
Result: UserSearchParamsMisconfigured,
Detail: "User DN search filter does not contain `%s`",
Suggestion: `During login, the user's DN is looked up using the search filter template:
"%s" gets replaced by the given username - it must be used.
Enter an LDAP search filter containing "%s"`,
}
}
// If group lookup is not configured, it's ok.
if l.GroupSearchBaseDistName != "" || l.GroupSearchFilter != "" {
// Validate Group Search parameters as they are given.
if l.GroupSearchBaseDistName == "" {
return Validation{
Result: GroupSearchParamsMisconfigured,
Detail: "Group Search Base DN is required.",
Suggestion: `Since you entered a value for the Group Search Filter - enter a value for the Group Search Base DN too:
Enter this value as the DN of the subtree where groups will be found.`,
}
}
l.GroupSearchBaseDistNames = strings.Split(l.GroupSearchBaseDistName, dnDelimiter)
if l.GroupSearchFilter == "" {
return Validation{
Result: GroupSearchParamsMisconfigured,
Detail: "Group Search Filter is required.",
Suggestion: `Since you entered a value for the Group Search Base DN - enter a value for the Group Search Filter too. This is a template where, before the query is sent to the server:
"%s" is replaced with the login username;
"%d" is replaced with the DN of the login user.
For example: "(&(objectclass=groupOfNames)(memberUid=%s))"`,
}
}
if !strings.Contains(l.GroupSearchFilter, "%d") && !strings.Contains(l.GroupSearchFilter, "%s") {
return Validation{
Result: GroupSearchParamsMisconfigured,
Detail: `GroupSearchFilter must contain at least one of "%s" or "%d"`,
Suggestion: `During group membership lookup the group search filter template is used:
"%s" gets replaced by the given username, and
"%d" gets replaced by the user's DN.
Either one is needed to find only groups that the user is a member of.
Enter an LDAP search filter template using at least one of these.`,
}
}
}
return Validation{
Result: ConfigOk,
}
}
// ValidateLookup takes a test username and performs user and group lookup (if
// configured) and returns the result. It is to validate the LDAP configuration.
// The lookup is performed without requiring the password for the test user -
// and so can be used to test any LDAP user intending to use MinIO.
func (l *Config) ValidateLookup(testUsername string) (*UserLookupResult, Validation) {
if testUsername == "" {
return nil, Validation{
Result: UserDNLookupError,
Detail: "Provided username is empty",
}
}
if r := l.Validate(); !r.IsOk() {
return nil, r
}
conn, err := l.Connect()
if err != nil {
return nil, Validation{
Result: ConnectivityError,
Detail: fmt.Sprintf("Could not connect to LDAP server: %v", err),
ErrCause: err,
Suggestion: `Check:
(1) server address
(2) TLS parameters, and
(3) LDAP server's TLS certificate is trusted by MinIO (when using TLS - highly recommended)`,
}
}
defer conn.Close()
if err := l.lookupBind(conn); err != nil {
return nil, Validation{
Result: LookupBindError,
ErrCause: err,
Detail: fmt.Sprintf("Error connecting as LDAP Lookup Bind user: %v", err),
Suggestion: "Check LDAP Lookup Bind user credentials and if user is allowed to login",
}
}
// Lookup the given username.
dn, err := l.lookupUserDN(conn, testUsername)
if err != nil {
return nil, Validation{
Result: UserDNLookupError,
Detail: fmt.Sprintf("Got an error when looking up user (%s) DN: %v", testUsername, err),
ErrCause: err,
Suggestion: `Check if this is a temporary error and try again.
Perhaps there is an error in the user search filter or user search base DN.`,
}
}
// Lookup groups.
groups, err := l.searchForUserGroups(conn, testUsername, dn)
if err != nil {
return nil, Validation{
Result: GroupMembershipsLookupError,
Detail: fmt.Sprintf("Got an error when looking up groups for user(=>%s, dn=>%s): %v", testUsername, dn, err),
ErrCause: err,
Suggestion: `Check if this is a temporary error and try again.
Perhaps there is an error in the group search filter or group search base DN.`,
}
}
return &UserLookupResult{
DN: dn,
GroupDNMemberships: groups,
}, Validation{
Result: ConfigOk,
Detail: "User lookup done.",
}
}

View File

@ -1,189 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package ldap
import (
"fmt"
"os"
"testing"
"github.com/minio/minio-go/v7/pkg/set"
)
const (
EnvTestLDAPServer = "LDAP_TEST_SERVER"
)
func TestConfigValidator(t *testing.T) {
ldapServer := os.Getenv(EnvTestLDAPServer)
if ldapServer == "" {
t.Skip()
}
testCases := []struct {
cfg Config
expectedResult Result
}{
{
cfg: func() Config {
v := Config{Enabled: true}
return v
}(),
expectedResult: ConnectivityError,
},
{
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
return v
}(),
expectedResult: ConnectivityError,
},
{
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
return v
}(),
expectedResult: LookupBindError,
},
{
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin1"
return v
}(),
expectedResult: LookupBindError,
},
{ // Case 4
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin"
return v
}(),
expectedResult: UserSearchParamsMisconfigured,
},
{
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin"
v.UserDNSearchFilter = "(uid=x)"
v.UserDNSearchBaseDistName = "dc=min,dc=io"
return v
}(),
expectedResult: UserSearchParamsMisconfigured,
},
{
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin"
v.UserDNSearchFilter = "(uid=%s)"
v.UserDNSearchBaseDistName = "dc=min,dc=io"
return v
}(),
expectedResult: ConfigOk,
},
{ // Case 7
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin"
v.UserDNSearchFilter = "(uid=%s)"
v.UserDNSearchBaseDistName = "dc=min,dc=io"
v.GroupSearchBaseDistName = "ou=swengg,dc=min,dc=io"
v.GroupSearchFilter = "(&(objectclass=groupofnames)(member=x))"
return v
}(),
expectedResult: GroupSearchParamsMisconfigured,
},
{
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin"
v.UserDNSearchFilter = "(uid=%s)"
v.UserDNSearchBaseDistName = "dc=min,dc=io"
v.GroupSearchFilter = "(&(objectclass=groupofnames)(member=x))"
return v
}(),
expectedResult: GroupSearchParamsMisconfigured,
},
{ // Case 9
cfg: func() Config {
v := Config{Enabled: true}
v.ServerAddr = ldapServer
v.serverInsecure = true
v.LookupBindDN = "cn=admin,dc=min,dc=io"
v.LookupBindPassword = "admin"
v.UserDNSearchFilter = "(uid=%s)"
v.UserDNSearchBaseDistName = "dc=min,dc=io"
v.GroupSearchBaseDistName = "ou=swengg,dc=min,dc=io"
v.GroupSearchFilter = "(&(objectclass=groupofnames)(member=%d))"
return v
}(),
expectedResult: ConfigOk,
},
}
expectedDN := "uid=dillon,ou=people,ou=swengg,dc=min,dc=io"
expectedGroups := set.CreateStringSet(
"cn=projecta,ou=groups,ou=swengg,dc=min,dc=io",
"cn=projectb,ou=groups,ou=swengg,dc=min,dc=io",
)
for i, test := range testCases {
result := test.cfg.Validate()
if result.Result != test.expectedResult {
fmt.Printf("Result: %#v\n", result)
t.Fatalf("Case %d: Got `%s` expected `%s`", i, result.Result, string(test.expectedResult))
}
if result.IsOk() {
lookupResult, validationResult := test.cfg.ValidateLookup("dillon")
if !validationResult.IsOk() {
t.Fatalf("Case %d: Got unexpected validation failure: %#v\n", i, validationResult)
}
if lookupResult.DN != expectedDN {
t.Fatalf("Case %d: Got unexpected DN: %v", i, lookupResult.DN)
}
if test.cfg.GroupSearchFilter == "" {
continue
}
if !set.CreateStringSet(lookupResult.GroupDNMemberships...).Equals(expectedGroups) {
t.Fatalf("Case %d: Got unexpected groups: %v", i, lookupResult.GroupDNMemberships)
}
}
}
}

View File

@ -22,44 +22,26 @@ import (
"time" "time"
"github.com/minio/minio/internal/config" "github.com/minio/minio/internal/config"
"github.com/minio/pkg/env" "github.com/minio/pkg/ldap"
) )
const ( const (
defaultLDAPExpiry = time.Hour * 1 defaultLDAPExpiry = time.Hour * 1
dnDelimiter = ";"
minLDAPExpiry time.Duration = 15 * time.Minute minLDAPExpiry time.Duration = 15 * time.Minute
maxLDAPExpiry time.Duration = 365 * 24 * time.Hour maxLDAPExpiry time.Duration = 365 * 24 * time.Hour
) )
// Config contains AD/LDAP server connectivity information. // Config contains AD/LDAP server connectivity information.
type Config struct { type Config struct {
Enabled bool `json:"enabled"` LDAP ldap.Config
// E.g. "ldap.minio.io:636"
ServerAddr string `json:"serverAddr"`
// User DN search parameters
UserDNSearchBaseDistName string `json:"userDNSearchBaseDN"`
UserDNSearchBaseDistNames []string `json:"-"` // Generated field
UserDNSearchFilter string `json:"userDNSearchFilter"`
// Group search parameters
GroupSearchBaseDistName string `json:"groupSearchBaseDN"`
GroupSearchBaseDistNames []string `json:"-"` // Generated field
GroupSearchFilter string `json:"groupSearchFilter"`
// Lookup bind LDAP service account
LookupBindDN string `json:"lookupBindDN"`
LookupBindPassword string `json:"lookupBindPassword"`
stsExpiryDuration time.Duration // contains converted value stsExpiryDuration time.Duration // contains converted value
tlsSkipVerify bool // allows skipping TLS verification }
serverInsecure bool // allows plain text connection to LDAP server
serverStartTLS bool // allows using StartTLS connection to LDAP server // Enabled returns if LDAP is enabled.
rootCAs *x509.CertPool func (l *Config) Enabled() bool {
return l.LDAP.Enabled
} }
// Clone returns a cloned copy of LDAP config. // Clone returns a cloned copy of LDAP config.
@ -68,21 +50,8 @@ func (l *Config) Clone() Config {
return Config{} return Config{}
} }
cfg := Config{ cfg := Config{
Enabled: l.Enabled, LDAP: l.LDAP.Clone(),
ServerAddr: l.ServerAddr,
UserDNSearchBaseDistName: l.UserDNSearchBaseDistName,
UserDNSearchBaseDistNames: l.UserDNSearchBaseDistNames,
UserDNSearchFilter: l.UserDNSearchFilter,
GroupSearchBaseDistName: l.GroupSearchBaseDistName,
GroupSearchBaseDistNames: l.GroupSearchBaseDistNames,
GroupSearchFilter: l.GroupSearchFilter,
LookupBindDN: l.LookupBindDN,
LookupBindPassword: l.LookupBindPassword,
stsExpiryDuration: l.stsExpiryDuration, stsExpiryDuration: l.stsExpiryDuration,
tlsSkipVerify: l.tlsSkipVerify,
serverInsecure: l.serverInsecure,
serverStartTLS: l.serverStartTLS,
rootCAs: l.rootCAs,
} }
return cfg return cfg
} }
@ -173,61 +142,74 @@ func Enabled(kvs config.KVS) bool {
} }
// Lookup - initializes LDAP config, overrides config, if any ENV values are set. // Lookup - initializes LDAP config, overrides config, if any ENV values are set.
func Lookup(kvs config.KVS, rootCAs *x509.CertPool) (l Config, err error) { func Lookup(s config.Config, rootCAs *x509.CertPool) (l Config, err error) {
l = Config{} l = Config{}
// Purge all removed keys first // Purge all removed keys first
kvs := s[config.IdentityLDAPSubSys][config.Default]
if len(kvs) > 0 {
for _, k := range removedKeys { for _, k := range removedKeys {
kvs.Delete(k) kvs.Delete(k)
} }
s[config.IdentityLDAPSubSys][config.Default] = kvs
}
if err = config.CheckValidKeys(config.IdentityLDAPSubSys, kvs, DefaultKVS); err != nil { if err := s.CheckValidKeys(config.IdentityLDAPSubSys, removedKeys); err != nil {
return l, err return l, err
} }
ldapServer := env.Get(EnvServerAddr, kvs.Get(ServerAddr)) getCfgVal := func(cfgParam string) string {
// As parameters are already validated, we skip checking
// if the config param was found.
val, _ := s.ResolveConfigParam(config.IdentityLDAPSubSys, config.Default, cfgParam)
return val
}
ldapServer := getCfgVal(ServerAddr)
if ldapServer == "" { if ldapServer == "" {
return l, nil return l, nil
} }
l.Enabled = true l.LDAP = ldap.Config{
l.rootCAs = rootCAs Enabled: true,
l.ServerAddr = ldapServer RootCAs: rootCAs,
ServerAddr: ldapServer,
}
l.stsExpiryDuration = defaultLDAPExpiry l.stsExpiryDuration = defaultLDAPExpiry
// LDAP connection configuration // LDAP connection configuration
if v := env.Get(EnvServerInsecure, kvs.Get(ServerInsecure)); v != "" { if v := getCfgVal(ServerInsecure); v != "" {
l.serverInsecure, err = config.ParseBool(v) l.LDAP.ServerInsecure, err = config.ParseBool(v)
if err != nil { if err != nil {
return l, err return l, err
} }
} }
if v := env.Get(EnvServerStartTLS, kvs.Get(ServerStartTLS)); v != "" { if v := getCfgVal(ServerStartTLS); v != "" {
l.serverStartTLS, err = config.ParseBool(v) l.LDAP.ServerStartTLS, err = config.ParseBool(v)
if err != nil { if err != nil {
return l, err return l, err
} }
} }
if v := env.Get(EnvTLSSkipVerify, kvs.Get(TLSSkipVerify)); v != "" { if v := getCfgVal(TLSSkipVerify); v != "" {
l.tlsSkipVerify, err = config.ParseBool(v) l.LDAP.TLSSkipVerify, err = config.ParseBool(v)
if err != nil { if err != nil {
return l, err return l, err
} }
} }
// Lookup bind user configuration // Lookup bind user configuration
l.LookupBindDN = env.Get(EnvLookupBindDN, kvs.Get(LookupBindDN)) l.LDAP.LookupBindDN = getCfgVal(LookupBindDN)
l.LookupBindPassword = env.Get(EnvLookupBindPassword, kvs.Get(LookupBindPassword)) l.LDAP.LookupBindPassword = getCfgVal(LookupBindPassword)
// User DN search configuration // User DN search configuration
l.UserDNSearchFilter = env.Get(EnvUserDNSearchFilter, kvs.Get(UserDNSearchFilter)) l.LDAP.UserDNSearchFilter = getCfgVal(UserDNSearchFilter)
l.UserDNSearchBaseDistName = env.Get(EnvUserDNSearchBaseDN, kvs.Get(UserDNSearchBaseDN)) l.LDAP.UserDNSearchBaseDistName = getCfgVal(UserDNSearchBaseDN)
// Group search params configuration // Group search params configuration
l.GroupSearchFilter = env.Get(EnvGroupSearchFilter, kvs.Get(GroupSearchFilter)) l.LDAP.GroupSearchFilter = getCfgVal(GroupSearchFilter)
l.GroupSearchBaseDistName = env.Get(EnvGroupSearchBaseDN, kvs.Get(GroupSearchBaseDN)) l.LDAP.GroupSearchBaseDistName = getCfgVal(GroupSearchBaseDN)
// Validate and test configuration. // Validate and test configuration.
valResult := l.Validate() valResult := l.LDAP.Validate()
if !valResult.IsOk() { if !valResult.IsOk() {
return l, valResult return l, valResult
} }

View File

@ -18,10 +18,7 @@
package ldap package ldap
import ( import (
"crypto/tls"
"errors"
"fmt" "fmt"
"net"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -31,121 +28,27 @@ import (
"github.com/minio/minio/internal/auth" "github.com/minio/minio/internal/auth"
) )
func getGroups(conn *ldap.Conn, sreq *ldap.SearchRequest) ([]string, error) {
var groups []string
sres, err := conn.Search(sreq)
if err != nil {
// Check if there is no matching result and return empty slice.
// Ref: https://ldap.com/ldap-result-code-reference/
if ldap.IsErrorWithCode(err, 32) {
return nil, nil
}
return nil, err
}
for _, entry := range sres.Entries {
// We only queried one attribute,
// so we only look up the first one.
groups = append(groups, entry.DN)
}
return groups, nil
}
func (l *Config) lookupBind(conn *ldap.Conn) error {
var err error
if l.LookupBindPassword == "" {
err = conn.UnauthenticatedBind(l.LookupBindDN)
} else {
err = conn.Bind(l.LookupBindDN, l.LookupBindPassword)
}
if ldap.IsErrorWithCode(err, 49) {
return fmt.Errorf("LDAP Lookup Bind user invalid credentials error: %w", err)
}
return err
}
// lookupUserDN searches for the DN of the user given their username. conn is
// assumed to be using the lookup bind service account. It is required that the
// search result in at most one result.
func (l *Config) lookupUserDN(conn *ldap.Conn, username string) (string, error) {
filter := strings.ReplaceAll(l.UserDNSearchFilter, "%s", ldap.EscapeFilter(username))
var foundDistNames []string
for _, userSearchBase := range l.UserDNSearchBaseDistNames {
searchRequest := ldap.NewSearchRequest(
userSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
filter,
[]string{}, // only need DN, so no pass no attributes here
nil,
)
searchResult, err := conn.Search(searchRequest)
if err != nil {
return "", err
}
for _, entry := range searchResult.Entries {
foundDistNames = append(foundDistNames, entry.DN)
}
}
if len(foundDistNames) == 0 {
return "", fmt.Errorf("User DN for %s not found", username)
}
if len(foundDistNames) != 1 {
return "", fmt.Errorf("Multiple DNs for %s found - please fix the search filter", username)
}
return foundDistNames[0], nil
}
func (l *Config) searchForUserGroups(conn *ldap.Conn, username, bindDN string) ([]string, error) {
// User groups lookup.
var groups []string
if l.GroupSearchFilter != "" {
for _, groupSearchBase := range l.GroupSearchBaseDistNames {
filter := strings.ReplaceAll(l.GroupSearchFilter, "%s", ldap.EscapeFilter(username))
filter = strings.ReplaceAll(filter, "%d", ldap.EscapeFilter(bindDN))
searchRequest := ldap.NewSearchRequest(
groupSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
filter,
nil,
nil,
)
var newGroups []string
newGroups, err := getGroups(conn, searchRequest)
if err != nil {
errRet := fmt.Errorf("Error finding groups of %s: %w", bindDN, err)
return nil, errRet
}
groups = append(groups, newGroups...)
}
}
return groups, nil
}
// LookupUserDN searches for the full DN and groups of a given username // LookupUserDN searches for the full DN and groups of a given username
func (l *Config) LookupUserDN(username string) (string, []string, error) { func (l *Config) LookupUserDN(username string) (string, []string, error) {
conn, err := l.Connect() conn, err := l.LDAP.Connect()
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
defer conn.Close() defer conn.Close()
// Bind to the lookup user account // Bind to the lookup user account
if err = l.lookupBind(conn); err != nil { if err = l.LDAP.LookupBind(conn); err != nil {
return "", nil, err return "", nil, err
} }
// Lookup user DN // Lookup user DN
bindDN, err := l.lookupUserDN(conn, username) bindDN, err := l.LDAP.LookupUserDN(conn, username)
if err != nil { if err != nil {
errRet := fmt.Errorf("Unable to find user DN: %w", err) errRet := fmt.Errorf("Unable to find user DN: %w", err)
return "", nil, errRet return "", nil, errRet
} }
groups, err := l.searchForUserGroups(conn, username, bindDN) groups, err := l.LDAP.SearchForUserGroups(conn, username, bindDN)
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
@ -156,7 +59,7 @@ func (l *Config) LookupUserDN(username string) (string, []string, error) {
// Bind - binds to ldap, searches LDAP and returns the distinguished name of the // Bind - binds to ldap, searches LDAP and returns the distinguished name of the
// user and the list of groups. // user and the list of groups.
func (l *Config) Bind(username, password string) (string, []string, error) { func (l *Config) Bind(username, password string) (string, []string, error) {
conn, err := l.Connect() conn, err := l.LDAP.Connect()
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
@ -164,12 +67,12 @@ func (l *Config) Bind(username, password string) (string, []string, error) {
var bindDN string var bindDN string
// Bind to the lookup user account // Bind to the lookup user account
if err = l.lookupBind(conn); err != nil { if err = l.LDAP.LookupBind(conn); err != nil {
return "", nil, err return "", nil, err
} }
// Lookup user DN // Lookup user DN
bindDN, err = l.lookupUserDN(conn, username) bindDN, err = l.LDAP.LookupUserDN(conn, username)
if err != nil { if err != nil {
errRet := fmt.Errorf("Unable to find user DN: %w", err) errRet := fmt.Errorf("Unable to find user DN: %w", err)
return "", nil, errRet return "", nil, errRet
@ -183,12 +86,12 @@ func (l *Config) Bind(username, password string) (string, []string, error) {
} }
// Bind to the lookup user account again to perform group search. // Bind to the lookup user account again to perform group search.
if err = l.lookupBind(conn); err != nil { if err = l.LDAP.LookupBind(conn); err != nil {
return "", nil, err return "", nil, err
} }
// User groups lookup. // User groups lookup.
groups, err := l.searchForUserGroups(conn, username, bindDN) groups, err := l.LDAP.SearchForUserGroups(conn, username, bindDN)
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
@ -196,43 +99,6 @@ func (l *Config) Bind(username, password string) (string, []string, error) {
return bindDN, groups, nil return bindDN, groups, nil
} }
// Connect connect to ldap server.
func (l *Config) Connect() (ldapConn *ldap.Conn, err error) {
if l == nil {
return nil, errors.New("LDAP is not configured")
}
_, _, err = net.SplitHostPort(l.ServerAddr)
if err != nil {
// User default LDAP port if none specified "636"
l.ServerAddr = net.JoinHostPort(l.ServerAddr, "636")
}
tlsConfig := &tls.Config{
InsecureSkipVerify: l.tlsSkipVerify,
RootCAs: l.rootCAs,
}
if l.serverInsecure {
ldapConn, err = ldap.Dial("tcp", l.ServerAddr)
} else {
if l.serverStartTLS {
ldapConn, err = ldap.Dial("tcp", l.ServerAddr)
} else {
ldapConn, err = ldap.DialTLS("tcp", l.ServerAddr, tlsConfig)
}
}
if ldapConn != nil {
ldapConn.SetTimeout(30 * time.Second) // Change default timeout to 30 seconds.
if l.serverStartTLS {
err = ldapConn.StartTLS(tlsConfig)
}
}
return ldapConn, err
}
// GetExpiryDuration - return parsed expiry duration. // GetExpiryDuration - return parsed expiry duration.
func (l Config) GetExpiryDuration(dsecs string) (time.Duration, error) { func (l Config) GetExpiryDuration(dsecs string) (time.Duration, error) {
if dsecs == "" { if dsecs == "" {
@ -254,7 +120,7 @@ func (l Config) GetExpiryDuration(dsecs string) (time.Duration, error) {
// IsLDAPUserDN determines if the given string could be a user DN from LDAP. // IsLDAPUserDN determines if the given string could be a user DN from LDAP.
func (l Config) IsLDAPUserDN(user string) bool { func (l Config) IsLDAPUserDN(user string) bool {
for _, baseDN := range l.UserDNSearchBaseDistNames { for _, baseDN := range l.LDAP.UserDNSearchBaseDistNames {
if strings.HasSuffix(user, ","+baseDN) { if strings.HasSuffix(user, ","+baseDN) {
return true return true
} }
@ -265,19 +131,19 @@ func (l Config) IsLDAPUserDN(user string) bool {
// GetNonEligibleUserDistNames - find user accounts (DNs) that are no longer // GetNonEligibleUserDistNames - find user accounts (DNs) that are no longer
// present in the LDAP server or do not meet filter criteria anymore // present in the LDAP server or do not meet filter criteria anymore
func (l *Config) GetNonEligibleUserDistNames(userDistNames []string) ([]string, error) { func (l *Config) GetNonEligibleUserDistNames(userDistNames []string) ([]string, error) {
conn, err := l.Connect() conn, err := l.LDAP.Connect()
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer conn.Close() defer conn.Close()
// Bind to the lookup user account // Bind to the lookup user account
if err = l.lookupBind(conn); err != nil { if err = l.LDAP.LookupBind(conn); err != nil {
return nil, err return nil, err
} }
// Evaluate the filter again with generic wildcard instead of specific values // Evaluate the filter again with generic wildcard instead of specific values
filter := strings.ReplaceAll(l.UserDNSearchFilter, "%s", "*") filter := strings.ReplaceAll(l.LDAP.UserDNSearchFilter, "%s", "*")
nonExistentUsers := []string{} nonExistentUsers := []string{}
for _, dn := range userDistNames { for _, dn := range userDistNames {
@ -310,21 +176,21 @@ func (l *Config) GetNonEligibleUserDistNames(userDistNames []string) ([]string,
// LookupGroupMemberships - for each DN finds the set of LDAP groups they are a // LookupGroupMemberships - for each DN finds the set of LDAP groups they are a
// member of. // member of.
func (l *Config) LookupGroupMemberships(userDistNames []string, userDNToUsernameMap map[string]string) (map[string]set.StringSet, error) { func (l *Config) LookupGroupMemberships(userDistNames []string, userDNToUsernameMap map[string]string) (map[string]set.StringSet, error) {
conn, err := l.Connect() conn, err := l.LDAP.Connect()
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer conn.Close() defer conn.Close()
// Bind to the lookup user account // Bind to the lookup user account
if err = l.lookupBind(conn); err != nil { if err = l.LDAP.LookupBind(conn); err != nil {
return nil, err return nil, err
} }
res := make(map[string]set.StringSet, len(userDistNames)) res := make(map[string]set.StringSet, len(userDistNames))
for _, userDistName := range userDistNames { for _, userDistName := range userDistNames {
username := userDNToUsernameMap[userDistName] username := userDNToUsernameMap[userDistName]
groups, err := l.searchForUserGroups(conn, username, userDistName) groups, err := l.LDAP.SearchForUserGroups(conn, username, userDistName)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -17,10 +17,35 @@
package ldap package ldap
import "github.com/minio/minio/internal/config" import (
"github.com/minio/minio/internal/config"
)
// LegacyConfig contains AD/LDAP server connectivity information from old config
// V33.
type LegacyConfig struct {
Enabled bool `json:"enabled"`
// E.g. "ldap.minio.io:636"
ServerAddr string `json:"serverAddr"`
// User DN search parameters
UserDNSearchBaseDistName string `json:"userDNSearchBaseDN"`
UserDNSearchBaseDistNames []string `json:"-"` // Generated field
UserDNSearchFilter string `json:"userDNSearchFilter"`
// Group search parameters
GroupSearchBaseDistName string `json:"groupSearchBaseDN"`
GroupSearchBaseDistNames []string `json:"-"` // Generated field
GroupSearchFilter string `json:"groupSearchFilter"`
// Lookup bind LDAP service account
LookupBindDN string `json:"lookupBindDN"`
LookupBindPassword string `json:"lookupBindPassword"`
}
// SetIdentityLDAP - One time migration code needed, for migrating from older config to new for LDAPConfig. // SetIdentityLDAP - One time migration code needed, for migrating from older config to new for LDAPConfig.
func SetIdentityLDAP(s config.Config, ldapArgs Config) { func SetIdentityLDAP(s config.Config, ldapArgs LegacyConfig) {
if !ldapArgs.Enabled { if !ldapArgs.Enabled {
// ldap not enabled no need to preserve it in new settings. // ldap not enabled no need to preserve it in new settings.
return return