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