aws.go 15 KB

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