oidc.go 12 KB

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