provisioner.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. stderrors "errors"
  7. "net/url"
  8. "regexp"
  9. "strings"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/certificates/db"
  12. "github.com/smallstep/certificates/errs"
  13. "golang.org/x/crypto/ssh"
  14. )
  15. // Interface is the interface that all provisioner types must implement.
  16. type Interface interface {
  17. GetID() string
  18. GetIDForToken() string
  19. GetTokenID(token string) (string, error)
  20. GetName() string
  21. GetType() Type
  22. GetEncryptedKey() (kid string, key string, ok bool)
  23. Init(config Config) error
  24. AuthorizeSign(ctx context.Context, token string) ([]SignOption, error)
  25. AuthorizeRevoke(ctx context.Context, token string) error
  26. AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error
  27. AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error)
  28. AuthorizeSSHRevoke(ctx context.Context, token string) error
  29. AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error)
  30. AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error)
  31. }
  32. // ErrAllowTokenReuse is an error that is returned by provisioners that allows
  33. // the reuse of tokens.
  34. //
  35. // This is, for example, returned by the Azure provisioner when
  36. // DisableTrustOnFirstUse is set to true. Azure caches tokens for up to 24hr and
  37. // has no mechanism for getting a different token - this can be an issue when
  38. // rebooting a VM. In contrast, AWS and GCP have facilities for requesting a new
  39. // token. Therefore, for the Azure provisioner we are enabling token reuse, with
  40. // the understanding that we are not following security best practices
  41. var ErrAllowTokenReuse = stderrors.New("allow token reuse")
  42. // Audiences stores all supported audiences by request type.
  43. type Audiences struct {
  44. Sign []string
  45. Revoke []string
  46. SSHSign []string
  47. SSHRevoke []string
  48. SSHRenew []string
  49. SSHRekey []string
  50. }
  51. // All returns all supported audiences across all request types in one list.
  52. func (a Audiences) All() (auds []string) {
  53. auds = a.Sign
  54. auds = append(auds, a.Revoke...)
  55. auds = append(auds, a.SSHSign...)
  56. auds = append(auds, a.SSHRevoke...)
  57. auds = append(auds, a.SSHRenew...)
  58. auds = append(auds, a.SSHRekey...)
  59. return
  60. }
  61. // WithFragment returns a copy of audiences where the url audiences contains the
  62. // given fragment.
  63. func (a Audiences) WithFragment(fragment string) Audiences {
  64. ret := Audiences{
  65. Sign: make([]string, len(a.Sign)),
  66. Revoke: make([]string, len(a.Revoke)),
  67. SSHSign: make([]string, len(a.SSHSign)),
  68. SSHRevoke: make([]string, len(a.SSHRevoke)),
  69. SSHRenew: make([]string, len(a.SSHRenew)),
  70. SSHRekey: make([]string, len(a.SSHRekey)),
  71. }
  72. for i, s := range a.Sign {
  73. if u, err := url.Parse(s); err == nil {
  74. ret.Sign[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
  75. } else {
  76. ret.Sign[i] = s
  77. }
  78. }
  79. for i, s := range a.Revoke {
  80. if u, err := url.Parse(s); err == nil {
  81. ret.Revoke[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
  82. } else {
  83. ret.Revoke[i] = s
  84. }
  85. }
  86. for i, s := range a.SSHSign {
  87. if u, err := url.Parse(s); err == nil {
  88. ret.SSHSign[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
  89. } else {
  90. ret.SSHSign[i] = s
  91. }
  92. }
  93. for i, s := range a.SSHRevoke {
  94. if u, err := url.Parse(s); err == nil {
  95. ret.SSHRevoke[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
  96. } else {
  97. ret.SSHRevoke[i] = s
  98. }
  99. }
  100. for i, s := range a.SSHRenew {
  101. if u, err := url.Parse(s); err == nil {
  102. ret.SSHRenew[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
  103. } else {
  104. ret.SSHRenew[i] = s
  105. }
  106. }
  107. for i, s := range a.SSHRekey {
  108. if u, err := url.Parse(s); err == nil {
  109. ret.SSHRekey[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
  110. } else {
  111. ret.SSHRekey[i] = s
  112. }
  113. }
  114. return ret
  115. }
  116. // generateSignAudience generates a sign audience with the format
  117. // https://<host>/1.0/sign#provisionerID
  118. func generateSignAudience(caURL, provisionerID string) (string, error) {
  119. u, err := url.Parse(caURL)
  120. if err != nil {
  121. return "", errors.Wrapf(err, "error parsing %s", caURL)
  122. }
  123. return u.ResolveReference(&url.URL{Path: "/1.0/sign", Fragment: provisionerID}).String(), nil
  124. }
  125. // Type indicates the provisioner Type.
  126. type Type int
  127. const (
  128. noopType Type = 0
  129. // TypeJWK is used to indicate the JWK provisioners.
  130. TypeJWK Type = 1
  131. // TypeOIDC is used to indicate the OIDC provisioners.
  132. TypeOIDC Type = 2
  133. // TypeGCP is used to indicate the GCP provisioners.
  134. TypeGCP Type = 3
  135. // TypeAWS is used to indicate the AWS provisioners.
  136. TypeAWS Type = 4
  137. // TypeAzure is used to indicate the Azure provisioners.
  138. TypeAzure Type = 5
  139. // TypeACME is used to indicate the ACME provisioners.
  140. TypeACME Type = 6
  141. // TypeX5C is used to indicate the X5C provisioners.
  142. TypeX5C Type = 7
  143. // TypeK8sSA is used to indicate the X5C provisioners.
  144. TypeK8sSA Type = 8
  145. // TypeSSHPOP is used to indicate the SSHPOP provisioners.
  146. TypeSSHPOP Type = 9
  147. // TypeSCEP is used to indicate the SCEP provisioners
  148. TypeSCEP Type = 10
  149. )
  150. // String returns the string representation of the type.
  151. func (t Type) String() string {
  152. switch t {
  153. case TypeJWK:
  154. return "JWK"
  155. case TypeOIDC:
  156. return "OIDC"
  157. case TypeGCP:
  158. return "GCP"
  159. case TypeAWS:
  160. return "AWS"
  161. case TypeAzure:
  162. return "Azure"
  163. case TypeACME:
  164. return "ACME"
  165. case TypeX5C:
  166. return "X5C"
  167. case TypeK8sSA:
  168. return "K8sSA"
  169. case TypeSSHPOP:
  170. return "SSHPOP"
  171. case TypeSCEP:
  172. return "SCEP"
  173. default:
  174. return ""
  175. }
  176. }
  177. // SSHKeys represents the SSH User and Host public keys.
  178. type SSHKeys struct {
  179. UserKeys []ssh.PublicKey
  180. HostKeys []ssh.PublicKey
  181. }
  182. // Config defines the default parameters used in the initialization of
  183. // provisioners.
  184. type Config struct {
  185. // Claims are the default claims.
  186. Claims Claims
  187. // Audiences are the audiences used in the default provisioner, (JWK).
  188. Audiences Audiences
  189. // DB is the interface to the authority DB client.
  190. DB db.AuthDB
  191. // SSHKeys are the root SSH public keys
  192. SSHKeys *SSHKeys
  193. // GetIdentityFunc is a function that returns an identity that will be
  194. // used by the provisioner to populate certificate attributes.
  195. GetIdentityFunc GetIdentityFunc
  196. }
  197. type provisioner struct {
  198. Type string `json:"type"`
  199. }
  200. // List represents a list of provisioners.
  201. type List []Interface
  202. // UnmarshalJSON implements json.Unmarshaler and allows to unmarshal a list of a
  203. // interfaces into the right type.
  204. func (l *List) UnmarshalJSON(data []byte) error {
  205. ps := []json.RawMessage{}
  206. if err := json.Unmarshal(data, &ps); err != nil {
  207. return errors.Wrap(err, "error unmarshaling provisioner list")
  208. }
  209. *l = List{}
  210. for _, data := range ps {
  211. var typ provisioner
  212. if err := json.Unmarshal(data, &typ); err != nil {
  213. return errors.Errorf("error unmarshaling provisioner")
  214. }
  215. var p Interface
  216. switch strings.ToLower(typ.Type) {
  217. case "jwk":
  218. p = &JWK{}
  219. case "oidc":
  220. p = &OIDC{}
  221. case "gcp":
  222. p = &GCP{}
  223. case "aws":
  224. p = &AWS{}
  225. case "azure":
  226. p = &Azure{}
  227. case "acme":
  228. p = &ACME{}
  229. case "x5c":
  230. p = &X5C{}
  231. case "k8ssa":
  232. p = &K8sSA{}
  233. case "sshpop":
  234. p = &SSHPOP{}
  235. case "scep":
  236. p = &SCEP{}
  237. default:
  238. // Skip unsupported provisioners. A client using this method may be
  239. // compiled with a version of smallstep/certificates that does not
  240. // support a specific provisioner type. If we don't skip unknown
  241. // provisioners, a client encountering an unknown provisioner will
  242. // break. Rather than break the client, we skip the provisioner.
  243. // TODO: accept a pluggable logger (depending on client) that can
  244. // warn the user that an unknown provisioner was found and suggest
  245. // that the user update their client's dependency on
  246. // step/certificates and recompile.
  247. continue
  248. }
  249. if err := json.Unmarshal(data, p); err != nil {
  250. return errors.Wrap(err, "error unmarshaling provisioner")
  251. }
  252. *l = append(*l, p)
  253. }
  254. return nil
  255. }
  256. var sshUserRegex = regexp.MustCompile("^[a-z][-a-z0-9_]*$")
  257. // SanitizeSSHUserPrincipal grabs an email or a string with the format
  258. // local@domain and returns a sanitized version of the local, valid to be used
  259. // as a user name. If the email starts with a letter between a and z, the
  260. // resulting string will match the regular expression `^[a-z][-a-z0-9_]*$`.
  261. func SanitizeSSHUserPrincipal(email string) string {
  262. if i := strings.LastIndex(email, "@"); i >= 0 {
  263. email = email[:i]
  264. }
  265. return strings.Map(func(r rune) rune {
  266. switch {
  267. case r >= 'a' && r <= 'z':
  268. return r
  269. case r >= '0' && r <= '9':
  270. return r
  271. case r == '-':
  272. return '-'
  273. case r == '.': // drop dots
  274. return -1
  275. default:
  276. return '_'
  277. }
  278. }, strings.ToLower(email))
  279. }
  280. type base struct{}
  281. // AuthorizeSign returns an unimplemented error. Provisioners should overwrite
  282. // this method if they will support authorizing tokens for signing x509 Certificates.
  283. func (b *base) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  284. return nil, errs.Unauthorized("provisioner.AuthorizeSign not implemented")
  285. }
  286. // AuthorizeRevoke returns an unimplemented error. Provisioners should overwrite
  287. // this method if they will support authorizing tokens for revoking x509 Certificates.
  288. func (b *base) AuthorizeRevoke(ctx context.Context, token string) error {
  289. return errs.Unauthorized("provisioner.AuthorizeRevoke not implemented")
  290. }
  291. // AuthorizeRenew returns an unimplemented error. Provisioners should overwrite
  292. // this method if they will support authorizing tokens for renewing x509 Certificates.
  293. func (b *base) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  294. return errs.Unauthorized("provisioner.AuthorizeRenew not implemented")
  295. }
  296. // AuthorizeSSHSign returns an unimplemented error. Provisioners should overwrite
  297. // this method if they will support authorizing tokens for signing SSH Certificates.
  298. func (b *base) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  299. return nil, errs.Unauthorized("provisioner.AuthorizeSSHSign not implemented")
  300. }
  301. // AuthorizeRevoke returns an unimplemented error. Provisioners should overwrite
  302. // this method if they will support authorizing tokens for revoking SSH Certificates.
  303. func (b *base) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  304. return errs.Unauthorized("provisioner.AuthorizeSSHRevoke not implemented")
  305. }
  306. // AuthorizeSSHRenew returns an unimplemented error. Provisioners should overwrite
  307. // this method if they will support authorizing tokens for renewing SSH Certificates.
  308. func (b *base) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  309. return nil, errs.Unauthorized("provisioner.AuthorizeSSHRenew not implemented")
  310. }
  311. // AuthorizeSSHRekey returns an unimplemented error. Provisioners should overwrite
  312. // this method if they will support authorizing tokens for rekeying SSH Certificates.
  313. func (b *base) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  314. return nil, nil, errs.Unauthorized("provisioner.AuthorizeSSHRekey not implemented")
  315. }
  316. // Identity is the type representing an externally supplied identity that is used
  317. // by provisioners to populate certificate fields.
  318. type Identity struct {
  319. Usernames []string `json:"usernames"`
  320. Permissions `json:"permissions"`
  321. }
  322. // Permissions defines extra extensions and critical options to grant to an SSH certificate.
  323. type Permissions struct {
  324. Extensions map[string]string `json:"extensions"`
  325. CriticalOptions map[string]string `json:"criticalOptions"`
  326. }
  327. // GetIdentityFunc is a function that returns an identity.
  328. type GetIdentityFunc func(ctx context.Context, p Interface, email string) (*Identity, error)
  329. // DefaultIdentityFunc return a default identity depending on the provisioner
  330. // type. For OIDC email is always present and the usernames might
  331. // contain empty strings.
  332. func DefaultIdentityFunc(ctx context.Context, p Interface, email string) (*Identity, error) {
  333. switch k := p.(type) {
  334. case *OIDC:
  335. // OIDC principals would be:
  336. // ~~1. Preferred usernames.~~ Note: Under discussion, currently disabled
  337. // 2. Sanitized local.
  338. // 3. Raw local (if different).
  339. // 4. Email address.
  340. name := SanitizeSSHUserPrincipal(email)
  341. if !sshUserRegex.MatchString(name) {
  342. return nil, errors.Errorf("invalid principal '%s' from email '%s'", name, email)
  343. }
  344. usernames := []string{name}
  345. if i := strings.LastIndex(email, "@"); i >= 0 {
  346. usernames = append(usernames, email[:i])
  347. }
  348. usernames = append(usernames, email)
  349. return &Identity{
  350. Usernames: SanitizeStringSlices(usernames),
  351. }, nil
  352. default:
  353. return nil, errors.Errorf("provisioner type '%T' not supported by identity function", k)
  354. }
  355. }
  356. // SanitizeStringSlices removes duplicated an empty strings.
  357. func SanitizeStringSlices(original []string) []string {
  358. output := []string{}
  359. seen := make(map[string]struct{})
  360. for _, entry := range original {
  361. if entry == "" {
  362. continue
  363. }
  364. if _, value := seen[entry]; !value {
  365. seen[entry] = struct{}{}
  366. output = append(output, entry)
  367. }
  368. }
  369. return output
  370. }
  371. // MockProvisioner for testing
  372. type MockProvisioner struct {
  373. Mret1, Mret2, Mret3 interface{}
  374. Merr error
  375. MgetID func() string
  376. MgetIDForToken func() string
  377. MgetTokenID func(string) (string, error)
  378. MgetName func() string
  379. MgetType func() Type
  380. MgetEncryptedKey func() (string, string, bool)
  381. Minit func(Config) error
  382. MauthorizeSign func(ctx context.Context, ott string) ([]SignOption, error)
  383. MauthorizeRenew func(ctx context.Context, cert *x509.Certificate) error
  384. MauthorizeRevoke func(ctx context.Context, ott string) error
  385. MauthorizeSSHSign func(ctx context.Context, ott string) ([]SignOption, error)
  386. MauthorizeSSHRenew func(ctx context.Context, ott string) (*ssh.Certificate, error)
  387. MauthorizeSSHRekey func(ctx context.Context, ott string) (*ssh.Certificate, []SignOption, error)
  388. MauthorizeSSHRevoke func(ctx context.Context, ott string) error
  389. }
  390. // GetID mock
  391. func (m *MockProvisioner) GetID() string {
  392. if m.MgetID != nil {
  393. return m.MgetID()
  394. }
  395. return m.Mret1.(string)
  396. }
  397. // GetIDForToken mock
  398. func (m *MockProvisioner) GetIDForToken() string {
  399. if m.MgetIDForToken != nil {
  400. return m.MgetIDForToken()
  401. }
  402. return m.Mret1.(string)
  403. }
  404. // GetTokenID mock
  405. func (m *MockProvisioner) GetTokenID(token string) (string, error) {
  406. if m.MgetTokenID != nil {
  407. return m.MgetTokenID(token)
  408. }
  409. if m.Mret1 == nil {
  410. return "", m.Merr
  411. }
  412. return m.Mret1.(string), m.Merr
  413. }
  414. // GetName mock
  415. func (m *MockProvisioner) GetName() string {
  416. if m.MgetName != nil {
  417. return m.MgetName()
  418. }
  419. return m.Mret1.(string)
  420. }
  421. // GetType mock
  422. func (m *MockProvisioner) GetType() Type {
  423. if m.MgetType != nil {
  424. return m.MgetType()
  425. }
  426. return m.Mret1.(Type)
  427. }
  428. // GetEncryptedKey mock
  429. func (m *MockProvisioner) GetEncryptedKey() (string, string, bool) {
  430. if m.MgetEncryptedKey != nil {
  431. return m.MgetEncryptedKey()
  432. }
  433. return m.Mret1.(string), m.Mret2.(string), m.Mret3.(bool)
  434. }
  435. // Init mock
  436. func (m *MockProvisioner) Init(c Config) error {
  437. if m.Minit != nil {
  438. return m.Minit(c)
  439. }
  440. return m.Merr
  441. }
  442. // AuthorizeSign mock
  443. func (m *MockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]SignOption, error) {
  444. if m.MauthorizeSign != nil {
  445. return m.MauthorizeSign(ctx, ott)
  446. }
  447. return m.Mret1.([]SignOption), m.Merr
  448. }
  449. // AuthorizeRevoke mock
  450. func (m *MockProvisioner) AuthorizeRevoke(ctx context.Context, ott string) error {
  451. if m.MauthorizeRevoke != nil {
  452. return m.MauthorizeRevoke(ctx, ott)
  453. }
  454. return m.Merr
  455. }
  456. // AuthorizeRenew mock
  457. func (m *MockProvisioner) AuthorizeRenew(ctx context.Context, c *x509.Certificate) error {
  458. if m.MauthorizeRenew != nil {
  459. return m.MauthorizeRenew(ctx, c)
  460. }
  461. return m.Merr
  462. }
  463. // AuthorizeSSHSign mock
  464. func (m *MockProvisioner) AuthorizeSSHSign(ctx context.Context, ott string) ([]SignOption, error) {
  465. if m.MauthorizeSign != nil {
  466. return m.MauthorizeSign(ctx, ott)
  467. }
  468. return m.Mret1.([]SignOption), m.Merr
  469. }
  470. // AuthorizeSSHRenew mock
  471. func (m *MockProvisioner) AuthorizeSSHRenew(ctx context.Context, ott string) (*ssh.Certificate, error) {
  472. if m.MauthorizeRenew != nil {
  473. return m.MauthorizeSSHRenew(ctx, ott)
  474. }
  475. return m.Mret1.(*ssh.Certificate), m.Merr
  476. }
  477. // AuthorizeSSHRekey mock
  478. func (m *MockProvisioner) AuthorizeSSHRekey(ctx context.Context, ott string) (*ssh.Certificate, []SignOption, error) {
  479. if m.MauthorizeSSHRekey != nil {
  480. return m.MauthorizeSSHRekey(ctx, ott)
  481. }
  482. return m.Mret1.(*ssh.Certificate), m.Mret2.([]SignOption), m.Merr
  483. }
  484. // AuthorizeSSHRevoke mock
  485. func (m *MockProvisioner) AuthorizeSSHRevoke(ctx context.Context, ott string) error {
  486. if m.MauthorizeSSHRevoke != nil {
  487. return m.MauthorizeSSHRevoke(ctx, ott)
  488. }
  489. return m.Merr
  490. }