oidc.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. func (o *openIDPayload) IsAdmin(admins []string) bool {
  47. if o.Email != "" {
  48. email := sanitizeEmail(o.Email)
  49. for _, e := range admins {
  50. if email == sanitizeEmail(e) {
  51. return true
  52. }
  53. }
  54. }
  55. // The groups and emails can be in the same array for now, but consider
  56. // making a specialized option later.
  57. for _, name := range o.Groups {
  58. for _, admin := range admins {
  59. if name == admin {
  60. return true
  61. }
  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. configuration openIDConfiguration
  85. keyStore *keyStore
  86. claimer *Claimer
  87. getIdentityFunc GetIdentityFunc
  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. // Update claims with global ones
  156. if o.claimer, err = NewClaimer(o.Claims, config.Claims); err != nil {
  157. return err
  158. }
  159. // Decode and validate openid-configuration endpoint
  160. u, err := url.Parse(o.ConfigurationEndpoint)
  161. if err != nil {
  162. return errors.Wrapf(err, "error parsing %s", o.ConfigurationEndpoint)
  163. }
  164. if !strings.Contains(u.Path, "/.well-known/openid-configuration") {
  165. u.Path = path.Join(u.Path, "/.well-known/openid-configuration")
  166. }
  167. if err := getAndDecode(u.String(), &o.configuration); err != nil {
  168. return err
  169. }
  170. if err := o.configuration.Validate(); err != nil {
  171. return errors.Wrapf(err, "error parsing %s", o.ConfigurationEndpoint)
  172. }
  173. // Replace {tenantid} with the configured one
  174. if o.TenantID != "" {
  175. o.configuration.Issuer = strings.ReplaceAll(o.configuration.Issuer, "{tenantid}", o.TenantID)
  176. }
  177. // Get JWK key set
  178. o.keyStore, err = newKeyStore(o.configuration.JWKSetURI)
  179. if err != nil {
  180. return err
  181. }
  182. // Set the identity getter if it exists, otherwise use the default.
  183. if config.GetIdentityFunc == nil {
  184. o.getIdentityFunc = DefaultIdentityFunc
  185. } else {
  186. o.getIdentityFunc = config.GetIdentityFunc
  187. }
  188. return nil
  189. }
  190. // ValidatePayload validates the given token payload.
  191. func (o *OIDC) ValidatePayload(p openIDPayload) error {
  192. // According to "rfc7519 JSON Web Token" acceptable skew should be no more
  193. // than a few minutes.
  194. if err := p.ValidateWithLeeway(jose.Expected{
  195. Issuer: o.configuration.Issuer,
  196. Audience: jose.Audience{o.ClientID},
  197. Time: time.Now().UTC(),
  198. }, time.Minute); err != nil {
  199. return errs.Wrap(http.StatusUnauthorized, err, "validatePayload: failed to validate oidc token payload")
  200. }
  201. // Validate azp if present
  202. if p.AuthorizedParty != "" && p.AuthorizedParty != o.ClientID {
  203. return errs.Unauthorized("validatePayload: failed to validate oidc token payload: invalid azp")
  204. }
  205. // Validate domains (case-insensitive)
  206. if p.Email != "" && len(o.Domains) > 0 && !p.IsAdmin(o.Admins) {
  207. email := sanitizeEmail(p.Email)
  208. var found bool
  209. for _, d := range o.Domains {
  210. if strings.HasSuffix(email, "@"+strings.ToLower(d)) {
  211. found = true
  212. break
  213. }
  214. }
  215. if !found {
  216. return errs.Unauthorized("validatePayload: failed to validate oidc token payload: email is not allowed")
  217. }
  218. }
  219. // Filter by oidc group claim
  220. if len(o.Groups) > 0 {
  221. var found bool
  222. for _, group := range o.Groups {
  223. for _, g := range p.Groups {
  224. if g == group {
  225. found = true
  226. break
  227. }
  228. }
  229. }
  230. if !found {
  231. return errs.Unauthorized("validatePayload: oidc token payload validation failed: invalid group")
  232. }
  233. }
  234. return nil
  235. }
  236. // authorizeToken applies the most common provisioner authorization claims,
  237. // leaving the rest to context specific methods.
  238. func (o *OIDC) authorizeToken(token string) (*openIDPayload, error) {
  239. jwt, err := jose.ParseSigned(token)
  240. if err != nil {
  241. return nil, errs.Wrap(http.StatusUnauthorized, err,
  242. "oidc.AuthorizeToken; error parsing oidc token")
  243. }
  244. // Parse claims to get the kid
  245. var claims openIDPayload
  246. if err := jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  247. return nil, errs.Wrap(http.StatusUnauthorized, err,
  248. "oidc.AuthorizeToken; error parsing oidc token claims")
  249. }
  250. found := false
  251. kid := jwt.Headers[0].KeyID
  252. keys := o.keyStore.Get(kid)
  253. for _, key := range keys {
  254. if err := jwt.Claims(key, &claims); err == nil {
  255. found = true
  256. break
  257. }
  258. }
  259. if !found {
  260. return nil, errs.Unauthorized("oidc.AuthorizeToken; cannot validate oidc token")
  261. }
  262. if err := o.ValidatePayload(claims); err != nil {
  263. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeToken")
  264. }
  265. return &claims, nil
  266. }
  267. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  268. // revoke the certificate with serial number in the `sub` property.
  269. // Only tokens generated by an admin have the right to revoke a certificate.
  270. func (o *OIDC) AuthorizeRevoke(ctx context.Context, token string) error {
  271. claims, err := o.authorizeToken(token)
  272. if err != nil {
  273. return errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeRevoke")
  274. }
  275. // Only admins can revoke certificates.
  276. if claims.IsAdmin(o.Admins) {
  277. return nil
  278. }
  279. return errs.Unauthorized("oidc.AuthorizeRevoke; cannot revoke with non-admin oidc token")
  280. }
  281. // AuthorizeSign validates the given token.
  282. func (o *OIDC) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  283. claims, err := o.authorizeToken(token)
  284. if err != nil {
  285. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSign")
  286. }
  287. // Certificate templates
  288. sans := []string{}
  289. if claims.Email != "" {
  290. sans = append(sans, claims.Email)
  291. }
  292. // Add uri SAN with iss#sub if issuer is a URL with schema.
  293. //
  294. // According to https://openid.net/specs/openid-connect-core-1_0.html the
  295. // iss value is a case sensitive URL using the https scheme that contains
  296. // scheme, host, and optionally, port number and path components and no
  297. // query or fragment components.
  298. if iss, err := url.Parse(claims.Issuer); err == nil && iss.Scheme != "" {
  299. iss.Fragment = claims.Subject
  300. sans = append(sans, iss.String())
  301. }
  302. data := x509util.CreateTemplateData(claims.Subject, sans)
  303. if v, err := unsafeParseSigned(token); err == nil {
  304. data.SetToken(v)
  305. }
  306. // Use the default template unless no-templates are configured and email is
  307. // an admin, in that case we will use the CR template.
  308. defaultTemplate := x509util.DefaultLeafTemplate
  309. if !o.Options.GetX509Options().HasTemplate() && claims.IsAdmin(o.Admins) {
  310. defaultTemplate = x509util.DefaultAdminLeafTemplate
  311. }
  312. templateOptions, err := CustomTemplateOptions(o.Options, data, defaultTemplate)
  313. if err != nil {
  314. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSign")
  315. }
  316. return []SignOption{
  317. templateOptions,
  318. // modifiers / withOptions
  319. newProvisionerExtensionOption(TypeOIDC, o.Name, o.ClientID),
  320. profileDefaultDuration(o.claimer.DefaultTLSCertDuration()),
  321. // validators
  322. defaultPublicKeyValidator{},
  323. newValidityValidator(o.claimer.MinTLSCertDuration(), o.claimer.MaxTLSCertDuration()),
  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. if o.claimer.IsDisableRenewal() {
  332. return errs.Unauthorized("oidc.AuthorizeRenew; renew is disabled for oidc provisioner '%s'", o.GetName())
  333. }
  334. return nil
  335. }
  336. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  337. func (o *OIDC) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  338. if !o.claimer.IsSSHCAEnabled() {
  339. return nil, errs.Unauthorized("oidc.AuthorizeSSHSign; sshCA is disabled for oidc provisioner '%s'", o.GetName())
  340. }
  341. claims, err := o.authorizeToken(token)
  342. if err != nil {
  343. return nil, errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSSHSign")
  344. }
  345. // Enforce an email claim
  346. if claims.Email == "" {
  347. return nil, errs.Unauthorized("oidc.AuthorizeSSHSign: failed to validate oidc token payload: email not found")
  348. }
  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.getIdentityFunc(ctx, o, 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. // Use the default template unless no-templates are configured and email is
  370. // an admin, in that case we will use the parameters in the request.
  371. isAdmin := claims.IsAdmin(o.Admins)
  372. defaultTemplate := sshutil.DefaultTemplate
  373. if isAdmin && !o.Options.GetSSHOptions().HasTemplate() {
  374. defaultTemplate = sshutil.DefaultAdminTemplate
  375. }
  376. templateOptions, err := CustomSSHTemplateOptions(o.Options, data, defaultTemplate)
  377. if err != nil {
  378. return nil, errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSign")
  379. }
  380. signOptions := []SignOption{templateOptions}
  381. // Admin users can use any principal, and can sign user and host certificates.
  382. // Non-admin users can only use principals returned by the identityFunc, and
  383. // can only sign user certificates.
  384. if isAdmin {
  385. signOptions = append(signOptions, &sshCertOptionsRequireValidator{
  386. CertType: true,
  387. KeyID: true,
  388. Principals: true,
  389. })
  390. } else {
  391. signOptions = append(signOptions, sshCertOptionsValidator(SignSSHOptions{
  392. CertType: SSHUserCert,
  393. Principals: iden.Usernames,
  394. }))
  395. }
  396. return append(signOptions,
  397. // Set the validity bounds if not set.
  398. &sshDefaultDuration{o.claimer},
  399. // Validate public key
  400. &sshDefaultPublicKeyValidator{},
  401. // Validate the validity period.
  402. &sshCertValidityValidator{o.claimer},
  403. // Require all the fields in the SSH certificate
  404. &sshCertDefaultValidator{},
  405. ), nil
  406. }
  407. // AuthorizeSSHRevoke returns nil if the token is valid, false otherwise.
  408. func (o *OIDC) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  409. claims, err := o.authorizeToken(token)
  410. if err != nil {
  411. return errs.Wrap(http.StatusInternalServerError, err, "oidc.AuthorizeSSHRevoke")
  412. }
  413. // Only admins can revoke certificates.
  414. if claims.IsAdmin(o.Admins) {
  415. return nil
  416. }
  417. return errs.Unauthorized("oidc.AuthorizeSSHRevoke; cannot revoke with non-admin oidc token")
  418. }
  419. func getAndDecode(uri string, v interface{}) error {
  420. resp, err := http.Get(uri)
  421. if err != nil {
  422. return errors.Wrapf(err, "failed to connect to %s", uri)
  423. }
  424. defer resp.Body.Close()
  425. if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
  426. return errors.Wrapf(err, "error reading %s", uri)
  427. }
  428. return nil
  429. }