oidc.go 14 KB

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