authenticator.go 8.3 KB
Newer Older
H
hongming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*

 Copyright 2020 The KubeSphere Authors.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

*/

package auth

import (
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider"
H
hongming 已提交
25
	informers "kubesphere.io/kubesphere/pkg/client/informers/externalversions"
H
hongming 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
	"kubesphere.io/kubesphere/pkg/constants"
	"net/mail"

	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	authuser "k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/klog"
	iamv1alpha2 "kubesphere.io/kubesphere/pkg/apis/iam/v1alpha2"
	"kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"
	authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
	kubesphere "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
	iamv1alpha2listers "kubesphere.io/kubesphere/pkg/client/listers/iam/v1alpha2"
)

var (
	RateLimitExceededError  = fmt.Errorf("auth rate limit exceeded")
	IncorrectPasswordError  = fmt.Errorf("incorrect password")
	AccountIsNotActiveError = fmt.Errorf("account is not active")
)

type PasswordAuthenticator interface {
	Authenticate(username, password string) (authuser.Info, string, error)
}

H
hongming 已提交
50
type OAuthAuthenticator interface {
H
hongming 已提交
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
	Authenticate(provider, code string) (authuser.Info, string, error)
}

type passwordAuthenticator struct {
	ksClient    kubesphere.Interface
	userGetter  *userGetter
	authOptions *authoptions.AuthenticationOptions
}

type oauth2Authenticator struct {
	ksClient    kubesphere.Interface
	userGetter  *userGetter
	authOptions *authoptions.AuthenticationOptions
}

type userGetter struct {
	userLister iamv1alpha2listers.UserLister
}

func NewPasswordAuthenticator(ksClient kubesphere.Interface,
	userLister iamv1alpha2listers.UserLister,
	options *authoptions.AuthenticationOptions) PasswordAuthenticator {
	passwordAuthenticator := &passwordAuthenticator{
		ksClient:    ksClient,
		userGetter:  &userGetter{userLister: userLister},
		authOptions: options,
	}
	return passwordAuthenticator
}

H
hongming 已提交
81 82 83
func NewOAuthAuthenticator(ksClient kubesphere.Interface,
	ksInformer informers.SharedInformerFactory,
	options *authoptions.AuthenticationOptions) OAuthAuthenticator {
H
hongming 已提交
84 85
	oauth2Authenticator := &oauth2Authenticator{
		ksClient:    ksClient,
H
hongming 已提交
86
		userGetter:  &userGetter{userLister: ksInformer.Iam().V1alpha2().Users().Lister()},
H
hongming 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
		authOptions: options,
	}
	return oauth2Authenticator
}

func (p *passwordAuthenticator) Authenticate(username, password string) (authuser.Info, string, error) {
	// empty username or password are not allowed
	if username == "" || password == "" {
		return nil, "", IncorrectPasswordError
	}
	// generic identity provider has higher priority
	for _, providerOptions := range p.authOptions.OAuthOptions.IdentityProviders {
		// the admin account in kubesphere has the highest priority
		if username == constants.AdminUserName {
			break
		}
H
hongming 已提交
103
		if genericProvider, _ := identityprovider.GetGenericProvider(providerOptions.Name); genericProvider != nil {
H
hongming 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
			authenticated, err := genericProvider.Authenticate(username, password)
			if err != nil {
				if errors.IsUnauthorized(err) {
					continue
				}
				return nil, providerOptions.Name, err
			}
			linkedAccount, err := p.userGetter.findLinkedAccount(providerOptions.Name, authenticated.GetUserID())
			// using this method requires you to manually provision users.
			if providerOptions.MappingMethod == oauth.MappingMethodLookup && linkedAccount == nil {
				continue
			}
			if linkedAccount != nil {
				return &authuser.DefaultInfo{Name: linkedAccount.GetName()}, providerOptions.Name, nil
			}
			// the user will automatically create and mapping when login successful.
			if providerOptions.MappingMethod == oauth.MappingMethodAuto {
				return preRegistrationUser(providerOptions.Name, authenticated), providerOptions.Name, nil
			}
		}
	}

	// kubesphere account
	user, err := p.userGetter.findUser(username)
	if err != nil {
		// ignore not found error
		if !errors.IsNotFound(err) {
			klog.Error(err)
			return nil, "", err
		}
	}

	// check user status
	if user != nil && (user.Status.State == nil || *user.Status.State != iamv1alpha2.UserActive) {
		if user.Status.State != nil && *user.Status.State == iamv1alpha2.UserAuthLimitExceeded {
			klog.Errorf("%s, username: %s", RateLimitExceededError, username)
			return nil, "", RateLimitExceededError
		} else {
			// state not active
			klog.Errorf("%s, username: %s", AccountIsNotActiveError, username)
			return nil, "", AccountIsNotActiveError
		}
	}

	// if the password is not empty, means that the password has been reset, even if the user was mapping from IDP
	if user != nil && user.Spec.EncryptedPassword != "" {
		if err = PasswordVerify(user.Spec.EncryptedPassword, password); err != nil {
			klog.Error(err)
			return nil, "", err
		}
		u := &authuser.DefaultInfo{
			Name: user.Name,
		}
		// check if the password is initialized
		if uninitialized := user.Annotations[iamv1alpha2.UninitializedAnnotation]; uninitialized != "" {
			u.Extra = map[string][]string{
				iamv1alpha2.ExtraUninitialized: {uninitialized},
			}
		}
		return u, "", nil
	}

	return nil, "", IncorrectPasswordError
}

func preRegistrationUser(idp string, identity identityprovider.Identity) authuser.Info {
	return &authuser.DefaultInfo{
		Name: iamv1alpha2.PreRegistrationUser,
		Extra: map[string][]string{
			iamv1alpha2.ExtraIdentityProvider: {idp},
			iamv1alpha2.ExtraUID:              {identity.GetUserID()},
			iamv1alpha2.ExtraUsername:         {identity.GetUsername()},
			iamv1alpha2.ExtraEmail:            {identity.GetEmail()},
		},
		Groups: []string{iamv1alpha2.PreRegistrationUserGroup},
	}
}

func (o oauth2Authenticator) Authenticate(provider, code string) (authuser.Info, string, error) {
	providerOptions, err := o.authOptions.OAuthOptions.IdentityProviderOptions(provider)
	// identity provider not registered
	if err != nil {
		klog.Error(err)
		return nil, "", err
	}
H
hongming 已提交
189
	oauthIdentityProvider, err := identityprovider.GetOAuthProvider(providerOptions.Name)
H
hongming 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
	if err != nil {
		klog.Error(err)
		return nil, "", err
	}
	authenticated, err := oauthIdentityProvider.IdentityExchange(code)
	if err != nil {
		klog.Error(err)
		return nil, "", err
	}

	user, err := o.userGetter.findLinkedAccount(providerOptions.Name, authenticated.GetUserID())
	if user == nil && providerOptions.MappingMethod == oauth.MappingMethodLookup {
		klog.Error(err)
		return nil, "", err
	}
	// the user will automatically create and mapping when login successful.
	if user == nil && providerOptions.MappingMethod == oauth.MappingMethodAuto {
		return preRegistrationUser(providerOptions.Name, authenticated), providerOptions.Name, nil
	}
	if user != nil {
		return &authuser.DefaultInfo{Name: user.GetName()}, providerOptions.Name, nil
	}

	return nil, "", errors.NewNotFound(iamv1alpha2.Resource("user"), authenticated.GetUsername())
}

func PasswordVerify(encryptedPassword, password string) error {
	if err := bcrypt.CompareHashAndPassword([]byte(encryptedPassword), []byte(password)); err != nil {
		return IncorrectPasswordError
	}
	return nil
}

// findUser
func (u *userGetter) findUser(username string) (*iamv1alpha2.User, error) {
	if _, err := mail.ParseAddress(username); err != nil {
		return u.userLister.Get(username)
	} else {
		users, err := u.userLister.List(labels.Everything())
		if err != nil {
			klog.Error(err)
			return nil, err
		}
		for _, find := range users {
			if find.Spec.Email == username {
				return find, nil
			}
		}
	}

	return nil, errors.NewNotFound(iamv1alpha2.Resource("user"), username)
}

func (u *userGetter) findLinkedAccount(idp, uid string) (*iamv1alpha2.User, error) {
	selector := labels.SelectorFromSet(labels.Set{
		iamv1alpha2.IdentifyProviderLabel: idp,
		iamv1alpha2.OriginUIDLabel:        uid,
	})

	users, err := u.userLister.List(selector)
	if err != nil {
		klog.Error(err)
		return nil, err
	}
	if len(users) != 1 {
		return nil, errors.NewNotFound(iamv1alpha2.Resource("user"), uid)
	}

	return users[0], err
}