oidc.go 15 KB

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