oidc.go 10 KB

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