nebula.go 13 KB

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