provisioner.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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.Errorf("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 unimplmented 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 unimplmented 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 unimplmented 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 unimplmented 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 unimplmented 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 unimplmented 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 unimplmented 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. }
  303. // GetIdentityFunc is a function that returns an identity.
  304. type GetIdentityFunc func(p Interface, email string) (*Identity, error)
  305. // DefaultIdentityFunc return a default identity depending on the provisioner type.
  306. func DefaultIdentityFunc(p Interface, email string) (*Identity, error) {
  307. switch k := p.(type) {
  308. case *OIDC:
  309. name := SanitizeSSHUserPrincipal(email)
  310. if !sshUserRegex.MatchString(name) {
  311. return nil, errors.Errorf("invalid principal '%s' from email '%s'", name, email)
  312. }
  313. return &Identity{Usernames: []string{name, email}}, nil
  314. default:
  315. return nil, errors.Errorf("provisioner type '%T' not supported by identity function", k)
  316. }
  317. }
  318. // MockProvisioner for testing
  319. type MockProvisioner struct {
  320. Mret1, Mret2, Mret3 interface{}
  321. Merr error
  322. MgetID func() string
  323. MgetTokenID func(string) (string, error)
  324. MgetName func() string
  325. MgetType func() Type
  326. MgetEncryptedKey func() (string, string, bool)
  327. Minit func(Config) error
  328. MauthorizeSign func(ctx context.Context, ott string) ([]SignOption, error)
  329. MauthorizeRenew func(ctx context.Context, cert *x509.Certificate) error
  330. MauthorizeRevoke func(ctx context.Context, ott string) error
  331. MauthorizeSSHSign func(ctx context.Context, ott string) ([]SignOption, error)
  332. MauthorizeSSHRenew func(ctx context.Context, ott string) (*ssh.Certificate, error)
  333. MauthorizeSSHRekey func(ctx context.Context, ott string) (*ssh.Certificate, []SignOption, error)
  334. MauthorizeSSHRevoke func(ctx context.Context, ott string) error
  335. }
  336. // GetID mock
  337. func (m *MockProvisioner) GetID() string {
  338. if m.MgetID != nil {
  339. return m.MgetID()
  340. }
  341. return m.Mret1.(string)
  342. }
  343. // GetTokenID mock
  344. func (m *MockProvisioner) GetTokenID(token string) (string, error) {
  345. if m.MgetTokenID != nil {
  346. return m.MgetTokenID(token)
  347. }
  348. if m.Mret1 == nil {
  349. return "", m.Merr
  350. }
  351. return m.Mret1.(string), m.Merr
  352. }
  353. // GetName mock
  354. func (m *MockProvisioner) GetName() string {
  355. if m.MgetName != nil {
  356. return m.MgetName()
  357. }
  358. return m.Mret1.(string)
  359. }
  360. // GetType mock
  361. func (m *MockProvisioner) GetType() Type {
  362. if m.MgetType != nil {
  363. return m.MgetType()
  364. }
  365. return m.Mret1.(Type)
  366. }
  367. // GetEncryptedKey mock
  368. func (m *MockProvisioner) GetEncryptedKey() (string, string, bool) {
  369. if m.MgetEncryptedKey != nil {
  370. return m.MgetEncryptedKey()
  371. }
  372. return m.Mret1.(string), m.Mret2.(string), m.Mret3.(bool)
  373. }
  374. // Init mock
  375. func (m *MockProvisioner) Init(c Config) error {
  376. if m.Minit != nil {
  377. return m.Minit(c)
  378. }
  379. return m.Merr
  380. }
  381. // AuthorizeSign mock
  382. func (m *MockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]SignOption, error) {
  383. if m.MauthorizeSign != nil {
  384. return m.MauthorizeSign(ctx, ott)
  385. }
  386. return m.Mret1.([]SignOption), m.Merr
  387. }
  388. // AuthorizeRevoke mock
  389. func (m *MockProvisioner) AuthorizeRevoke(ctx context.Context, ott string) error {
  390. if m.MauthorizeRevoke != nil {
  391. return m.MauthorizeRevoke(ctx, ott)
  392. }
  393. return m.Merr
  394. }
  395. // AuthorizeRenew mock
  396. func (m *MockProvisioner) AuthorizeRenew(ctx context.Context, c *x509.Certificate) error {
  397. if m.MauthorizeRenew != nil {
  398. return m.MauthorizeRenew(ctx, c)
  399. }
  400. return m.Merr
  401. }
  402. // AuthorizeSSHSign mock
  403. func (m *MockProvisioner) AuthorizeSSHSign(ctx context.Context, ott string) ([]SignOption, error) {
  404. if m.MauthorizeSign != nil {
  405. return m.MauthorizeSign(ctx, ott)
  406. }
  407. return m.Mret1.([]SignOption), m.Merr
  408. }
  409. // AuthorizeSSHRenew mock
  410. func (m *MockProvisioner) AuthorizeSSHRenew(ctx context.Context, ott string) (*ssh.Certificate, error) {
  411. if m.MauthorizeRenew != nil {
  412. return m.MauthorizeSSHRenew(ctx, ott)
  413. }
  414. return m.Mret1.(*ssh.Certificate), m.Merr
  415. }
  416. // AuthorizeSSHRekey mock
  417. func (m *MockProvisioner) AuthorizeSSHRekey(ctx context.Context, ott string) (*ssh.Certificate, []SignOption, error) {
  418. if m.MauthorizeSSHRekey != nil {
  419. return m.MauthorizeSSHRekey(ctx, ott)
  420. }
  421. return m.Mret1.(*ssh.Certificate), m.Mret2.([]SignOption), m.Merr
  422. }
  423. // AuthorizeSSHRevoke mock
  424. func (m *MockProvisioner) AuthorizeSSHRevoke(ctx context.Context, ott string) error {
  425. if m.MauthorizeSSHRevoke != nil {
  426. return m.MauthorizeSSHRevoke(ctx, ott)
  427. }
  428. return m.Merr
  429. }