oidc.go 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright 2020 guylewin, guy@lewin.co.il
//
// 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 (
	"context"
	"fmt"

F
fatedier 已提交
21
	"github.com/fatedier/frp/pkg/msg"
22 23 24 25 26 27 28

	"github.com/coreos/go-oidc"
	"github.com/vaughan0/go-ini"
	"golang.org/x/oauth2/clientcredentials"
)

type oidcClientConfig struct {
F
fatedier 已提交
29
	// OidcClientID specifies the client ID to use to get a token in OIDC
30 31
	// authentication if AuthenticationMethod == "oidc". By default, this value
	// is "".
F
fatedier 已提交
32
	OidcClientID string `json:"oidc_client_id"`
33 34 35 36 37 38 39
	// OidcClientSecret specifies the client secret to use to get a token in OIDC
	// authentication if AuthenticationMethod == "oidc". By default, this value
	// is "".
	OidcClientSecret string `json:"oidc_client_secret"`
	// OidcAudience specifies the audience of the token in OIDC authentication
	//if AuthenticationMethod == "oidc". By default, this value is "".
	OidcAudience string `json:"oidc_audience"`
F
fatedier 已提交
40
	// OidcTokenEndpointURL specifies the URL which implements OIDC Token Endpoint.
41 42
	// It will be used to get an OIDC token if AuthenticationMethod == "oidc".
	// By default, this value is "".
F
fatedier 已提交
43
	OidcTokenEndpointURL string `json:"oidc_token_endpoint_url"`
44 45 46 47
}

func getDefaultOidcClientConf() oidcClientConfig {
	return oidcClientConfig{
F
fatedier 已提交
48
		OidcClientID:         "",
49 50
		OidcClientSecret:     "",
		OidcAudience:         "",
F
fatedier 已提交
51
		OidcTokenEndpointURL: "",
52 53 54 55 56 57 58 59 60 61 62 63
	}
}

func unmarshalOidcClientConfFromIni(conf ini.File) oidcClientConfig {
	var (
		tmpStr string
		ok     bool
	)

	cfg := getDefaultOidcClientConf()

	if tmpStr, ok = conf.Get("common", "oidc_client_id"); ok {
F
fatedier 已提交
64
		cfg.OidcClientID = tmpStr
65 66 67 68 69 70 71 72 73 74 75
	}

	if tmpStr, ok = conf.Get("common", "oidc_client_secret"); ok {
		cfg.OidcClientSecret = tmpStr
	}

	if tmpStr, ok = conf.Get("common", "oidc_audience"); ok {
		cfg.OidcAudience = tmpStr
	}

	if tmpStr, ok = conf.Get("common", "oidc_token_endpoint_url"); ok {
F
fatedier 已提交
76
		cfg.OidcTokenEndpointURL = tmpStr
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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
	}

	return cfg
}

type oidcServerConfig struct {
	// OidcIssuer specifies the issuer to verify OIDC tokens with. This issuer
	// will be used to load public keys to verify signature and will be compared
	// with the issuer claim in the OIDC token. It will be used if
	// AuthenticationMethod == "oidc". By default, this value is "".
	OidcIssuer string `json:"oidc_issuer"`
	// OidcAudience specifies the audience OIDC tokens should contain when validated.
	// If this value is empty, audience ("client ID") verification will be skipped.
	// It will be used when AuthenticationMethod == "oidc". By default, this
	// value is "".
	OidcAudience string `json:"oidc_audience"`
	// OidcSkipExpiryCheck specifies whether to skip checking if the OIDC token is
	// expired. It will be used when AuthenticationMethod == "oidc". By default, this
	// value is false.
	OidcSkipExpiryCheck bool `json:"oidc_skip_expiry_check"`
	// OidcSkipIssuerCheck specifies whether to skip checking if the OIDC token's
	// issuer claim matches the issuer specified in OidcIssuer. It will be used when
	// AuthenticationMethod == "oidc". By default, this value is false.
	OidcSkipIssuerCheck bool `json:"oidc_skip_issuer_check"`
}

func getDefaultOidcServerConf() oidcServerConfig {
	return oidcServerConfig{
		OidcIssuer:          "",
		OidcAudience:        "",
		OidcSkipExpiryCheck: false,
		OidcSkipIssuerCheck: false,
	}
}

func unmarshalOidcServerConfFromIni(conf ini.File) oidcServerConfig {
	var (
		tmpStr string
		ok     bool
	)

	cfg := getDefaultOidcServerConf()

	if tmpStr, ok = conf.Get("common", "oidc_issuer"); ok {
		cfg.OidcIssuer = tmpStr
	}

	if tmpStr, ok = conf.Get("common", "oidc_audience"); ok {
		cfg.OidcAudience = tmpStr
	}

	if tmpStr, ok = conf.Get("common", "oidc_skip_expiry_check"); ok && tmpStr == "true" {
		cfg.OidcSkipExpiryCheck = true
	} else {
		cfg.OidcSkipExpiryCheck = false
	}

	if tmpStr, ok = conf.Get("common", "oidc_skip_issuer_check"); ok && tmpStr == "true" {
		cfg.OidcSkipIssuerCheck = true
	} else {
		cfg.OidcSkipIssuerCheck = false
	}

	return cfg
}

type OidcAuthProvider struct {
	baseConfig

	tokenGenerator *clientcredentials.Config
}

func NewOidcAuthSetter(baseCfg baseConfig, cfg oidcClientConfig) *OidcAuthProvider {
	tokenGenerator := &clientcredentials.Config{
F
fatedier 已提交
151
		ClientID:     cfg.OidcClientID,
152 153
		ClientSecret: cfg.OidcClientSecret,
		Scopes:       []string{cfg.OidcAudience},
F
fatedier 已提交
154
		TokenURL:     cfg.OidcTokenEndpointURL,
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 189 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
	}

	return &OidcAuthProvider{
		baseConfig:     baseCfg,
		tokenGenerator: tokenGenerator,
	}
}

func (auth *OidcAuthProvider) generateAccessToken() (accessToken string, err error) {
	tokenObj, err := auth.tokenGenerator.Token(context.Background())
	if err != nil {
		return "", fmt.Errorf("couldn't generate OIDC token for login: %v", err)
	}
	return tokenObj.AccessToken, nil
}

func (auth *OidcAuthProvider) SetLogin(loginMsg *msg.Login) (err error) {
	loginMsg.PrivilegeKey, err = auth.generateAccessToken()
	return err
}

func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) {
	if !auth.AuthenticateHeartBeats {
		return nil
	}

	pingMsg.PrivilegeKey, err = auth.generateAccessToken()
	return err
}

func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
	if !auth.AuthenticateNewWorkConns {
		return nil
	}

	newWorkConnMsg.PrivilegeKey, err = auth.generateAccessToken()
	return err
}

type OidcAuthConsumer struct {
	baseConfig

	verifier         *oidc.IDTokenVerifier
	subjectFromLogin string
}

func NewOidcAuthVerifier(baseCfg baseConfig, cfg oidcServerConfig) *OidcAuthConsumer {
	provider, err := oidc.NewProvider(context.Background(), cfg.OidcIssuer)
	if err != nil {
		panic(err)
	}
	verifierConf := oidc.Config{
		ClientID:          cfg.OidcAudience,
		SkipClientIDCheck: cfg.OidcAudience == "",
		SkipExpiryCheck:   cfg.OidcSkipExpiryCheck,
		SkipIssuerCheck:   cfg.OidcSkipIssuerCheck,
	}
	return &OidcAuthConsumer{
		baseConfig: baseCfg,
		verifier:   provider.Verifier(&verifierConf),
	}
}

func (auth *OidcAuthConsumer) VerifyLogin(loginMsg *msg.Login) (err error) {
	token, err := auth.verifier.Verify(context.Background(), loginMsg.PrivilegeKey)
	if err != nil {
		return fmt.Errorf("invalid OIDC token in login: %v", err)
	}
	auth.subjectFromLogin = token.Subject
	return nil
}

func (auth *OidcAuthConsumer) verifyPostLoginToken(privilegeKey string) (err error) {
	token, err := auth.verifier.Verify(context.Background(), privilegeKey)
	if err != nil {
		return fmt.Errorf("invalid OIDC token in ping: %v", err)
	}
	if token.Subject != auth.subjectFromLogin {
		return fmt.Errorf("received different OIDC subject in login and ping. "+
			"original subject: %s, "+
			"new subject: %s",
			auth.subjectFromLogin, token.Subject)
	}
	return nil
}

func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) {
	if !auth.AuthenticateHeartBeats {
		return nil
	}

	return auth.verifyPostLoginToken(pingMsg.PrivilegeKey)
}

func (auth *OidcAuthConsumer) VerifyNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
	if !auth.AuthenticateNewWorkConns {
		return nil
	}

	return auth.verifyPostLoginToken(newWorkConnMsg.PrivilegeKey)
}