nebula.go 13 KB

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