oidc.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Copyright 2020 guylewin, guy@lewin.co.il
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package auth
  15. import (
  16. "context"
  17. "fmt"
  18. "github.com/coreos/go-oidc"
  19. "golang.org/x/oauth2/clientcredentials"
  20. "github.com/fatedier/frp/pkg/msg"
  21. )
  22. type OidcClientConfig struct {
  23. // OidcClientID specifies the client ID to use to get a token in OIDC
  24. // authentication if AuthenticationMethod == "oidc". By default, this value
  25. // is "".
  26. OidcClientID string `ini:"oidc_client_id" json:"oidc_client_id"`
  27. // OidcClientSecret specifies the client secret to use to get a token in OIDC
  28. // authentication if AuthenticationMethod == "oidc". By default, this value
  29. // is "".
  30. OidcClientSecret string `ini:"oidc_client_secret" json:"oidc_client_secret"`
  31. // OidcAudience specifies the audience of the token in OIDC authentication
  32. // if AuthenticationMethod == "oidc". By default, this value is "".
  33. OidcAudience string `ini:"oidc_audience" json:"oidc_audience"`
  34. // OidcScope specifies the scope of the token in OIDC authentication
  35. // if AuthenticationMethod == "oidc". By default, this value is "".
  36. OidcScope string `ini:"oidc_scope" json:"oidc_scope"`
  37. // OidcTokenEndpointURL specifies the URL which implements OIDC Token Endpoint.
  38. // It will be used to get an OIDC token if AuthenticationMethod == "oidc".
  39. // By default, this value is "".
  40. OidcTokenEndpointURL string `ini:"oidc_token_endpoint_url" json:"oidc_token_endpoint_url"`
  41. // OidcAdditionalEndpointParams specifies additional parameters to be sent
  42. // this field will be transfer to map[string][]string in OIDC token generator
  43. // The field will be set by prefix "oidc_additional_"
  44. OidcAdditionalEndpointParams map[string]string `ini:"-" json:"oidc_additional_endpoint_params"`
  45. }
  46. func getDefaultOidcClientConf() OidcClientConfig {
  47. return OidcClientConfig{
  48. OidcClientID: "",
  49. OidcClientSecret: "",
  50. OidcAudience: "",
  51. OidcScope: "",
  52. OidcTokenEndpointURL: "",
  53. OidcAdditionalEndpointParams: make(map[string]string),
  54. }
  55. }
  56. type OidcServerConfig struct {
  57. // OidcIssuer specifies the issuer to verify OIDC tokens with. This issuer
  58. // will be used to load public keys to verify signature and will be compared
  59. // with the issuer claim in the OIDC token. It will be used if
  60. // AuthenticationMethod == "oidc". By default, this value is "".
  61. OidcIssuer string `ini:"oidc_issuer" json:"oidc_issuer"`
  62. // OidcAudience specifies the audience OIDC tokens should contain when validated.
  63. // If this value is empty, audience ("client ID") verification will be skipped.
  64. // It will be used when AuthenticationMethod == "oidc". By default, this
  65. // value is "".
  66. OidcAudience string `ini:"oidc_audience" json:"oidc_audience"`
  67. // OidcSkipExpiryCheck specifies whether to skip checking if the OIDC token is
  68. // expired. It will be used when AuthenticationMethod == "oidc". By default, this
  69. // value is false.
  70. OidcSkipExpiryCheck bool `ini:"oidc_skip_expiry_check" json:"oidc_skip_expiry_check"`
  71. // OidcSkipIssuerCheck specifies whether to skip checking if the OIDC token's
  72. // issuer claim matches the issuer specified in OidcIssuer. It will be used when
  73. // AuthenticationMethod == "oidc". By default, this value is false.
  74. OidcSkipIssuerCheck bool `ini:"oidc_skip_issuer_check" json:"oidc_skip_issuer_check"`
  75. }
  76. func getDefaultOidcServerConf() OidcServerConfig {
  77. return OidcServerConfig{
  78. OidcIssuer: "",
  79. OidcAudience: "",
  80. OidcSkipExpiryCheck: false,
  81. OidcSkipIssuerCheck: false,
  82. }
  83. }
  84. type OidcAuthProvider struct {
  85. BaseConfig
  86. tokenGenerator *clientcredentials.Config
  87. }
  88. func NewOidcAuthSetter(baseCfg BaseConfig, cfg OidcClientConfig) *OidcAuthProvider {
  89. eps := make(map[string][]string)
  90. for k, v := range cfg.OidcAdditionalEndpointParams {
  91. eps[k] = []string{v}
  92. }
  93. // Previous versions hardcoded the scope to audience,
  94. // so for backwards compatibility, use that if no scope is set
  95. scope := cfg.OidcAudience
  96. if cfg.OidcScope != "" {
  97. scope = cfg.OidcScope
  98. }
  99. tokenGenerator := &clientcredentials.Config{
  100. ClientID: cfg.OidcClientID,
  101. ClientSecret: cfg.OidcClientSecret,
  102. Scopes: []string{scope},
  103. TokenURL: cfg.OidcTokenEndpointURL,
  104. EndpointParams: eps,
  105. }
  106. return &OidcAuthProvider{
  107. BaseConfig: baseCfg,
  108. tokenGenerator: tokenGenerator,
  109. }
  110. }
  111. func (auth *OidcAuthProvider) generateAccessToken() (accessToken string, err error) {
  112. tokenObj, err := auth.tokenGenerator.Token(context.Background())
  113. if err != nil {
  114. return "", fmt.Errorf("couldn't generate OIDC token for login: %v", err)
  115. }
  116. return tokenObj.AccessToken, nil
  117. }
  118. func (auth *OidcAuthProvider) SetLogin(loginMsg *msg.Login) (err error) {
  119. loginMsg.PrivilegeKey, err = auth.generateAccessToken()
  120. return err
  121. }
  122. func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) {
  123. if !auth.AuthenticateHeartBeats {
  124. return nil
  125. }
  126. pingMsg.PrivilegeKey, err = auth.generateAccessToken()
  127. return err
  128. }
  129. func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
  130. if !auth.AuthenticateNewWorkConns {
  131. return nil
  132. }
  133. newWorkConnMsg.PrivilegeKey, err = auth.generateAccessToken()
  134. return err
  135. }
  136. type OidcAuthConsumer struct {
  137. BaseConfig
  138. verifier *oidc.IDTokenVerifier
  139. subjectFromLogin string
  140. }
  141. func NewOidcAuthVerifier(baseCfg BaseConfig, cfg OidcServerConfig) *OidcAuthConsumer {
  142. provider, err := oidc.NewProvider(context.Background(), cfg.OidcIssuer)
  143. if err != nil {
  144. panic(err)
  145. }
  146. verifierConf := oidc.Config{
  147. ClientID: cfg.OidcAudience,
  148. SkipClientIDCheck: cfg.OidcAudience == "",
  149. SkipExpiryCheck: cfg.OidcSkipExpiryCheck,
  150. SkipIssuerCheck: cfg.OidcSkipIssuerCheck,
  151. }
  152. return &OidcAuthConsumer{
  153. BaseConfig: baseCfg,
  154. verifier: provider.Verifier(&verifierConf),
  155. }
  156. }
  157. func (auth *OidcAuthConsumer) VerifyLogin(loginMsg *msg.Login) (err error) {
  158. token, err := auth.verifier.Verify(context.Background(), loginMsg.PrivilegeKey)
  159. if err != nil {
  160. return fmt.Errorf("invalid OIDC token in login: %v", err)
  161. }
  162. auth.subjectFromLogin = token.Subject
  163. return nil
  164. }
  165. func (auth *OidcAuthConsumer) verifyPostLoginToken(privilegeKey string) (err error) {
  166. token, err := auth.verifier.Verify(context.Background(), privilegeKey)
  167. if err != nil {
  168. return fmt.Errorf("invalid OIDC token in ping: %v", err)
  169. }
  170. if token.Subject != auth.subjectFromLogin {
  171. return fmt.Errorf("received different OIDC subject in login and ping. "+
  172. "original subject: %s, "+
  173. "new subject: %s",
  174. auth.subjectFromLogin, token.Subject)
  175. }
  176. return nil
  177. }
  178. func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) {
  179. if !auth.AuthenticateHeartBeats {
  180. return nil
  181. }
  182. return auth.verifyPostLoginToken(pingMsg.PrivilegeKey)
  183. }
  184. func (auth *OidcAuthConsumer) VerifyNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
  185. if !auth.AuthenticateNewWorkConns {
  186. return nil
  187. }
  188. return auth.verifyPostLoginToken(newWorkConnMsg.PrivilegeKey)
  189. }