oidc.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "slices"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/linkedca"
  15. "go.step.sm/crypto/jose"
  16. "go.step.sm/crypto/sshutil"
  17. "go.step.sm/crypto/x509util"
  18. "github.com/smallstep/certificates/errs"
  19. )
  20. // openIDConfiguration contains the necessary properties in the
  21. // `/.well-known/openid-configuration` document.
  22. type openIDConfiguration struct {
  23. Issuer string `json:"issuer"`
  24. JWKSetURI string `json:"jwks_uri"`
  25. }
  26. // Validate validates the values in a well-known OpenID configuration endpoint.
  27. func (c openIDConfiguration) Validate() error {
  28. switch {
  29. case c.Issuer == "":
  30. return errors.New("issuer cannot be empty")
  31. case c.JWKSetURI == "":
  32. return errors.New("jwks_uri cannot be empty")
  33. default:
  34. return nil
  35. }
  36. }
  37. // openIDPayload represents the fields on the id_token JWT payload.
  38. type openIDPayload struct {
  39. jose.Claims
  40. AtHash string `json:"at_hash"`
  41. AuthorizedParty string `json:"azp"`
  42. Email string `json:"email"`
  43. EmailVerified bool `json:"email_verified"`
  44. Hd string `json:"hd"`
  45. Nonce string `json:"nonce"`
  46. Groups []string `json:"groups"`
  47. }
  48. func (o *openIDPayload) IsAdmin(admins []string) bool {
  49. if o.Email != "" {
  50. email := sanitizeEmail(o.Email)
  51. for _, e := range admins {
  52. if email == sanitizeEmail(e) {
  53. return true
  54. }
  55. }
  56. }
  57. // The groups and emails can be in the same array for now, but consider
  58. // making a specialized option later.
  59. for _, name := range o.Groups {
  60. if slices.Contains(admins, name) {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. // OIDC represents an OAuth 2.0 OpenID Connect provider.
  67. //
  68. // ClientSecret is mandatory, but it can be an empty string.
  69. type OIDC struct {
  70. *base
  71. ID string `json:"-"`
  72. Type string `json:"type"`
  73. Name string `json:"name"`
  74. ClientID string `json:"clientID"`
  75. ClientSecret string `json:"clientSecret"`
  76. ConfigurationEndpoint string `json:"configurationEndpoint"`
  77. TenantID string `json:"tenantID,omitempty"`
  78. Admins []string `json:"admins,omitempty"`
  79. Domains []string `json:"domains,omitempty"`
  80. Groups []string `json:"groups,omitempty"`
  81. ListenAddress string `json:"listenAddress,omitempty"`
  82. Claims *Claims `json:"claims,omitempty"`
  83. Options *Options `json:"options,omitempty"`
  84. Scopes []string `json:"scopes,omitempty"`
  85. AuthParams []string `json:"authParams,omitempty"`
  86. configuration openIDConfiguration
  87. keyStore *keyStore
  88. ctl *Controller
  89. }
  90. func sanitizeEmail(email string) string {
  91. if i := strings.LastIndex(email, "@"); i >= 0 {
  92. email = email[:i] + strings.ToLower(email[i:])
  93. }
  94. return email
  95. }
  96. // GetID returns the provisioner unique identifier, the OIDC provisioner the
  97. // uses the clientID for this.
  98. func (o *OIDC) GetID() string {
  99. if o.ID != "" {
  100. return o.ID
  101. }
  102. return o.GetIDForToken()
  103. }
  104. // GetIDForToken returns an identifier that will be used to load the provisioner
  105. // from a token.
  106. func (o *OIDC) GetIDForToken() string {
  107. return o.ClientID
  108. }
  109. // GetTokenID returns the provisioner unique identifier, the OIDC provisioner the
  110. // uses the clientID for this.
  111. func (o *OIDC) GetTokenID(ott string) (string, error) {
  112. // Validate payload
  113. token, err := jose.ParseSigned(ott)
  114. if err != nil {
  115. return "", errors.Wrap(err, "error parsing token")
  116. }
  117. // Get claims w/out verification. We need to look up the provisioner
  118. // key in order to verify the claims and we need the issuer from the claims
  119. // before we can look up the provisioner.
  120. var claims openIDPayload
  121. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  122. return "", errors.Wrap(err, "error verifying claims")
  123. }
  124. return claims.Nonce, nil
  125. }
  126. // GetName returns the name of the provisioner.
  127. func (o *OIDC) GetName() string {
  128. return o.Name
  129. }
  130. // GetType returns the type of provisioner.
  131. func (o *OIDC) GetType() Type {
  132. return TypeOIDC
  133. }
  134. // GetEncryptedKey is not available in an OIDC provisioner.
  135. func (o *OIDC) GetEncryptedKey() (kid, key string, ok bool) {
  136. return "", "", false
  137. }
  138. // Init validates and initializes the OIDC provider.
  139. func (o *OIDC) Init(config Config) (err error) {
  140. switch {
  141. case o.Type == "":
  142. return errors.New("type cannot be empty")
  143. case o.Name == "":
  144. return errors.New("name cannot be empty")
  145. case o.ClientID == "":
  146. return errors.New("clientID cannot be empty")
  147. case o.ConfigurationEndpoint == "":
  148. return errors.New("configurationEndpoint cannot be empty")
  149. }
  150. // Validate listenAddress if given
  151. if o.ListenAddress != "" {
  152. if _, _, err := net.SplitHostPort(o.ListenAddress); err != nil {
  153. return errors.Wrap(err, "error parsing listenAddress")
  154. }
  155. }
  156. // Decode and validate openid-configuration endpoint
  157. u, err := url.Parse(o.ConfigurationEndpoint)
  158. if err != nil {
  159. return errors.Wrapf(err, "error parsing %s", o.ConfigurationEndpoint)
  160. }
  161. if !strings.Contains(u.Path, "/.well-known/openid-configuration") {
  162. u.Path = path.Join(u.Path, "/.well-known/openid-configuration")
  163. }
  164. // Initialize the common provisioner controller
  165. o.ctl, err = NewController(o, o.Claims, config, o.Options)
  166. if err != nil {
  167. return err
  168. }
  169. // Decode and validate openid-configuration
  170. httpClient := o.ctl.GetHTTPClient()
  171. if err := getAndDecode(httpClient, u.String(), &o.configuration); err != nil {
  172. return err
  173. }
  174. if err := o.configuration.Validate(); err != nil {
  175. return errors.Wrapf(err, "error parsing %s", o.ConfigurationEndpoint)
  176. }
  177. // Replace {tenantid} with the configured one
  178. if o.TenantID != "" {
  179. o.configuration.Issuer = strings.ReplaceAll(o.configuration.Issuer, "{tenantid}", o.TenantID)
  180. }
  181. // Get JWK key set
  182. o.keyStore, err = newKeyStore(httpClient, o.configuration.JWKSetURI)
  183. return
  184. }
  185. // ValidatePayload validates the given token payload.
  186. func (o *OIDC) ValidatePayload(p openIDPayload) error {
  187. // According to "rfc7519 JSON Web Token" acceptable skew should be no more
  188. // than a few minutes.
  189. if err := p.ValidateWithLeeway(jose.Expected{
  190. Issuer: o.configuration.Issuer,
  191. AnyAudience: jose.Audience{o.ClientID},
  192. Time: time.Now().UTC(),
  193. }, time.Minute); err != nil {
  194. return errs.Wrap(http.StatusUnauthorized, err, "validatePayload: failed to validate oidc token payload")
  195. }
  196. // Validate azp if present
  197. if p.AuthorizedParty != "" && p.AuthorizedParty != o.ClientID {
  198. return errs.Unauthorized("validatePayload: failed to validate oidc token payload: invalid azp")
  199. }
  200. // Validate domains (case-insensitive)
  201. if p.Email != "" && len(o.Domains) > 0 && !p.IsAdmin(o.Admins) {
  202. email := sanitizeEmail(p.Email)
  203. var found bool
  204. for _, d := range o.Domains {
  205. if strings.HasSuffix(email, "@"+strings.ToLower(d)) {
  206. found = true
  207. break
  208. }
  209. }
  210. if !found {
  211. return errs.Unauthorized("validatePayload: failed to validate oidc token payload: email %q is not allowed", p.Email)
  212. }
  213. }
  214. // Filter by oidc group claim
  215. if len(o.Groups) > 0 {
  216. var found bool
  217. for _, group := range o.Groups {
  218. if slices.Contains(p.Groups, group) {
  219. found = true
  220. }
  221. }
  222. if !found {
  223. return errs.Unauthorized("validatePayload: oidc token payload validation failed: invalid group")
  224. }
  225. }
  226. return nil
  227. }
  228. // authorizeToken applies the most common provisioner authorization claims,
  229. // leaving the rest to context specific methods.
  230. func (o *OIDC) authorizeToken(token string) (*openIDPayload, error) {
  231. jwt, err := jose.ParseSigned(token)
  232. if err != nil {
  233. return nil, errs.Wrap(http.StatusUnauthorized, err,
  234. "oidc.AuthorizeToken; error parsing oidc token")
  235. }
  236. // Parse claims to get the kid
  237. var claims openIDPayload
  238. if err := jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  239. return nil, errs.Wrap(http.StatusUnauthorized, err,
  240. "oidc.AuthorizeToken; error parsing oidc token claims")
  241. }
  242. found := false
  243. kid := jwt.Headers[0].KeyID
  244. keys := o.keyStore.Get(kid)
  245. for _, key := range keys {
  246. if err := jwt.Claims(key, &claims); err == nil {
  247. found = true
  248. break
  249. }
  250. }
  251. if !found {
  252. return nil, errs.Unauthorized("oidc.AuthorizeToken; cannot validate oidc token")
  253. }
  254. if err := o.ValidatePayload(claims); err != nil {
  255. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeToken")
  256. }
  257. return &claims, nil
  258. }
  259. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  260. // revoke the certificate with serial number in the `sub` property.
  261. // Only tokens generated by an admin have the right to revoke a certificate.
  262. func (o *OIDC) AuthorizeRevoke(_ context.Context, token string) error {
  263. claims, err := o.authorizeToken(token)
  264. if err != nil {
  265. return errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeRevoke")
  266. }
  267. // Only admins can revoke certificates.
  268. if claims.IsAdmin(o.Admins) {
  269. return nil
  270. }
  271. return errs.Unauthorized("oidc.AuthorizeRevoke; cannot revoke with non-admin oidc token")
  272. }
  273. // AuthorizeSign validates the given token.
  274. func (o *OIDC) AuthorizeSign(_ context.Context, token string) ([]SignOption, error) {
  275. claims, err := o.authorizeToken(token)
  276. if err != nil {
  277. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSign")
  278. }
  279. // Certificate templates
  280. sans := []string{}
  281. if claims.Email != "" {
  282. sans = append(sans, claims.Email)
  283. }
  284. // Add uri SAN with iss#sub if issuer is a URL with schema.
  285. //
  286. // According to https://openid.net/specs/openid-connect-core-1_0.html the
  287. // iss value is a case sensitive URL using the https scheme that contains
  288. // scheme, host, and optionally, port number and path components and no
  289. // query or fragment components.
  290. if iss, err := url.Parse(claims.Issuer); err == nil && iss.Scheme != "" {
  291. iss.Fragment = claims.Subject
  292. sans = append(sans, iss.String())
  293. }
  294. data := x509util.CreateTemplateData(claims.Subject, sans)
  295. if v, err := unsafeParseSigned(token); err == nil {
  296. data.SetToken(v)
  297. }
  298. // Use the default template unless no-templates are configured and email is
  299. // an admin, in that case we will use the CR template.
  300. defaultTemplate := x509util.DefaultLeafTemplate
  301. if !o.Options.GetX509Options().HasTemplate() && claims.IsAdmin(o.Admins) {
  302. defaultTemplate = x509util.DefaultAdminLeafTemplate
  303. }
  304. templateOptions, err := CustomTemplateOptions(o.Options, data, defaultTemplate)
  305. if err != nil {
  306. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSign")
  307. }
  308. return []SignOption{
  309. o,
  310. templateOptions,
  311. // modifiers / withOptions
  312. newProvisionerExtensionOption(TypeOIDC, o.Name, o.ClientID).WithControllerOptions(o.ctl),
  313. profileDefaultDuration(o.ctl.Claimer.DefaultTLSCertDuration()),
  314. // validators
  315. defaultPublicKeyValidator{},
  316. newValidityValidator(o.ctl.Claimer.MinTLSCertDuration(), o.ctl.Claimer.MaxTLSCertDuration()),
  317. newX509NamePolicyValidator(o.ctl.getPolicy().getX509()),
  318. // webhooks
  319. o.ctl.newWebhookController(data, linkedca.Webhook_X509),
  320. }, nil
  321. }
  322. // AuthorizeRenew returns an error if the renewal is disabled.
  323. // NOTE: This method does not actually validate the certificate or check it's
  324. // revocation status. Just confirms that the provisioner that created the
  325. // certificate was configured to allow renewals.
  326. func (o *OIDC) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  327. return o.ctl.AuthorizeRenew(ctx, cert)
  328. }
  329. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  330. func (o *OIDC) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  331. if !o.ctl.Claimer.IsSSHCAEnabled() {
  332. return nil, errs.Unauthorized("oidc.AuthorizeSSHSign; sshCA is disabled for oidc provisioner '%s'", o.GetName())
  333. }
  334. claims, err := o.authorizeToken(token)
  335. if err != nil {
  336. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSSHSign")
  337. }
  338. if claims.Subject == "" {
  339. return nil, errs.Unauthorized("oidc.AuthorizeSSHSign: failed to validate oidc token payload: subject not found")
  340. }
  341. var data sshutil.TemplateData
  342. if claims.Email == "" {
  343. // If email is empty, use the Subject claim instead to create minimal
  344. // data for the template to use.
  345. data = sshutil.CreateTemplateData(sshutil.UserCert, claims.Subject, nil)
  346. if v, err := unsafeParseSigned(token); err == nil {
  347. data.SetToken(v)
  348. }
  349. } else {
  350. // Get the identity using either the default identityFunc or one injected
  351. // externally. Note that the PreferredUsername might be empty.
  352. // TBD: Would preferred_username present a safety issue here?
  353. iden, err := o.ctl.GetIdentity(ctx, claims.Email)
  354. if err != nil {
  355. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSSHSign")
  356. }
  357. // Certificate templates.
  358. data = sshutil.CreateTemplateData(sshutil.UserCert, claims.Email, iden.Usernames)
  359. if v, err := unsafeParseSigned(token); err == nil {
  360. data.SetToken(v)
  361. }
  362. // Add custom extensions added in the identity function.
  363. for k, v := range iden.Permissions.Extensions {
  364. data.AddExtension(k, v)
  365. }
  366. // Add custom critical options added in the identity function.
  367. for k, v := range iden.Permissions.CriticalOptions {
  368. data.AddCriticalOption(k, v)
  369. }
  370. }
  371. // Use the default template unless no-templates are configured and email is
  372. // an admin, in that case we will use the parameters in the request.
  373. isAdmin := claims.IsAdmin(o.Admins)
  374. defaultTemplate := sshutil.DefaultTemplate
  375. if isAdmin && !o.Options.GetSSHOptions().HasTemplate() {
  376. defaultTemplate = sshutil.DefaultAdminTemplate
  377. }
  378. templateOptions, err := CustomSSHTemplateOptions(o.Options, data, defaultTemplate)
  379. if err != nil {
  380. return nil, errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSign")
  381. }
  382. signOptions := []SignOption{templateOptions}
  383. // Admin users can use any principal, and can sign user and host certificates.
  384. // Non-admin users can only use principals returned by the identityFunc, and
  385. // can only sign user certificates.
  386. if isAdmin {
  387. signOptions = append(signOptions, &sshCertOptionsRequireValidator{
  388. CertType: true,
  389. KeyID: true,
  390. Principals: true,
  391. })
  392. } else {
  393. signOptions = append(signOptions, sshCertOptionsValidator(SignSSHOptions{
  394. CertType: SSHUserCert,
  395. }))
  396. }
  397. return append(signOptions,
  398. o,
  399. // Set the validity bounds if not set.
  400. &sshDefaultDuration{o.ctl.Claimer},
  401. // Validate public key
  402. &sshDefaultPublicKeyValidator{},
  403. // Validate the validity period.
  404. &sshCertValidityValidator{o.ctl.Claimer},
  405. // Require all the fields in the SSH certificate
  406. &sshCertDefaultValidator{},
  407. // Ensure that all principal names are allowed
  408. newSSHNamePolicyValidator(o.ctl.getPolicy().getSSHHost(), o.ctl.getPolicy().getSSHUser()),
  409. // Call webhooks
  410. o.ctl.newWebhookController(data, linkedca.Webhook_SSH),
  411. ), nil
  412. }
  413. // AuthorizeSSHRevoke returns nil if the token is valid, false otherwise.
  414. func (o *OIDC) AuthorizeSSHRevoke(_ context.Context, token string) error {
  415. claims, err := o.authorizeToken(token)
  416. if err != nil {
  417. return errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSSHRevoke")
  418. }
  419. // Only admins can revoke certificates.
  420. if claims.IsAdmin(o.Admins) {
  421. return nil
  422. }
  423. return errs.Unauthorized("oidc.AuthorizeSSHRevoke; cannot revoke with non-admin oidc token")
  424. }
  425. func getAndDecode(client HTTPClient, uri string, v any) error {
  426. resp, err := client.Get(uri)
  427. if err != nil {
  428. return errors.Wrapf(err, "failed to connect to %s", uri)
  429. }
  430. defer resp.Body.Close()
  431. if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
  432. return errors.Wrapf(err, "error reading %s", uri)
  433. }
  434. return nil
  435. }