nebula.go 14 KB

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