aws.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. Type string `json:"type"`
  114. Name string `json:"name"`
  115. Accounts []string `json:"accounts"`
  116. DisableCustomSANs bool `json:"disableCustomSANs"`
  117. DisableTrustOnFirstUse bool `json:"disableTrustOnFirstUse"`
  118. InstanceAge Duration `json:"instanceAge,omitempty"`
  119. Claims *Claims `json:"claims,omitempty"`
  120. claimer *Claimer
  121. config *awsConfig
  122. audiences Audiences
  123. }
  124. // GetID returns the provisioner unique identifier.
  125. func (p *AWS) GetID() string {
  126. return "aws/" + p.Name
  127. }
  128. // GetTokenID returns the identifier of the token.
  129. func (p *AWS) GetTokenID(token string) (string, error) {
  130. payload, err := p.authorizeToken(token)
  131. if err != nil {
  132. return "", err
  133. }
  134. // If TOFU is disabled create an ID for the token, so it cannot be reused.
  135. // The timestamps, document and signatures should be mostly unique.
  136. if p.DisableTrustOnFirstUse {
  137. sum := sha256.Sum256([]byte(token))
  138. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  139. }
  140. return payload.ID, nil
  141. }
  142. // GetName returns the name of the provisioner.
  143. func (p *AWS) GetName() string {
  144. return p.Name
  145. }
  146. // GetType returns the type of provisioner.
  147. func (p *AWS) GetType() Type {
  148. return TypeAWS
  149. }
  150. // GetEncryptedKey is not available in an AWS provisioner.
  151. func (p *AWS) GetEncryptedKey() (kid string, key string, ok bool) {
  152. return "", "", false
  153. }
  154. // GetIdentityToken retrieves the identity document and it's signature and
  155. // generates a token with them.
  156. func (p *AWS) GetIdentityToken(subject, caURL string) (string, error) {
  157. // Initialize the config if this method is used from the cli.
  158. if err := p.assertConfig(); err != nil {
  159. return "", err
  160. }
  161. var idoc awsInstanceIdentityDocument
  162. doc, err := p.readURL(p.config.identityURL)
  163. if err != nil {
  164. return "", errors.Wrap(err, "error retrieving identity document, are you in an AWS VM?")
  165. }
  166. if err := json.Unmarshal(doc, &idoc); err != nil {
  167. return "", errors.Wrap(err, "error unmarshaling identity document")
  168. }
  169. sig, err := p.readURL(p.config.signatureURL)
  170. if err != nil {
  171. return "", errors.Wrap(err, "error retrieving identity document signature, are you in an AWS VM?")
  172. }
  173. signature, err := base64.StdEncoding.DecodeString(string(sig))
  174. if err != nil {
  175. return "", errors.Wrap(err, "error decoding identity document signature")
  176. }
  177. if err := p.checkSignature(doc, signature); err != nil {
  178. return "", err
  179. }
  180. audience, err := generateSignAudience(caURL, p.GetID())
  181. if err != nil {
  182. return "", err
  183. }
  184. // Create unique ID for Trust On First Use (TOFU). Only the first instance
  185. // per provisioner is allowed as we don't have a way to trust the given
  186. // sans.
  187. unique := fmt.Sprintf("%s.%s", p.GetID(), idoc.InstanceID)
  188. sum := sha256.Sum256([]byte(unique))
  189. // Create a JWT from the identity document
  190. signer, err := jose.NewSigner(
  191. jose.SigningKey{Algorithm: jose.HS256, Key: signature},
  192. new(jose.SignerOptions).WithType("JWT"),
  193. )
  194. if err != nil {
  195. return "", errors.Wrap(err, "error creating signer")
  196. }
  197. now := time.Now()
  198. payload := awsPayload{
  199. Claims: jose.Claims{
  200. Issuer: awsIssuer,
  201. Subject: subject,
  202. Audience: []string{audience},
  203. Expiry: jose.NewNumericDate(now.Add(5 * time.Minute)),
  204. NotBefore: jose.NewNumericDate(now),
  205. IssuedAt: jose.NewNumericDate(now),
  206. ID: strings.ToLower(hex.EncodeToString(sum[:])),
  207. },
  208. Amazon: awsAmazonPayload{
  209. Document: doc,
  210. Signature: signature,
  211. },
  212. }
  213. tok, err := jose.Signed(signer).Claims(payload).CompactSerialize()
  214. if err != nil {
  215. return "", errors.Wrap(err, "error serialiazing token")
  216. }
  217. return tok, nil
  218. }
  219. // Init validates and initializes the AWS provisioner.
  220. func (p *AWS) Init(config Config) (err error) {
  221. switch {
  222. case p.Type == "":
  223. return errors.New("provisioner type cannot be empty")
  224. case p.Name == "":
  225. return errors.New("provisioner name cannot be empty")
  226. case p.InstanceAge.Value() < 0:
  227. return errors.New("provisioner instanceAge cannot be negative")
  228. }
  229. // Update claims with global ones
  230. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  231. return err
  232. }
  233. // Add default config
  234. if p.config, err = newAWSConfig(); err != nil {
  235. return err
  236. }
  237. p.audiences = config.Audiences.WithFragment(p.GetID())
  238. return nil
  239. }
  240. // AuthorizeSign validates the given token and returns the sign options that
  241. // will be used on certificate creation.
  242. func (p *AWS) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  243. payload, err := p.authorizeToken(token)
  244. if err != nil {
  245. return nil, err
  246. }
  247. // Check for the sign ssh method, default to sign X.509
  248. if m := MethodFromContext(ctx); m == SignSSHMethod {
  249. if p.claimer.IsSSHCAEnabled() == false {
  250. return nil, errors.Errorf("ssh ca is disabled for provisioner %s", p.GetID())
  251. }
  252. return p.authorizeSSHSign(payload)
  253. }
  254. doc := payload.document
  255. // Enforce known CN and default DNS and IP if configured.
  256. // By default we'll accept the CN and SANs in the CSR.
  257. // There's no way to trust them other than TOFU.
  258. var so []SignOption
  259. if p.DisableCustomSANs {
  260. so = append(so, dnsNamesValidator([]string{
  261. fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
  262. }))
  263. so = append(so, ipAddressesValidator([]net.IP{
  264. net.ParseIP(doc.PrivateIP),
  265. }))
  266. }
  267. return append(so,
  268. defaultPublicKeyValidator{},
  269. commonNameValidator(payload.Claims.Subject),
  270. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  271. newProvisionerExtensionOption(TypeAWS, p.Name, doc.AccountID, "InstanceID", doc.InstanceID),
  272. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  273. ), nil
  274. }
  275. // AuthorizeRenewal returns an error if the renewal is disabled.
  276. func (p *AWS) AuthorizeRenewal(cert *x509.Certificate) error {
  277. if p.claimer.IsDisableRenewal() {
  278. return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
  279. }
  280. return nil
  281. }
  282. // AuthorizeRevoke returns an error because revoke is not supported on AWS
  283. // provisioners.
  284. func (p *AWS) AuthorizeRevoke(token string) error {
  285. return errors.New("revoke is not supported on a AWS provisioner")
  286. }
  287. // assertConfig initializes the config if it has not been initialized
  288. func (p *AWS) assertConfig() (err error) {
  289. if p.config != nil {
  290. return
  291. }
  292. p.config, err = newAWSConfig()
  293. return err
  294. }
  295. // checkSignature returns an error if the signature is not valid.
  296. func (p *AWS) checkSignature(signed, signature []byte) error {
  297. if err := p.config.certificate.CheckSignature(p.config.signatureAlgorithm, signed, signature); err != nil {
  298. return errors.Wrap(err, "error validating identity document signature")
  299. }
  300. return nil
  301. }
  302. // readURL does a GET request to the given url and returns the body. It's not
  303. // using pkg/errors to avoid verbose errors, the caller should use it and write
  304. // the appropriate error.
  305. func (p *AWS) readURL(url string) ([]byte, error) {
  306. r, err := http.Get(url)
  307. if err != nil {
  308. return nil, err
  309. }
  310. defer r.Body.Close()
  311. b, err := ioutil.ReadAll(r.Body)
  312. if err != nil {
  313. return nil, err
  314. }
  315. return b, nil
  316. }
  317. // authorizeToken performs common jwt authorization actions and returns the
  318. // claims for case specific downstream parsing.
  319. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  320. func (p *AWS) authorizeToken(token string) (*awsPayload, error) {
  321. jwt, err := jose.ParseSigned(token)
  322. if err != nil {
  323. return nil, errors.Wrapf(err, "error parsing token")
  324. }
  325. if len(jwt.Headers) == 0 {
  326. return nil, errors.New("error parsing token: header is missing")
  327. }
  328. var unsafeClaims awsPayload
  329. if err := jwt.UnsafeClaimsWithoutVerification(&unsafeClaims); err != nil {
  330. return nil, errors.Wrap(err, "error unmarshaling claims")
  331. }
  332. var payload awsPayload
  333. if err := jwt.Claims(unsafeClaims.Amazon.Signature, &payload); err != nil {
  334. return nil, errors.Wrap(err, "error verifying claims")
  335. }
  336. // Validate identity document signature
  337. if err := p.checkSignature(payload.Amazon.Document, payload.Amazon.Signature); err != nil {
  338. return nil, err
  339. }
  340. var doc awsInstanceIdentityDocument
  341. if err := json.Unmarshal(payload.Amazon.Document, &doc); err != nil {
  342. return nil, errors.Wrap(err, "error unmarshaling identity document")
  343. }
  344. switch {
  345. case doc.AccountID == "":
  346. return nil, errors.New("identity document accountId cannot be empty")
  347. case doc.InstanceID == "":
  348. return nil, errors.New("identity document instanceId cannot be empty")
  349. case doc.PrivateIP == "":
  350. return nil, errors.New("identity document privateIp cannot be empty")
  351. case doc.Region == "":
  352. return nil, errors.New("identity document region cannot be empty")
  353. }
  354. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  355. // more than a few minutes.
  356. now := time.Now().UTC()
  357. if err = payload.ValidateWithLeeway(jose.Expected{
  358. Issuer: awsIssuer,
  359. Time: now,
  360. }, time.Minute); err != nil {
  361. return nil, errors.Wrapf(err, "invalid token")
  362. }
  363. // validate audiences with the defaults
  364. if !matchesAudience(payload.Audience, p.audiences.Sign) {
  365. return nil, errors.New("invalid token: invalid audience claim (aud)")
  366. }
  367. // Validate subject, it has to be known if disableCustomSANs is enabled
  368. if p.DisableCustomSANs {
  369. if payload.Subject != doc.InstanceID &&
  370. payload.Subject != doc.PrivateIP &&
  371. payload.Subject != fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region) {
  372. return nil, errors.New("invalid token: invalid subject claim (sub)")
  373. }
  374. }
  375. // validate accounts
  376. if len(p.Accounts) > 0 {
  377. var found bool
  378. for _, sa := range p.Accounts {
  379. if sa == doc.AccountID {
  380. found = true
  381. break
  382. }
  383. }
  384. if !found {
  385. return nil, errors.New("invalid identity document: accountId is not valid")
  386. }
  387. }
  388. // validate instance age
  389. if d := p.InstanceAge.Value(); d > 0 {
  390. if now.Sub(doc.PendingTime) > d {
  391. return nil, errors.New("identity document pendingTime is too old")
  392. }
  393. }
  394. payload.document = doc
  395. return &payload, nil
  396. }
  397. // authorizeSSHSign returns the list of SignOption for a SignSSH request.
  398. func (p *AWS) authorizeSSHSign(claims *awsPayload) ([]SignOption, error) {
  399. doc := claims.document
  400. signOptions := []SignOption{
  401. // set the key id to the token subject
  402. sshCertificateKeyIDModifier(claims.Subject),
  403. }
  404. // Default to host + known IPs/hostnames
  405. defaults := SSHOptions{
  406. CertType: SSHHostCert,
  407. Principals: []string{
  408. doc.PrivateIP,
  409. fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
  410. },
  411. }
  412. // Validate user options
  413. signOptions = append(signOptions, sshCertificateOptionsValidator(defaults))
  414. // Set defaults if not given as user options
  415. signOptions = append(signOptions, sshCertificateDefaultsModifier(defaults))
  416. return append(signOptions,
  417. // set the default extensions
  418. &sshDefaultExtensionModifier{},
  419. // checks the validity bounds, and set the validity if has not been set
  420. &sshCertificateValidityModifier{p.claimer},
  421. // validate public key
  422. &sshDefaultPublicKeyValidator{},
  423. // require all the fields in the SSH certificate
  424. &sshCertificateDefaultValidator{},
  425. ), nil
  426. }