provisioner.go 15 KB

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