1
0

oidc.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/v3/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. if cfg.OidcAudience != "" {
  94. eps["audience"] = []string{cfg.OidcAudience}
  95. }
  96. tokenGenerator := &clientcredentials.Config{
  97. ClientID: cfg.OidcClientID,
  98. ClientSecret: cfg.OidcClientSecret,
  99. Scopes: []string{cfg.OidcScope},
  100. TokenURL: cfg.OidcTokenEndpointURL,
  101. EndpointParams: eps,
  102. }
  103. return &OidcAuthProvider{
  104. BaseConfig: baseCfg,
  105. tokenGenerator: tokenGenerator,
  106. }
  107. }
  108. func (auth *OidcAuthProvider) generateAccessToken() (accessToken string, err error) {
  109. tokenObj, err := auth.tokenGenerator.Token(context.Background())
  110. if err != nil {
  111. return "", fmt.Errorf("couldn't generate OIDC token for login: %v", err)
  112. }
  113. return tokenObj.AccessToken, nil
  114. }
  115. func (auth *OidcAuthProvider) SetLogin(loginMsg *msg.Login) (err error) {
  116. loginMsg.PrivilegeKey, err = auth.generateAccessToken()
  117. return err
  118. }
  119. func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) {
  120. if !auth.AuthenticateHeartBeats {
  121. return nil
  122. }
  123. pingMsg.PrivilegeKey, err = auth.generateAccessToken()
  124. return err
  125. }
  126. func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
  127. if !auth.AuthenticateNewWorkConns {
  128. return nil
  129. }
  130. newWorkConnMsg.PrivilegeKey, err = auth.generateAccessToken()
  131. return err
  132. }
  133. type OidcAuthConsumer struct {
  134. BaseConfig
  135. verifier *oidc.IDTokenVerifier
  136. subjectFromLogin string
  137. }
  138. func NewOidcAuthVerifier(baseCfg BaseConfig, cfg OidcServerConfig) *OidcAuthConsumer {
  139. provider, err := oidc.NewProvider(context.Background(), cfg.OidcIssuer)
  140. if err != nil {
  141. panic(err)
  142. }
  143. verifierConf := oidc.Config{
  144. ClientID: cfg.OidcAudience,
  145. SkipClientIDCheck: cfg.OidcAudience == "",
  146. SkipExpiryCheck: cfg.OidcSkipExpiryCheck,
  147. SkipIssuerCheck: cfg.OidcSkipIssuerCheck,
  148. }
  149. return &OidcAuthConsumer{
  150. BaseConfig: baseCfg,
  151. verifier: provider.Verifier(&verifierConf),
  152. }
  153. }
  154. func (auth *OidcAuthConsumer) VerifyLogin(loginMsg *msg.Login) (err error) {
  155. token, err := auth.verifier.Verify(context.Background(), loginMsg.PrivilegeKey)
  156. if err != nil {
  157. return fmt.Errorf("invalid OIDC token in login: %v", err)
  158. }
  159. auth.subjectFromLogin = token.Subject
  160. return nil
  161. }
  162. func (auth *OidcAuthConsumer) verifyPostLoginToken(privilegeKey string) (err error) {
  163. token, err := auth.verifier.Verify(context.Background(), privilegeKey)
  164. if err != nil {
  165. return fmt.Errorf("invalid OIDC token in ping: %v", err)
  166. }
  167. if token.Subject != auth.subjectFromLogin {
  168. return fmt.Errorf("received different OIDC subject in login and ping. "+
  169. "original subject: %s, "+
  170. "new subject: %s",
  171. auth.subjectFromLogin, token.Subject)
  172. }
  173. return nil
  174. }
  175. func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) {
  176. if !auth.AuthenticateHeartBeats {
  177. return nil
  178. }
  179. return auth.verifyPostLoginToken(pingMsg.PrivilegeKey)
  180. }
  181. func (auth *OidcAuthConsumer) VerifyNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) {
  182. if !auth.AuthenticateNewWorkConns {
  183. return nil
  184. }
  185. return auth.verifyPostLoginToken(newWorkConnMsg.PrivilegeKey)
  186. }