nebula.go 14 KB

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