4
0

oidc.go 11 KB

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