oidc.go 11 KB

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