nebula.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. "math/big"
  11. "net"
  12. "time"
  13. "github.com/pkg/errors"
  14. nebula "github.com/slackhq/nebula/cert"
  15. "golang.org/x/crypto/ssh"
  16. "github.com/smallstep/linkedca"
  17. "go.step.sm/crypto/jose"
  18. "go.step.sm/crypto/sshutil"
  19. "go.step.sm/crypto/x25519"
  20. "go.step.sm/crypto/x509util"
  21. "github.com/smallstep/certificates/errs"
  22. "github.com/smallstep/certificates/internal/cast"
  23. )
  24. const (
  25. // NebulaCertHeader is the token header that contains a Nebula certificate.
  26. NebulaCertHeader jose.HeaderKey = "nebula"
  27. )
  28. // Nebula is a provisioner that verifies tokens signed using Nebula private
  29. // keys. The tokens contain a Nebula certificate in the header, which can be
  30. // used to verify the token signature. The certificates are themselves verified
  31. // using the Nebula CA certificates encoded in Roots. The verification process
  32. // is similar to the process for X5C tokens.
  33. //
  34. // Because Nebula "leaf" certificates use X25519 keys, the tokens are signed
  35. // using XEd25519 defined at
  36. // https://signal.org/docs/specifications/xeddsa/#xeddsa and implemented by
  37. // go.step.sm/crypto/x25519.
  38. type Nebula struct {
  39. ID string `json:"-"`
  40. Type string `json:"type"`
  41. Name string `json:"name"`
  42. Roots []byte `json:"roots"`
  43. Claims *Claims `json:"claims,omitempty"`
  44. Options *Options `json:"options,omitempty"`
  45. caPool *nebula.NebulaCAPool
  46. ctl *Controller
  47. }
  48. // Init verifies and initializes the Nebula provisioner.
  49. func (p *Nebula) Init(config Config) (err error) {
  50. switch {
  51. case p.Type == "":
  52. return errors.New("provisioner type cannot be empty")
  53. case p.Name == "":
  54. return errors.New("provisioner name cannot be empty")
  55. case len(p.Roots) == 0:
  56. return errors.New("provisioner root(s) cannot be empty")
  57. }
  58. var certErrors []error
  59. p.caPool, certErrors, err = nebula.NewCAPoolFromBytes(p.Roots)
  60. if err != nil {
  61. return errs.InternalServer("failed to create CA pool: %v", err)
  62. }
  63. if len(certErrors) > 0 {
  64. return errs.InternalServer("failed to create CA pool: %v", certErrors)
  65. }
  66. config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
  67. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  68. return
  69. }
  70. // GetID returns the provisioner id.
  71. func (p *Nebula) GetID() string {
  72. if p.ID != "" {
  73. return p.ID
  74. }
  75. return p.GetIDForToken()
  76. }
  77. // GetIDForToken returns an identifier that will be used to load the provisioner
  78. // from a token.
  79. func (p *Nebula) GetIDForToken() string {
  80. return "nebula/" + p.Name
  81. }
  82. // GetTokenID returns the identifier of the token.
  83. func (p *Nebula) GetTokenID(token string) (string, error) {
  84. // Validate payload
  85. t, err := jose.ParseSigned(token)
  86. if err != nil {
  87. return "", errors.Wrap(err, "error parsing token")
  88. }
  89. // Get claims w/out verification. We need to look up the provisioner
  90. // key in order to verify the claims and we need the issuer from the claims
  91. // before we can look up the provisioner.
  92. var claims jose.Claims
  93. if err = t.UnsafeClaimsWithoutVerification(&claims); err != nil {
  94. return "", errors.Wrap(err, "error verifying claims")
  95. }
  96. return claims.ID, nil
  97. }
  98. // GetName returns the name of the provisioner.
  99. func (p *Nebula) GetName() string {
  100. return p.Name
  101. }
  102. // GetType returns the type of provisioner.
  103. func (p *Nebula) GetType() Type {
  104. return TypeNebula
  105. }
  106. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  107. func (p *Nebula) GetEncryptedKey() (kid, key string, ok bool) {
  108. return "", "", false
  109. }
  110. // AuthorizeSign returns the list of SignOption for a Sign request.
  111. func (p *Nebula) AuthorizeSign(_ context.Context, token string) ([]SignOption, error) {
  112. crt, claims, err := p.authorizeToken(token, p.ctl.Audiences.Sign)
  113. if err != nil {
  114. return nil, err
  115. }
  116. sans := claims.SANs
  117. if len(sans) == 0 {
  118. sans = make([]string, len(crt.Details.Ips)+1)
  119. sans[0] = crt.Details.Name
  120. for i, ipnet := range crt.Details.Ips {
  121. sans[i+1] = ipnet.IP.String()
  122. }
  123. }
  124. data := x509util.CreateTemplateData(claims.Subject, sans)
  125. if v, err := unsafeParseSigned(token); err == nil {
  126. data.SetToken(v)
  127. }
  128. // The Nebula certificate will be available using the template variable
  129. // AuthorizationCrt. For example {{ .AuthorizationCrt.Details.Groups }} can
  130. // be used to get all the groups.
  131. data.SetAuthorizationCertificate(crt)
  132. templateOptions, err := TemplateOptions(p.Options, data)
  133. if err != nil {
  134. return nil, err
  135. }
  136. return []SignOption{
  137. p,
  138. templateOptions,
  139. // modifiers / withOptions
  140. newProvisionerExtensionOption(TypeNebula, p.Name, "").WithControllerOptions(p.ctl),
  141. profileLimitDuration{
  142. def: p.ctl.Claimer.DefaultTLSCertDuration(),
  143. notBefore: crt.Details.NotBefore,
  144. notAfter: crt.Details.NotAfter,
  145. },
  146. // validators
  147. commonNameValidator(claims.Subject),
  148. nebulaSANsValidator{
  149. Name: crt.Details.Name,
  150. IPs: crt.Details.Ips,
  151. },
  152. defaultPublicKeyValidator{},
  153. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  154. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  155. p.ctl.newWebhookController(data, linkedca.Webhook_X509),
  156. }, nil
  157. }
  158. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  159. // Currently the Nebula provisioner only grants host SSH certificates.
  160. func (p *Nebula) AuthorizeSSHSign(_ context.Context, token string) ([]SignOption, error) {
  161. if !p.ctl.Claimer.IsSSHCAEnabled() {
  162. return nil, errs.Unauthorized("ssh is disabled for nebula provisioner '%s'", p.Name)
  163. }
  164. crt, claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  165. if err != nil {
  166. return nil, err
  167. }
  168. // Default template attributes.
  169. keyID := claims.Subject
  170. principals := make([]string, len(crt.Details.Ips)+1)
  171. principals[0] = crt.Details.Name
  172. for i, ipnet := range crt.Details.Ips {
  173. principals[i+1] = ipnet.IP.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.Details.Name,
  183. IPs: crt.Details.Ips,
  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.Details.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 error if the token is not valid.
  251. func (p *Nebula) AuthorizeRevoke(_ context.Context, token string) error {
  252. return p.validateToken(token, p.ctl.Audiences.Revoke)
  253. }
  254. // AuthorizeSSHRevoke returns an error if SSH is disabled or the token is invalid.
  255. func (p *Nebula) AuthorizeSSHRevoke(_ context.Context, token string) error {
  256. if !p.ctl.Claimer.IsSSHCAEnabled() {
  257. return errs.Unauthorized("ssh is disabled for nebula provisioner '%s'", p.Name)
  258. }
  259. if _, _, err := p.authorizeToken(token, p.ctl.Audiences.SSHRevoke); err != nil {
  260. return err
  261. }
  262. return nil
  263. }
  264. // AuthorizeSSHRenew returns an unauthorized error.
  265. func (p *Nebula) AuthorizeSSHRenew(context.Context, string) (*ssh.Certificate, error) {
  266. return nil, errs.Unauthorized("nebula provisioner does not support SSH renew")
  267. }
  268. // AuthorizeSSHRekey returns an unauthorized error.
  269. func (p *Nebula) AuthorizeSSHRekey(context.Context, string) (*ssh.Certificate, []SignOption, error) {
  270. return nil, nil, errs.Unauthorized("nebula provisioner does not support SSH rekey")
  271. }
  272. func (p *Nebula) validateToken(token string, audiences []string) error {
  273. _, _, err := p.authorizeToken(token, audiences)
  274. return err
  275. }
  276. func (p *Nebula) authorizeToken(token string, audiences []string) (*nebula.NebulaCertificate, *jwtPayload, error) {
  277. jwt, err := jose.ParseSigned(token)
  278. if err != nil {
  279. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse token"))
  280. }
  281. // Extract Nebula certificate
  282. h, ok := jwt.Headers[0].ExtraHeaders[NebulaCertHeader]
  283. if !ok {
  284. return nil, nil, errs.Unauthorized("failed to parse token: nebula header is missing")
  285. }
  286. s, ok := h.(string)
  287. if !ok {
  288. return nil, nil, errs.Unauthorized("failed to parse token: nebula header is not valid")
  289. }
  290. b, err := base64.StdEncoding.DecodeString(s)
  291. if err != nil {
  292. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse token: nebula header is not valid"))
  293. }
  294. c, err := nebula.UnmarshalNebulaCertificate(b)
  295. if err != nil {
  296. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse nebula certificate: nebula header is not valid"))
  297. }
  298. // Validate nebula certificate against CAs
  299. if valid, err := c.Verify(now(), p.caPool); !valid {
  300. if err != nil {
  301. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: failed to verify certificate against configured CA"))
  302. }
  303. return nil, nil, errs.Unauthorized("token is not valid: failed to verify certificate against configured CA")
  304. }
  305. var pub any
  306. switch {
  307. case c.Details.Curve == nebula.Curve_P256:
  308. // When Nebula is used with ECDSA P-256 keys, both CAs and clients use the same type.
  309. ecdhPub, err := ecdh.P256().NewPublicKey(c.Details.PublicKey)
  310. if err != nil {
  311. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse nebula public key"))
  312. }
  313. publicKeyBytes := ecdhPub.Bytes()
  314. pub = &ecdsa.PublicKey{ // convert back to *ecdsa.PublicKey, because our jose package nor go-jose supports *ecdh.PublicKey
  315. Curve: elliptic.P256(),
  316. X: big.NewInt(0).SetBytes(publicKeyBytes[1:33]),
  317. Y: big.NewInt(0).SetBytes(publicKeyBytes[33:]),
  318. }
  319. case c.Details.IsCA:
  320. pub = ed25519.PublicKey(c.Details.PublicKey)
  321. default:
  322. pub = x25519.PublicKey(c.Details.PublicKey)
  323. }
  324. // Validate token with public key
  325. var claims jwtPayload
  326. if err := jose.Verify(jwt, pub, &claims); err != nil {
  327. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: signature does not match"))
  328. }
  329. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  330. // more than a few minutes.
  331. if err = claims.ValidateWithLeeway(jose.Expected{
  332. Issuer: p.Name,
  333. Time: now(),
  334. }, time.Minute); err != nil {
  335. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: invalid claims"))
  336. }
  337. // Validate token and subject too.
  338. if !matchesAudience(claims.Audience, audiences) {
  339. return nil, nil, errs.Unauthorized("token is not valid: invalid claims")
  340. }
  341. if claims.Subject == "" {
  342. return nil, nil, errs.Unauthorized("token is not valid: subject cannot be empty")
  343. }
  344. return c, &claims, nil
  345. }
  346. type nebulaSANsValidator struct {
  347. Name string
  348. IPs []*net.IPNet
  349. }
  350. // Valid verifies that the SANs stored in the validator are contained with those
  351. // requested in the x509 certificate request.
  352. func (v nebulaSANsValidator) Valid(req *x509.CertificateRequest) error {
  353. dnsNames, ips, emails, uris := x509util.SplitSANs([]string{v.Name})
  354. if len(req.DNSNames) > 0 {
  355. if err := dnsNamesValidator(dnsNames).Valid(req); err != nil {
  356. return err
  357. }
  358. }
  359. if len(req.EmailAddresses) > 0 {
  360. if err := emailAddressesValidator(emails).Valid(req); err != nil {
  361. return err
  362. }
  363. }
  364. if len(req.URIs) > 0 {
  365. if err := newURIsValidator(context.Background(), uris).Valid(req); err != nil {
  366. return err
  367. }
  368. }
  369. if len(req.IPAddresses) > 0 {
  370. for _, ip := range req.IPAddresses {
  371. var valid bool
  372. // Check ip in name
  373. for _, ipInName := range ips {
  374. if ip.Equal(ipInName) {
  375. valid = true
  376. break
  377. }
  378. }
  379. // Check ip network
  380. if !valid {
  381. for _, ipNet := range v.IPs {
  382. if ip.Equal(ipNet.IP) {
  383. valid = true
  384. break
  385. }
  386. }
  387. }
  388. if !valid {
  389. for _, ipNet := range v.IPs {
  390. ips = append(ips, ipNet.IP)
  391. }
  392. return errs.Forbidden("certificate request contains invalid IP addresses - got %v, want %v", req.IPAddresses, ips)
  393. }
  394. }
  395. }
  396. return nil
  397. }
  398. type nebulaPrincipalsValidator struct {
  399. Name string
  400. IPs []*net.IPNet
  401. }
  402. // Valid checks that the SignSSHOptions principals contains only names in the
  403. // Nebula certificate.
  404. func (v nebulaPrincipalsValidator) Valid(got SignSSHOptions) error {
  405. for _, p := range got.Principals {
  406. var valid bool
  407. if p == v.Name {
  408. valid = true
  409. }
  410. if !valid {
  411. if ip := net.ParseIP(p); ip != nil {
  412. for _, ipnet := range v.IPs {
  413. if ip.Equal(ipnet.IP) {
  414. valid = true
  415. break
  416. }
  417. }
  418. }
  419. }
  420. if !valid {
  421. ips := make([]net.IP, len(v.IPs))
  422. for i, ipNet := range v.IPs {
  423. ips[i] = ipNet.IP
  424. }
  425. return errs.Forbidden(
  426. "ssh certificate principals contains invalid name or IP addresses - got %v, want %s or %v",
  427. got.Principals, v.Name, ips,
  428. )
  429. }
  430. }
  431. return nil
  432. }