nebula.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. templateOptions,
  128. // modifiers / withOptions
  129. newProvisionerExtensionOption(TypeNebula, p.Name, ""),
  130. profileLimitDuration{
  131. def: p.ctl.Claimer.DefaultTLSCertDuration(),
  132. notBefore: crt.Details.NotBefore,
  133. notAfter: crt.Details.NotAfter,
  134. },
  135. // validators
  136. commonNameValidator(claims.Subject),
  137. nebulaSANsValidator{
  138. Name: crt.Details.Name,
  139. IPs: crt.Details.Ips,
  140. },
  141. defaultPublicKeyValidator{},
  142. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  143. }, nil
  144. }
  145. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  146. // Currently the Nebula provisioner only grants host SSH certificates.
  147. func (p *Nebula) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  148. if !p.ctl.Claimer.IsSSHCAEnabled() {
  149. return nil, errs.Unauthorized("ssh is disabled for nebula provisioner '%s'", p.Name)
  150. }
  151. crt, claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  152. if err != nil {
  153. return nil, err
  154. }
  155. // Default template attributes.
  156. keyID := claims.Subject
  157. principals := make([]string, len(crt.Details.Ips)+1)
  158. principals[0] = crt.Details.Name
  159. for i, ipnet := range crt.Details.Ips {
  160. principals[i+1] = ipnet.IP.String()
  161. }
  162. var signOptions []SignOption
  163. // If step ssh options are given, validate them and set key id, principals
  164. // and validity.
  165. if claims.Step != nil && claims.Step.SSH != nil {
  166. opts := claims.Step.SSH
  167. // Check that the token only contains valid principals.
  168. v := nebulaPrincipalsValidator{
  169. Name: crt.Details.Name,
  170. IPs: crt.Details.Ips,
  171. }
  172. if err := v.Valid(*opts); err != nil {
  173. return nil, err
  174. }
  175. // Check that the cert type is a valid one.
  176. if opts.CertType != "" && opts.CertType != SSHHostCert {
  177. return nil, errs.Forbidden("ssh certificate type does not match - got %v, want %v", opts.CertType, SSHHostCert)
  178. }
  179. signOptions = []SignOption{
  180. // validate is a host certificate and users's KeyID is the subject.
  181. sshCertOptionsValidator(SignSSHOptions{
  182. CertType: SSHHostCert,
  183. KeyID: claims.Subject,
  184. }),
  185. // validates user's SSHOptions with the ones in the token
  186. sshCertOptionsValidator(*opts),
  187. }
  188. // Use options in the token.
  189. if opts.KeyID != "" {
  190. keyID = opts.KeyID
  191. }
  192. if len(opts.Principals) > 0 {
  193. principals = opts.Principals
  194. }
  195. // Add modifiers from custom claims
  196. t := now()
  197. if !opts.ValidAfter.IsZero() {
  198. signOptions = append(signOptions, sshCertValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
  199. }
  200. if !opts.ValidBefore.IsZero() {
  201. signOptions = append(signOptions, sshCertValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
  202. }
  203. }
  204. // Certificate templates.
  205. data := sshutil.CreateTemplateData(sshutil.HostCert, keyID, principals)
  206. if v, err := unsafeParseSigned(token); err == nil {
  207. data.SetToken(v)
  208. }
  209. // The Nebula certificate will be available using the template variable Crt.
  210. // For example {{ .AuthorizationCrt.Details.Groups }} can be used to get all the groups.
  211. data.SetAuthorizationCertificate(crt)
  212. templateOptions, err := TemplateSSHOptions(p.Options, data)
  213. if err != nil {
  214. return nil, err
  215. }
  216. return append(signOptions,
  217. templateOptions,
  218. // Checks the validity bounds, and set the validity if has not been set.
  219. &sshLimitDuration{p.ctl.Claimer, crt.Details.NotAfter},
  220. // Validate public key.
  221. &sshDefaultPublicKeyValidator{},
  222. // Validate the validity period.
  223. &sshCertValidityValidator{p.ctl.Claimer},
  224. // Require all the fields in the SSH certificate
  225. &sshCertDefaultValidator{},
  226. ), nil
  227. }
  228. // AuthorizeRenew returns an error if the renewal is disabled.
  229. func (p *Nebula) AuthorizeRenew(ctx context.Context, crt *x509.Certificate) error {
  230. return p.ctl.AuthorizeRenew(ctx, crt)
  231. }
  232. // AuthorizeRevoke returns an error if the token is not valid.
  233. func (p *Nebula) AuthorizeRevoke(ctx context.Context, token string) error {
  234. return p.validateToken(token, p.ctl.Audiences.Revoke)
  235. }
  236. // AuthorizeSSHRevoke returns an error if SSH is disabled or the token is invalid.
  237. func (p *Nebula) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  238. if !p.ctl.Claimer.IsSSHCAEnabled() {
  239. return errs.Unauthorized("ssh is disabled for nebula provisioner '%s'", p.Name)
  240. }
  241. if _, _, err := p.authorizeToken(token, p.ctl.Audiences.SSHRevoke); err != nil {
  242. return err
  243. }
  244. return nil
  245. }
  246. // AuthorizeSSHRenew returns an unauthorized error.
  247. func (p *Nebula) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  248. return nil, errs.Unauthorized("nebula provisioner does not support SSH renew")
  249. }
  250. // AuthorizeSSHRekey returns an unauthorized error.
  251. func (p *Nebula) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  252. return nil, nil, errs.Unauthorized("nebula provisioner does not support SSH rekey")
  253. }
  254. func (p *Nebula) validateToken(token string, audiences []string) error {
  255. _, _, err := p.authorizeToken(token, audiences)
  256. return err
  257. }
  258. func (p *Nebula) authorizeToken(token string, audiences []string) (*nebula.NebulaCertificate, *jwtPayload, error) {
  259. jwt, err := jose.ParseSigned(token)
  260. if err != nil {
  261. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse token"))
  262. }
  263. // Extract Nebula certificate
  264. h, ok := jwt.Headers[0].ExtraHeaders[NebulaCertHeader]
  265. if !ok {
  266. return nil, nil, errs.Unauthorized("failed to parse token: nebula header is missing")
  267. }
  268. s, ok := h.(string)
  269. if !ok {
  270. return nil, nil, errs.Unauthorized("failed to parse token: nebula header is not valid")
  271. }
  272. b, err := base64.StdEncoding.DecodeString(s)
  273. if err != nil {
  274. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse token: nebula header is not valid"))
  275. }
  276. c, err := nebula.UnmarshalNebulaCertificate(b)
  277. if err != nil {
  278. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("failed to parse nebula certificate: nebula header is not valid"))
  279. }
  280. // Validate nebula certificate against CAs
  281. if valid, err := c.Verify(now(), p.caPool); !valid {
  282. if err != nil {
  283. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: failed to verify certificate against configured CA"))
  284. }
  285. return nil, nil, errs.Unauthorized("token is not valid: failed to verify certificate against configured CA")
  286. }
  287. var pub interface{}
  288. if c.Details.IsCA {
  289. pub = ed25519.PublicKey(c.Details.PublicKey)
  290. } else {
  291. pub = x25519.PublicKey(c.Details.PublicKey)
  292. }
  293. // Validate token with public key
  294. var claims jwtPayload
  295. if err := jose.Verify(jwt, pub, &claims); err != nil {
  296. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: signature does not match"))
  297. }
  298. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  299. // more than a few minutes.
  300. if err = claims.ValidateWithLeeway(jose.Expected{
  301. Issuer: p.Name,
  302. Time: now(),
  303. }, time.Minute); err != nil {
  304. return nil, nil, errs.UnauthorizedErr(err, errs.WithMessage("token is not valid: invalid claims"))
  305. }
  306. // Validate token and subject too.
  307. if !matchesAudience(claims.Audience, audiences) {
  308. return nil, nil, errs.Unauthorized("token is not valid: invalid claims")
  309. }
  310. if claims.Subject == "" {
  311. return nil, nil, errs.Unauthorized("token is not valid: subject cannot be empty")
  312. }
  313. return c, &claims, nil
  314. }
  315. type nebulaSANsValidator struct {
  316. Name string
  317. IPs []*net.IPNet
  318. }
  319. // Valid verifies that the SANs stored in the validator are contained with those
  320. // requested in the x509 certificate request.
  321. func (v nebulaSANsValidator) Valid(req *x509.CertificateRequest) error {
  322. dnsNames, ips, emails, uris := x509util.SplitSANs([]string{v.Name})
  323. if len(req.DNSNames) > 0 {
  324. if err := dnsNamesValidator(dnsNames).Valid(req); err != nil {
  325. return err
  326. }
  327. }
  328. if len(req.EmailAddresses) > 0 {
  329. if err := emailAddressesValidator(emails).Valid(req); err != nil {
  330. return err
  331. }
  332. }
  333. if len(req.URIs) > 0 {
  334. if err := urisValidator(uris).Valid(req); err != nil {
  335. return err
  336. }
  337. }
  338. if len(req.IPAddresses) > 0 {
  339. for _, ip := range req.IPAddresses {
  340. var valid bool
  341. // Check ip in name
  342. for _, ipInName := range ips {
  343. if ip.Equal(ipInName) {
  344. valid = true
  345. break
  346. }
  347. }
  348. // Check ip network
  349. if !valid {
  350. for _, ipNet := range v.IPs {
  351. if ip.Equal(ipNet.IP) {
  352. valid = true
  353. break
  354. }
  355. }
  356. }
  357. if !valid {
  358. for _, ipNet := range v.IPs {
  359. ips = append(ips, ipNet.IP)
  360. }
  361. return errs.Forbidden("certificate request contains invalid IP addresses - got %v, want %v", req.IPAddresses, ips)
  362. }
  363. }
  364. }
  365. return nil
  366. }
  367. type nebulaPrincipalsValidator struct {
  368. Name string
  369. IPs []*net.IPNet
  370. }
  371. // Valid checks that the SignSSHOptions principals contains only names in the
  372. // Nebula certificate.
  373. func (v nebulaPrincipalsValidator) Valid(got SignSSHOptions) error {
  374. for _, p := range got.Principals {
  375. var valid bool
  376. if p == v.Name {
  377. valid = true
  378. }
  379. if !valid {
  380. if ip := net.ParseIP(p); ip != nil {
  381. for _, ipnet := range v.IPs {
  382. if ip.Equal(ipnet.IP) {
  383. valid = true
  384. break
  385. }
  386. }
  387. }
  388. }
  389. if !valid {
  390. ips := make([]net.IP, len(v.IPs))
  391. for i, ipNet := range v.IPs {
  392. ips[i] = ipNet.IP
  393. }
  394. return errs.Forbidden(
  395. "ssh certificate principals contains invalid name or IP addresses - got %v, want %s or %v",
  396. got.Principals, v.Name, ips,
  397. )
  398. }
  399. }
  400. return nil
  401. }