nebula.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/ed25519"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "net"
  8. "time"
  9. "github.com/pkg/errors"
  10. nebula "github.com/slackhq/nebula/cert"
  11. "go.step.sm/crypto/jose"
  12. "go.step.sm/crypto/sshutil"
  13. "go.step.sm/crypto/x25519"
  14. "go.step.sm/crypto/x509util"
  15. "go.step.sm/linkedca"
  16. "golang.org/x/crypto/ssh"
  17. "github.com/smallstep/certificates/errs"
  18. )
  19. const (
  20. // NebulaCertHeader is the token header that contains a Nebula certificate.
  21. NebulaCertHeader jose.HeaderKey = "nebula"
  22. )
  23. // Nebula is a provisioner that verifies tokens signed using Nebula private
  24. // keys. The tokens contain a Nebula certificate in the header, which can be
  25. // used to verify the token signature. The certificates are themselves verified
  26. // using the Nebula CA certificates encoded in Roots. The verification process
  27. // is similar to the process for X5C tokens.
  28. //
  29. // Because Nebula "leaf" certificates use X25519 keys, the tokens are signed
  30. // using XEd25519 defined at
  31. // https://signal.org/docs/specifications/xeddsa/#xeddsa and implemented by
  32. // go.step.sm/crypto/x25519.
  33. type Nebula struct {
  34. ID string `json:"-"`
  35. Type string `json:"type"`
  36. Name string `json:"name"`
  37. Roots []byte `json:"roots"`
  38. Claims *Claims `json:"claims,omitempty"`
  39. Options *Options `json:"options,omitempty"`
  40. caPool *nebula.NebulaCAPool
  41. ctl *Controller
  42. }
  43. // Init verifies and initializes the Nebula provisioner.
  44. func (p *Nebula) Init(config Config) (err error) {
  45. switch {
  46. case p.Type == "":
  47. return errors.New("provisioner type cannot be empty")
  48. case p.Name == "":
  49. return errors.New("provisioner name cannot be empty")
  50. case len(p.Roots) == 0:
  51. return errors.New("provisioner root(s) cannot be empty")
  52. }
  53. p.caPool, err = nebula.NewCAPoolFromBytes(p.Roots)
  54. if err != nil {
  55. return errs.InternalServer("failed to create ca pool: %v", err)
  56. }
  57. config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
  58. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  59. return
  60. }
  61. // GetID returns the provisioner id.
  62. func (p *Nebula) GetID() string {
  63. if p.ID != "" {
  64. return p.ID
  65. }
  66. return p.GetIDForToken()
  67. }
  68. // GetIDForToken returns an identifier that will be used to load the provisioner
  69. // from a token.
  70. func (p *Nebula) GetIDForToken() string {
  71. return "nebula/" + p.Name
  72. }
  73. // GetTokenID returns the identifier of the token.
  74. func (p *Nebula) GetTokenID(token string) (string, error) {
  75. // Validate payload
  76. t, err := jose.ParseSigned(token)
  77. if err != nil {
  78. return "", errors.Wrap(err, "error parsing token")
  79. }
  80. // Get claims w/out verification. We need to look up the provisioner
  81. // key in order to verify the claims and we need the issuer from the claims
  82. // before we can look up the provisioner.
  83. var claims jose.Claims
  84. if err = t.UnsafeClaimsWithoutVerification(&claims); err != nil {
  85. return "", errors.Wrap(err, "error verifying claims")
  86. }
  87. return claims.ID, nil
  88. }
  89. // GetName returns the name of the provisioner.
  90. func (p *Nebula) GetName() string {
  91. return p.Name
  92. }
  93. // GetType returns the type of provisioner.
  94. func (p *Nebula) GetType() Type {
  95. return TypeNebula
  96. }
  97. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  98. func (p *Nebula) GetEncryptedKey() (kid, key string, ok bool) {
  99. return "", "", false
  100. }
  101. // AuthorizeSign returns the list of SignOption for a Sign request.
  102. func (p *Nebula) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  103. crt, claims, err := p.authorizeToken(token, p.ctl.Audiences.Sign)
  104. if err != nil {
  105. return nil, err
  106. }
  107. sans := claims.SANs
  108. if len(sans) == 0 {
  109. sans = make([]string, len(crt.Details.Ips)+1)
  110. sans[0] = crt.Details.Name
  111. for i, ipnet := range crt.Details.Ips {
  112. sans[i+1] = ipnet.IP.String()
  113. }
  114. }
  115. data := x509util.CreateTemplateData(claims.Subject, sans)
  116. if v, err := unsafeParseSigned(token); err == nil {
  117. data.SetToken(v)
  118. }
  119. // The Nebula certificate will be available using the template variable
  120. // AuthorizationCrt. For example {{ .AuthorizationCrt.Details.Groups }} can
  121. // be used to get all the groups.
  122. data.SetAuthorizationCertificate(crt)
  123. templateOptions, err := TemplateOptions(p.Options, data)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return []SignOption{
  128. p,
  129. templateOptions,
  130. // modifiers / withOptions
  131. newProvisionerExtensionOption(TypeNebula, p.Name, ""),
  132. profileLimitDuration{
  133. def: p.ctl.Claimer.DefaultTLSCertDuration(),
  134. notBefore: crt.Details.NotBefore,
  135. notAfter: crt.Details.NotAfter,
  136. },
  137. // validators
  138. commonNameValidator(claims.Subject),
  139. nebulaSANsValidator{
  140. Name: crt.Details.Name,
  141. IPs: crt.Details.Ips,
  142. },
  143. defaultPublicKeyValidator{},
  144. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  145. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  146. p.ctl.newWebhookController(data, linkedca.Webhook_X509),
  147. }, nil
  148. }
  149. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  150. // Currently the Nebula provisioner only grants host SSH certificates.
  151. func (p *Nebula) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  152. if !p.ctl.Claimer.IsSSHCAEnabled() {
  153. return nil, errs.Unauthorized("ssh is disabled for nebula provisioner '%s'", p.Name)
  154. }
  155. crt, claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  156. if err != nil {
  157. return nil, err
  158. }
  159. // Default template attributes.
  160. keyID := claims.Subject
  161. principals := make([]string, len(crt.Details.Ips)+1)
  162. principals[0] = crt.Details.Name
  163. for i, ipnet := range crt.Details.Ips {
  164. principals[i+1] = ipnet.IP.String()
  165. }
  166. var signOptions []SignOption
  167. // If step ssh options are given, validate them and set key id, principals
  168. // and validity.
  169. if claims.Step != nil && claims.Step.SSH != nil {
  170. opts := claims.Step.SSH
  171. // Check that the token only contains valid principals.
  172. v := nebulaPrincipalsValidator{
  173. Name: crt.Details.Name,
  174. IPs: crt.Details.Ips,
  175. }
  176. if err := v.Valid(*opts); err != nil {
  177. return nil, err
  178. }
  179. // Check that the cert type is a valid one.
  180. if opts.CertType != "" && opts.CertType != SSHHostCert {
  181. return nil, errs.Forbidden("ssh certificate type does not match - got %v, want %v", opts.CertType, SSHHostCert)
  182. }
  183. signOptions = []SignOption{
  184. // validate is a host certificate and users's KeyID is the subject.
  185. sshCertOptionsValidator(SignSSHOptions{
  186. CertType: SSHHostCert,
  187. KeyID: claims.Subject,
  188. }),
  189. // validates user's SSHOptions with the ones in the token
  190. sshCertOptionsValidator(*opts),
  191. }
  192. // Use options in the token.
  193. if opts.KeyID != "" {
  194. keyID = opts.KeyID
  195. }
  196. if len(opts.Principals) > 0 {
  197. principals = opts.Principals
  198. }
  199. // Add modifiers from custom claims
  200. t := now()
  201. if !opts.ValidAfter.IsZero() {
  202. signOptions = append(signOptions, sshCertValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
  203. }
  204. if !opts.ValidBefore.IsZero() {
  205. signOptions = append(signOptions, sshCertValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
  206. }
  207. }
  208. // Certificate templates.
  209. data := sshutil.CreateTemplateData(sshutil.HostCert, keyID, principals)
  210. if v, err := unsafeParseSigned(token); err == nil {
  211. data.SetToken(v)
  212. }
  213. // The Nebula certificate will be available using the template variable Crt.
  214. // For example {{ .AuthorizationCrt.Details.Groups }} can be used to get all the groups.
  215. data.SetAuthorizationCertificate(crt)
  216. templateOptions, err := TemplateSSHOptions(p.Options, data)
  217. if err != nil {
  218. return nil, err
  219. }
  220. return append(signOptions,
  221. p,
  222. templateOptions,
  223. // Checks the validity bounds, and set the validity if has not been set.
  224. &sshLimitDuration{p.ctl.Claimer, crt.Details.NotAfter},
  225. // Validate public key.
  226. &sshDefaultPublicKeyValidator{},
  227. // Validate the validity period.
  228. &sshCertValidityValidator{p.ctl.Claimer},
  229. // Require all the fields in the SSH certificate
  230. &sshCertDefaultValidator{},
  231. // Ensure that all principal names are allowed
  232. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), nil),
  233. // Call webhooks
  234. p.ctl.newWebhookController(data, linkedca.Webhook_SSH),
  235. ), nil
  236. }
  237. // AuthorizeRenew returns an error if the renewal is disabled.
  238. func (p *Nebula) AuthorizeRenew(ctx context.Context, crt *x509.Certificate) error {
  239. return p.ctl.AuthorizeRenew(ctx, crt)
  240. }
  241. // AuthorizeRevoke returns an error if the token is not valid.
  242. func (p *Nebula) AuthorizeRevoke(ctx context.Context, token string) error {
  243. return p.validateToken(token, p.ctl.Audiences.Revoke)
  244. }
  245. // AuthorizeSSHRevoke returns an error if SSH is disabled or the token is invalid.
  246. func (p *Nebula) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  247. if !p.ctl.Claimer.IsSSHCAEnabled() {
  248. return errs.Unauthorized("ssh is disabled for nebula provisioner '%s'", p.Name)
  249. }
  250. if _, _, err := p.authorizeToken(token, p.ctl.Audiences.SSHRevoke); err != nil {
  251. return err
  252. }
  253. return nil
  254. }
  255. // AuthorizeSSHRenew returns an unauthorized error.
  256. func (p *Nebula) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  257. return nil, errs.Unauthorized("nebula provisioner does not support SSH renew")
  258. }
  259. // AuthorizeSSHRekey returns an unauthorized error.
  260. func (p *Nebula) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  261. return nil, nil, errs.Unauthorized("nebula provisioner does not support SSH rekey")
  262. }
  263. func (p *Nebula) validateToken(token string, audiences []string) error {
  264. _, _, err := p.authorizeToken(token, audiences)
  265. return err
  266. }
  267. func (p *Nebula) authorizeToken(token string, audiences []string) (*nebula.NebulaCertificate, *jwtPayload, error) {
  268. jwt, err := jose.ParseSigned(token)
  269. if err != nil {
  270. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse token"))
  271. }
  272. // Extract Nebula certificate
  273. h, ok := jwt.Headers[0].ExtraHeaders[NebulaCertHeader]
  274. if !ok {
  275. return nil, nil, errs.Unauthorized("failed to parse token: nebula header is missing")
  276. }
  277. s, ok := h.(string)
  278. if !ok {
  279. return nil, nil, errs.Unauthorized("failed to parse token: nebula header is not valid")
  280. }
  281. b, err := base64.StdEncoding.DecodeString(s)
  282. if err != nil {
  283. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse token: nebula header is not valid"))
  284. }
  285. c, err := nebula.UnmarshalNebulaCertificate(b)
  286. if err != nil {
  287. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse nebula certificate: nebula header is not valid"))
  288. }
  289. // Validate nebula certificate against CAs
  290. if valid, err := c.Verify(now(), p.caPool); !valid {
  291. if err != nil {
  292. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: failed to verify certificate against configured CA"))
  293. }
  294. return nil, nil, errs.Unauthorized("token is not valid: failed to verify certificate against configured CA")
  295. }
  296. var pub interface{}
  297. if c.Details.IsCA {
  298. pub = ed25519.PublicKey(c.Details.PublicKey)
  299. } else {
  300. pub = x25519.PublicKey(c.Details.PublicKey)
  301. }
  302. // Validate token with public key
  303. var claims jwtPayload
  304. if err := jose.Verify(jwt, pub, &claims); err != nil {
  305. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: signature does not match"))
  306. }
  307. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  308. // more than a few minutes.
  309. if err = claims.ValidateWithLeeway(jose.Expected{
  310. Issuer: p.Name,
  311. Time: now(),
  312. }, time.Minute); err != nil {
  313. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: invalid claims"))
  314. }
  315. // Validate token and subject too.
  316. if !matchesAudience(claims.Audience, audiences) {
  317. return nil, nil, errs.Unauthorized("token is not valid: invalid claims")
  318. }
  319. if claims.Subject == "" {
  320. return nil, nil, errs.Unauthorized("token is not valid: subject cannot be empty")
  321. }
  322. return c, &claims, nil
  323. }
  324. type nebulaSANsValidator struct {
  325. Name string
  326. IPs []*net.IPNet
  327. }
  328. // Valid verifies that the SANs stored in the validator are contained with those
  329. // requested in the x509 certificate request.
  330. func (v nebulaSANsValidator) Valid(req *x509.CertificateRequest) error {
  331. dnsNames, ips, emails, uris := x509util.SplitSANs([]string{v.Name})
  332. if len(req.DNSNames) > 0 {
  333. if err := dnsNamesValidator(dnsNames).Valid(req); err != nil {
  334. return err
  335. }
  336. }
  337. if len(req.EmailAddresses) > 0 {
  338. if err := emailAddressesValidator(emails).Valid(req); err != nil {
  339. return err
  340. }
  341. }
  342. if len(req.URIs) > 0 {
  343. if err := urisValidator(uris).Valid(req); err != nil {
  344. return err
  345. }
  346. }
  347. if len(req.IPAddresses) > 0 {
  348. for _, ip := range req.IPAddresses {
  349. var valid bool
  350. // Check ip in name
  351. for _, ipInName := range ips {
  352. if ip.Equal(ipInName) {
  353. valid = true
  354. break
  355. }
  356. }
  357. // Check ip network
  358. if !valid {
  359. for _, ipNet := range v.IPs {
  360. if ip.Equal(ipNet.IP) {
  361. valid = true
  362. break
  363. }
  364. }
  365. }
  366. if !valid {
  367. for _, ipNet := range v.IPs {
  368. ips = append(ips, ipNet.IP)
  369. }
  370. return errs.Forbidden("certificate request contains invalid IP addresses - got %v, want %v", req.IPAddresses, ips)
  371. }
  372. }
  373. }
  374. return nil
  375. }
  376. type nebulaPrincipalsValidator struct {
  377. Name string
  378. IPs []*net.IPNet
  379. }
  380. // Valid checks that the SignSSHOptions principals contains only names in the
  381. // Nebula certificate.
  382. func (v nebulaPrincipalsValidator) Valid(got SignSSHOptions) error {
  383. for _, p := range got.Principals {
  384. var valid bool
  385. if p == v.Name {
  386. valid = true
  387. }
  388. if !valid {
  389. if ip := net.ParseIP(p); ip != nil {
  390. for _, ipnet := range v.IPs {
  391. if ip.Equal(ipnet.IP) {
  392. valid = true
  393. break
  394. }
  395. }
  396. }
  397. }
  398. if !valid {
  399. ips := make([]net.IP, len(v.IPs))
  400. for i, ipNet := range v.IPs {
  401. ips[i] = ipNet.IP
  402. }
  403. return errs.Forbidden(
  404. "ssh certificate principals contains invalid name or IP addresses - got %v, want %s or %v",
  405. got.Principals, v.Name, ips,
  406. )
  407. }
  408. }
  409. return nil
  410. }