aws.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "encoding/pem"
  10. "fmt"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "strings"
  15. "time"
  16. "github.com/pkg/errors"
  17. "github.com/smallstep/certificates/errs"
  18. "github.com/smallstep/cli/jose"
  19. )
  20. // awsIssuer is the string used as issuer in the generated tokens.
  21. const awsIssuer = "ec2.amazonaws.com"
  22. // awsIdentityURL is the url used to retrieve the instance identity document.
  23. const awsIdentityURL = "http://169.254.169.254/latest/dynamic/instance-identity/document"
  24. // awsSignatureURL is the url used to retrieve the instance identity signature.
  25. const awsSignatureURL = "http://169.254.169.254/latest/dynamic/instance-identity/signature"
  26. // awsCertificate is the certificate used to validate the instance identity
  27. // signature.
  28. const awsCertificate = `-----BEGIN CERTIFICATE-----
  29. MIIDIjCCAougAwIBAgIJAKnL4UEDMN/FMA0GCSqGSIb3DQEBBQUAMGoxCzAJBgNV
  30. BAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRgw
  31. FgYDVQQKEw9BbWF6b24uY29tIEluYy4xGjAYBgNVBAMTEWVjMi5hbWF6b25hd3Mu
  32. Y29tMB4XDTE0MDYwNTE0MjgwMloXDTI0MDYwNTE0MjgwMlowajELMAkGA1UEBhMC
  33. VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxGDAWBgNV
  34. BAoTD0FtYXpvbi5jb20gSW5jLjEaMBgGA1UEAxMRZWMyLmFtYXpvbmF3cy5jb20w
  35. gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIe9GN//SRK2knbjySG0ho3yqQM3
  36. e2TDhWO8D2e8+XZqck754gFSo99AbT2RmXClambI7xsYHZFapbELC4H91ycihvrD
  37. jbST1ZjkLQgga0NE1q43eS68ZeTDccScXQSNivSlzJZS8HJZjgqzBlXjZftjtdJL
  38. XeE4hwvo0sD4f3j9AgMBAAGjgc8wgcwwHQYDVR0OBBYEFCXWzAgVyrbwnFncFFIs
  39. 77VBdlE4MIGcBgNVHSMEgZQwgZGAFCXWzAgVyrbwnFncFFIs77VBdlE4oW6kbDBq
  40. MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh
  41. dHRsZTEYMBYGA1UEChMPQW1hem9uLmNvbSBJbmMuMRowGAYDVQQDExFlYzIuYW1h
  42. em9uYXdzLmNvbYIJAKnL4UEDMN/FMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEF
  43. BQADgYEAFYcz1OgEhQBXIwIdsgCOS8vEtiJYF+j9uO6jz7VOmJqO+pRlAbRlvY8T
  44. C1haGgSI/A1uZUKs/Zfnph0oEI0/hu1IIJ/SKBDtN5lvmZ/IzbOPIJWirlsllQIQ
  45. 7zvWbGd9c9+Rm3p04oTvhup99la7kZqevJK0QRdD/6NpCKsqP/0=
  46. -----END CERTIFICATE-----`
  47. // awsSignatureAlgorithm is the signature algorithm used to verify the identity
  48. // document signature.
  49. const awsSignatureAlgorithm = x509.SHA256WithRSA
  50. type awsConfig struct {
  51. identityURL string
  52. signatureURL string
  53. certificate *x509.Certificate
  54. signatureAlgorithm x509.SignatureAlgorithm
  55. }
  56. func newAWSConfig() (*awsConfig, error) {
  57. block, _ := pem.Decode([]byte(awsCertificate))
  58. if block == nil || block.Type != "CERTIFICATE" {
  59. return nil, errors.New("error decoding AWS certificate")
  60. }
  61. cert, err := x509.ParseCertificate(block.Bytes)
  62. if err != nil {
  63. return nil, errors.Wrap(err, "error parsing AWS certificate")
  64. }
  65. return &awsConfig{
  66. identityURL: awsIdentityURL,
  67. signatureURL: awsSignatureURL,
  68. certificate: cert,
  69. signatureAlgorithm: awsSignatureAlgorithm,
  70. }, nil
  71. }
  72. type awsPayload struct {
  73. jose.Claims
  74. Amazon awsAmazonPayload `json:"amazon"`
  75. SANs []string `json:"sans"`
  76. document awsInstanceIdentityDocument
  77. }
  78. type awsAmazonPayload struct {
  79. Document []byte `json:"document"`
  80. Signature []byte `json:"signature"`
  81. }
  82. type awsInstanceIdentityDocument struct {
  83. AccountID string `json:"accountId"`
  84. Architecture string `json:"architecture"`
  85. AvailabilityZone string `json:"availabilityZone"`
  86. BillingProducts []string `json:"billingProducts"`
  87. DevpayProductCodes []string `json:"devpayProductCodes"`
  88. ImageID string `json:"imageId"`
  89. InstanceID string `json:"instanceId"`
  90. InstanceType string `json:"instanceType"`
  91. KernelID string `json:"kernelId"`
  92. PendingTime time.Time `json:"pendingTime"`
  93. PrivateIP string `json:"privateIp"`
  94. RamdiskID string `json:"ramdiskId"`
  95. Region string `json:"region"`
  96. Version string `json:"version"`
  97. }
  98. // AWS is the provisioner that supports identity tokens created from the Amazon
  99. // Web Services Instance Identity Documents.
  100. //
  101. // If DisableCustomSANs is true, only the internal DNS and IP will be added as a
  102. // SAN. By default it will accept any SAN in the CSR.
  103. //
  104. // If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
  105. // with the same instance will be accepted. By default only the first request
  106. // will be accepted.
  107. //
  108. // If InstanceAge is set, only the instances with a pendingTime within the given
  109. // period will be accepted.
  110. //
  111. // Amazon Identity docs are available at
  112. // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
  113. type AWS struct {
  114. *base
  115. Type string `json:"type"`
  116. Name string `json:"name"`
  117. Accounts []string `json:"accounts"`
  118. DisableCustomSANs bool `json:"disableCustomSANs"`
  119. DisableTrustOnFirstUse bool `json:"disableTrustOnFirstUse"`
  120. InstanceAge Duration `json:"instanceAge,omitempty"`
  121. Claims *Claims `json:"claims,omitempty"`
  122. claimer *Claimer
  123. config *awsConfig
  124. audiences Audiences
  125. }
  126. // GetID returns the provisioner unique identifier.
  127. func (p *AWS) GetID() string {
  128. return "aws/" + p.Name
  129. }
  130. // GetTokenID returns the identifier of the token.
  131. func (p *AWS) GetTokenID(token string) (string, error) {
  132. payload, err := p.authorizeToken(token)
  133. if err != nil {
  134. return "", err
  135. }
  136. // If TOFU is disabled create an ID for the token, so it cannot be reused.
  137. // The timestamps, document and signatures should be mostly unique.
  138. if p.DisableTrustOnFirstUse {
  139. sum := sha256.Sum256([]byte(token))
  140. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  141. }
  142. return payload.ID, nil
  143. }
  144. // GetName returns the name of the provisioner.
  145. func (p *AWS) GetName() string {
  146. return p.Name
  147. }
  148. // GetType returns the type of provisioner.
  149. func (p *AWS) GetType() Type {
  150. return TypeAWS
  151. }
  152. // GetEncryptedKey is not available in an AWS provisioner.
  153. func (p *AWS) GetEncryptedKey() (kid string, key string, ok bool) {
  154. return "", "", false
  155. }
  156. // GetIdentityToken retrieves the identity document and it's signature and
  157. // generates a token with them.
  158. func (p *AWS) GetIdentityToken(subject, caURL string) (string, error) {
  159. // Initialize the config if this method is used from the cli.
  160. if err := p.assertConfig(); err != nil {
  161. return "", err
  162. }
  163. var idoc awsInstanceIdentityDocument
  164. doc, err := p.readURL(p.config.identityURL)
  165. if err != nil {
  166. return "", errors.Wrap(err, "error retrieving identity document, are you in an AWS VM?")
  167. }
  168. if err := json.Unmarshal(doc, &idoc); err != nil {
  169. return "", errors.Wrap(err, "error unmarshaling identity document")
  170. }
  171. sig, err := p.readURL(p.config.signatureURL)
  172. if err != nil {
  173. return "", errors.Wrap(err, "error retrieving identity document signature, are you in an AWS VM?")
  174. }
  175. signature, err := base64.StdEncoding.DecodeString(string(sig))
  176. if err != nil {
  177. return "", errors.Wrap(err, "error decoding identity document signature")
  178. }
  179. if err := p.checkSignature(doc, signature); err != nil {
  180. return "", err
  181. }
  182. audience, err := generateSignAudience(caURL, p.GetID())
  183. if err != nil {
  184. return "", err
  185. }
  186. // Create unique ID for Trust On First Use (TOFU). Only the first instance
  187. // per provisioner is allowed as we don't have a way to trust the given
  188. // sans.
  189. unique := fmt.Sprintf("%s.%s", p.GetID(), idoc.InstanceID)
  190. sum := sha256.Sum256([]byte(unique))
  191. // Create a JWT from the identity document
  192. signer, err := jose.NewSigner(
  193. jose.SigningKey{Algorithm: jose.HS256, Key: signature},
  194. new(jose.SignerOptions).WithType("JWT"),
  195. )
  196. if err != nil {
  197. return "", errors.Wrap(err, "error creating signer")
  198. }
  199. now := time.Now()
  200. payload := awsPayload{
  201. Claims: jose.Claims{
  202. Issuer: awsIssuer,
  203. Subject: subject,
  204. Audience: []string{audience},
  205. Expiry: jose.NewNumericDate(now.Add(5 * time.Minute)),
  206. NotBefore: jose.NewNumericDate(now),
  207. IssuedAt: jose.NewNumericDate(now),
  208. ID: strings.ToLower(hex.EncodeToString(sum[:])),
  209. },
  210. Amazon: awsAmazonPayload{
  211. Document: doc,
  212. Signature: signature,
  213. },
  214. }
  215. tok, err := jose.Signed(signer).Claims(payload).CompactSerialize()
  216. if err != nil {
  217. return "", errors.Wrap(err, "error serialiazing token")
  218. }
  219. return tok, nil
  220. }
  221. // Init validates and initializes the AWS provisioner.
  222. func (p *AWS) Init(config Config) (err error) {
  223. switch {
  224. case p.Type == "":
  225. return errors.New("provisioner type cannot be empty")
  226. case p.Name == "":
  227. return errors.New("provisioner name cannot be empty")
  228. case p.InstanceAge.Value() < 0:
  229. return errors.New("provisioner instanceAge cannot be negative")
  230. }
  231. // Update claims with global ones
  232. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  233. return err
  234. }
  235. // Add default config
  236. if p.config, err = newAWSConfig(); err != nil {
  237. return err
  238. }
  239. p.audiences = config.Audiences.WithFragment(p.GetID())
  240. return nil
  241. }
  242. // AuthorizeSign validates the given token and returns the sign options that
  243. // will be used on certificate creation.
  244. func (p *AWS) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  245. payload, err := p.authorizeToken(token)
  246. if err != nil {
  247. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSign")
  248. }
  249. doc := payload.document
  250. // Enforce known CN and default DNS and IP if configured.
  251. // By default we'll accept the CN and SANs in the CSR.
  252. // There's no way to trust them other than TOFU.
  253. var so []SignOption
  254. if p.DisableCustomSANs {
  255. so = append(so, dnsNamesValidator([]string{
  256. fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
  257. }))
  258. so = append(so, ipAddressesValidator([]net.IP{
  259. net.ParseIP(doc.PrivateIP),
  260. }))
  261. }
  262. return append(so,
  263. // modifiers / withOptions
  264. newProvisionerExtensionOption(TypeAWS, p.Name, doc.AccountID, "InstanceID", doc.InstanceID),
  265. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  266. // validators
  267. defaultPublicKeyValidator{},
  268. commonNameValidator(payload.Claims.Subject),
  269. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  270. ), nil
  271. }
  272. // AuthorizeRenew returns an error if the renewal is disabled.
  273. // NOTE: This method does not actually validate the certificate or check it's
  274. // revocation status. Just confirms that the provisioner that created the
  275. // certificate was configured to allow renewals.
  276. func (p *AWS) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  277. if p.claimer.IsDisableRenewal() {
  278. return errs.Unauthorized("aws.AuthorizeRenew; renew is disabled for aws provisioner %s", p.GetID())
  279. }
  280. return nil
  281. }
  282. // assertConfig initializes the config if it has not been initialized
  283. func (p *AWS) assertConfig() (err error) {
  284. if p.config != nil {
  285. return
  286. }
  287. p.config, err = newAWSConfig()
  288. return err
  289. }
  290. // checkSignature returns an error if the signature is not valid.
  291. func (p *AWS) checkSignature(signed, signature []byte) error {
  292. if err := p.config.certificate.CheckSignature(p.config.signatureAlgorithm, signed, signature); err != nil {
  293. return errors.Wrap(err, "error validating identity document signature")
  294. }
  295. return nil
  296. }
  297. // readURL does a GET request to the given url and returns the body. It's not
  298. // using pkg/errors to avoid verbose errors, the caller should use it and write
  299. // the appropriate error.
  300. func (p *AWS) readURL(url string) ([]byte, error) {
  301. r, err := http.Get(url)
  302. if err != nil {
  303. return nil, err
  304. }
  305. defer r.Body.Close()
  306. b, err := ioutil.ReadAll(r.Body)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return b, nil
  311. }
  312. // authorizeToken performs common jwt authorization actions and returns the
  313. // claims for case specific downstream parsing.
  314. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  315. func (p *AWS) authorizeToken(token string) (*awsPayload, error) {
  316. jwt, err := jose.ParseSigned(token)
  317. if err != nil {
  318. return nil, errs.Wrapf(http.StatusUnauthorized, err, "aws.authorizeToken; error parsing aws token")
  319. }
  320. if len(jwt.Headers) == 0 {
  321. return nil, errs.InternalServer("aws.authorizeToken; error parsing token, header is missing")
  322. }
  323. var unsafeClaims awsPayload
  324. if err := jwt.UnsafeClaimsWithoutVerification(&unsafeClaims); err != nil {
  325. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; error unmarshaling claims")
  326. }
  327. var payload awsPayload
  328. if err := jwt.Claims(unsafeClaims.Amazon.Signature, &payload); err != nil {
  329. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; error verifying claims")
  330. }
  331. // Validate identity document signature
  332. if err := p.checkSignature(payload.Amazon.Document, payload.Amazon.Signature); err != nil {
  333. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; invalid aws token signature")
  334. }
  335. var doc awsInstanceIdentityDocument
  336. if err := json.Unmarshal(payload.Amazon.Document, &doc); err != nil {
  337. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; error unmarshaling aws identity document")
  338. }
  339. switch {
  340. case doc.AccountID == "":
  341. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document accountId cannot be empty")
  342. case doc.InstanceID == "":
  343. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document instanceId cannot be empty")
  344. case doc.PrivateIP == "":
  345. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document privateIp cannot be empty")
  346. case doc.Region == "":
  347. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document region cannot be empty")
  348. }
  349. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  350. // more than a few minutes.
  351. now := time.Now().UTC()
  352. if err = payload.ValidateWithLeeway(jose.Expected{
  353. Issuer: awsIssuer,
  354. Time: now,
  355. }, time.Minute); err != nil {
  356. return nil, errs.Wrapf(http.StatusUnauthorized, err, "aws.authorizeToken; invalid aws token")
  357. }
  358. // validate audiences with the defaults
  359. if !matchesAudience(payload.Audience, p.audiences.Sign) {
  360. return nil, errs.Unauthorized("aws.authorizeToken; invalid token - invalid audience claim (aud)")
  361. }
  362. // Validate subject, it has to be known if disableCustomSANs is enabled
  363. if p.DisableCustomSANs {
  364. if payload.Subject != doc.InstanceID &&
  365. payload.Subject != doc.PrivateIP &&
  366. payload.Subject != fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region) {
  367. return nil, errs.Unauthorized("aws.authorizeToken; invalid token - invalid subject claim (sub)")
  368. }
  369. }
  370. // validate accounts
  371. if len(p.Accounts) > 0 {
  372. var found bool
  373. for _, sa := range p.Accounts {
  374. if sa == doc.AccountID {
  375. found = true
  376. break
  377. }
  378. }
  379. if !found {
  380. return nil, errs.Unauthorized("aws.authorizeToken; invalid aws identity document - accountId is not valid")
  381. }
  382. }
  383. // validate instance age
  384. if d := p.InstanceAge.Value(); d > 0 {
  385. if now.Sub(doc.PendingTime) > d {
  386. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document pendingTime is too old")
  387. }
  388. }
  389. payload.document = doc
  390. return &payload, nil
  391. }
  392. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  393. func (p *AWS) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  394. if !p.claimer.IsSSHCAEnabled() {
  395. return nil, errs.Unauthorized("aws.AuthorizeSSHSign; ssh ca is disabled for aws provisioner %s", p.GetID())
  396. }
  397. claims, err := p.authorizeToken(token)
  398. if err != nil {
  399. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSSHSign")
  400. }
  401. doc := claims.document
  402. signOptions := []SignOption{
  403. // set the key id to the token subject
  404. sshCertKeyIDModifier(claims.Subject),
  405. }
  406. // Default to host + known IPs/hostnames
  407. defaults := SSHOptions{
  408. CertType: SSHHostCert,
  409. Principals: []string{
  410. doc.PrivateIP,
  411. fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
  412. },
  413. }
  414. // Validate user options
  415. signOptions = append(signOptions, sshCertOptionsValidator(defaults))
  416. // Set defaults if not given as user options
  417. signOptions = append(signOptions, sshCertDefaultsModifier(defaults))
  418. return append(signOptions,
  419. // Set the default extensions.
  420. &sshDefaultExtensionModifier{},
  421. // Set the validity bounds if not set.
  422. &sshDefaultDuration{p.claimer},
  423. // Validate public key
  424. &sshDefaultPublicKeyValidator{},
  425. // Validate the validity period.
  426. &sshCertValidityValidator{p.claimer},
  427. // Require all the fields in the SSH certificate
  428. &sshCertDefaultValidator{},
  429. ), nil
  430. }