oidc.go 15 KB

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