nebula.go 14 KB

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