oidc.go 14 KB

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