4
0

aws.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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"
  12. "net"
  13. "net/http"
  14. "os"
  15. "strings"
  16. "time"
  17. "github.com/pkg/errors"
  18. "go.step.sm/crypto/jose"
  19. "go.step.sm/crypto/sshutil"
  20. "go.step.sm/crypto/x509util"
  21. "github.com/smallstep/certificates/errs"
  22. )
  23. // awsIssuer is the string used as issuer in the generated tokens.
  24. const awsIssuer = "ec2.amazonaws.com"
  25. // awsIdentityURL is the url used to retrieve the instance identity document.
  26. const awsIdentityURL = "http://169.254.169.254/latest/dynamic/instance-identity/document"
  27. // awsSignatureURL is the url used to retrieve the instance identity signature.
  28. const awsSignatureURL = "http://169.254.169.254/latest/dynamic/instance-identity/signature"
  29. // awsAPITokenURL is the url used to get the IMDSv2 API token
  30. const awsAPITokenURL = "http://169.254.169.254/latest/api/token" //nolint:gosec // no credentials here
  31. // awsAPITokenTTL is the default TTL to use when requesting IMDSv2 API tokens
  32. // -- we keep this short-lived since we get a new token with every call to readURL()
  33. const awsAPITokenTTL = "30"
  34. // awsMetadataTokenHeader is the header that must be passed with every IMDSv2 request
  35. const awsMetadataTokenHeader = "X-aws-ec2-metadata-token" //nolint:gosec // no credentials here
  36. // awsMetadataTokenTTLHeader is the header used to indicate the token TTL requested
  37. const awsMetadataTokenTTLHeader = "X-aws-ec2-metadata-token-ttl-seconds" //nolint:gosec // no credentials here
  38. // awsCertificate is the certificate used to validate the instance identity
  39. // signature.
  40. //
  41. // The first certificate is used in:
  42. //
  43. // ap-northeast-2, ap-south-1, ap-southeast-1, ap-southeast-2
  44. // eu-central-1, eu-north-1, eu-west-1, eu-west-2, eu-west-3
  45. // us-east-1, us-east-2, us-west-1, us-west-2
  46. // ca-central-1, sa-east-1
  47. //
  48. // The second certificate is used in:
  49. //
  50. // eu-south-1
  51. //
  52. // The third certificate is used in:
  53. //
  54. // ap-east-1
  55. //
  56. // The fourth certificate is used in:
  57. //
  58. // af-south-1
  59. //
  60. // The fifth certificate is used in:
  61. //
  62. // me-south-1
  63. const awsCertificate = `-----BEGIN CERTIFICATE-----
  64. MIIDIjCCAougAwIBAgIJAKnL4UEDMN/FMA0GCSqGSIb3DQEBBQUAMGoxCzAJBgNV
  65. BAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRgw
  66. FgYDVQQKEw9BbWF6b24uY29tIEluYy4xGjAYBgNVBAMTEWVjMi5hbWF6b25hd3Mu
  67. Y29tMB4XDTE0MDYwNTE0MjgwMloXDTI0MDYwNTE0MjgwMlowajELMAkGA1UEBhMC
  68. VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxGDAWBgNV
  69. BAoTD0FtYXpvbi5jb20gSW5jLjEaMBgGA1UEAxMRZWMyLmFtYXpvbmF3cy5jb20w
  70. gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIe9GN//SRK2knbjySG0ho3yqQM3
  71. e2TDhWO8D2e8+XZqck754gFSo99AbT2RmXClambI7xsYHZFapbELC4H91ycihvrD
  72. jbST1ZjkLQgga0NE1q43eS68ZeTDccScXQSNivSlzJZS8HJZjgqzBlXjZftjtdJL
  73. XeE4hwvo0sD4f3j9AgMBAAGjgc8wgcwwHQYDVR0OBBYEFCXWzAgVyrbwnFncFFIs
  74. 77VBdlE4MIGcBgNVHSMEgZQwgZGAFCXWzAgVyrbwnFncFFIs77VBdlE4oW6kbDBq
  75. MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh
  76. dHRsZTEYMBYGA1UEChMPQW1hem9uLmNvbSBJbmMuMRowGAYDVQQDExFlYzIuYW1h
  77. em9uYXdzLmNvbYIJAKnL4UEDMN/FMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEF
  78. BQADgYEAFYcz1OgEhQBXIwIdsgCOS8vEtiJYF+j9uO6jz7VOmJqO+pRlAbRlvY8T
  79. C1haGgSI/A1uZUKs/Zfnph0oEI0/hu1IIJ/SKBDtN5lvmZ/IzbOPIJWirlsllQIQ
  80. 7zvWbGd9c9+Rm3p04oTvhup99la7kZqevJK0QRdD/6NpCKsqP/0=
  81. -----END CERTIFICATE-----
  82. -----BEGIN CERTIFICATE-----
  83. MIICNjCCAZ+gAwIBAgIJAOZ3GEIaDcugMA0GCSqGSIb3DQEBCwUAMFwxCzAJBgNV
  84. BAYTAlVTMRkwFwYDVQQIExBXYXNoaW5ndG9uIFN0YXRlMRAwDgYDVQQHEwdTZWF0
  85. dGxlMSAwHgYDVQQKExdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzAgFw0xOTEwMjQx
  86. NTE5MDlaGA8yMTk5MDMyOTE1MTkwOVowXDELMAkGA1UEBhMCVVMxGTAXBgNVBAgT
  87. EFdhc2hpbmd0b24gU3RhdGUxEDAOBgNVBAcTB1NlYXR0bGUxIDAeBgNVBAoTF0Ft
  88. YXpvbiBXZWIgU2VydmljZXMgTExDMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
  89. gQCjiPgW3vsXRj4JoA16WQDyoPc/eh3QBARaApJEc4nPIGoUolpAXcjFhWplo2O+
  90. ivgfCsc4AU9OpYdAPha3spLey/bhHPRi1JZHRNqScKP0hzsCNmKhfnZTIEQCFvsp
  91. DRp4zr91/WS06/flJFBYJ6JHhp0KwM81XQG59lV6kkoW7QIDAQABMA0GCSqGSIb3
  92. DQEBCwUAA4GBAGLLrY3P+HH6C57dYgtJkuGZGT2+rMkk2n81/abzTJvsqRqGRrWv
  93. XRKRXlKdM/dfiuYGokDGxiC0Mg6TYy6wvsR2qRhtXW1OtZkiHWcQCnOttz+8vpew
  94. wx8JGMvowtuKB1iMsbwyRqZkFYLcvH+Opfb/Aayi20/ChQLdI6M2R5VU
  95. -----END CERTIFICATE-----
  96. -----BEGIN CERTIFICATE-----
  97. MIICSzCCAbQCCQDtQvkVxRvK9TANBgkqhkiG9w0BAQsFADBqMQswCQYDVQQGEwJV
  98. UzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2VhdHRsZTEYMBYGA1UE
  99. ChMPQW1hem9uLmNvbSBJbmMuMRowGAYDVQQDExFlYzIuYW1hem9uYXdzLmNvbTAe
  100. Fw0xOTAyMDMwMzAwMDZaFw0yOTAyMDIwMzAwMDZaMGoxCzAJBgNVBAYTAlVTMRMw
  101. EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRgwFgYDVQQKEw9B
  102. bWF6b24uY29tIEluYy4xGjAYBgNVBAMTEWVjMi5hbWF6b25hd3MuY29tMIGfMA0G
  103. CSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1kkHXYTfc7gY5Q55JJhjTieHAgacaQkiR
  104. Pity9QPDE3b+NXDh4UdP1xdIw73JcIIG3sG9RhWiXVCHh6KkuCTqJfPUknIKk8vs
  105. M3RXflUpBe8Pf+P92pxqPMCz1Fr2NehS3JhhpkCZVGxxwLC5gaG0Lr4rFORubjYY
  106. Rh84dK98VwIDAQABMA0GCSqGSIb3DQEBCwUAA4GBAA6xV9f0HMqXjPHuGILDyaNN
  107. dKcvplNFwDTydVg32MNubAGnecoEBtUPtxBsLoVYXCOb+b5/ZMDubPF9tU/vSXuo
  108. TpYM5Bq57gJzDRaBOntQbX9bgHiUxw6XZWaTS/6xjRJDT5p3S1E0mPI3lP/eJv4o
  109. Ezk5zb3eIf10/sqt4756
  110. -----END CERTIFICATE-----
  111. -----BEGIN CERTIFICATE-----
  112. MIICNjCCAZ+gAwIBAgIJAKumfZiRrNvHMA0GCSqGSIb3DQEBCwUAMFwxCzAJBgNV
  113. BAYTAlVTMRkwFwYDVQQIExBXYXNoaW5ndG9uIFN0YXRlMRAwDgYDVQQHEwdTZWF0
  114. dGxlMSAwHgYDVQQKExdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzAgFw0xOTExMjcw
  115. NzE0MDVaGA8yMTk5MDUwMjA3MTQwNVowXDELMAkGA1UEBhMCVVMxGTAXBgNVBAgT
  116. EFdhc2hpbmd0b24gU3RhdGUxEDAOBgNVBAcTB1NlYXR0bGUxIDAeBgNVBAoTF0Ft
  117. YXpvbiBXZWIgU2VydmljZXMgTExDMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
  118. gQDFd571nUzVtke3rPyRkYfvs3jh0C0EMzzG72boyUNjnfw1+m0TeFraTLKb9T6F
  119. 7TuB/ZEN+vmlYqr2+5Va8U8qLbPF0bRH+FdaKjhgWZdYXxGzQzU3ioy5W5ZM1VyB
  120. 7iUsxEAlxsybC3ziPYaHI42UiTkQNahmoroNeqVyHNnBpQIDAQABMA0GCSqGSIb3
  121. DQEBCwUAA4GBAAJLylWyElEgOpW4B1XPyRVD4pAds8Guw2+krgqkY0HxLCdjosuH
  122. RytGDGN+q75aAoXzW5a7SGpxLxk6Hfv0xp3RjDHsoeP0i1d8MD3hAC5ezxS4oukK
  123. s5gbPOnokhKTMPXbTdRn5ZifCbWlx+bYN/mTYKvxho7b5SVg2o1La9aK
  124. -----END CERTIFICATE-----
  125. -----BEGIN CERTIFICATE-----
  126. MIIDPDCCAqWgAwIBAgIJAMl6uIV/zqJFMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNV
  127. BAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMRAwDgYDVQQHDAdTZWF0dGxlMSAw
  128. HgYDVQQKDBdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzEaMBgGA1UEAwwRZWMyLmFt
  129. YXpvbmF3cy5jb20wIBcNMTkwNDI2MTQzMjQ3WhgPMjE5ODA5MjkxNDMyNDdaMHIx
  130. CzAJBgNVBAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMRAwDgYDVQQHDAdTZWF0
  131. dGxlMSAwHgYDVQQKDBdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzEaMBgGA1UEAwwR
  132. ZWMyLmFtYXpvbmF3cy5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALVN
  133. CDTZEnIeoX1SEYqq6k1BV0ZlpY5y3KnoOreCAE589TwS4MX5+8Fzd6AmACmugeBP
  134. Qk7Hm6b2+g/d4tWycyxLaQlcq81DB1GmXehRkZRgGeRge1ePWd1TUA0I8P/QBT7S
  135. gUePm/kANSFU+P7s7u1NNl+vynyi0wUUrw7/wIZTAgMBAAGjgdcwgdQwHQYDVR0O
  136. BBYEFILtMd+T4YgH1cgc+hVsVOV+480FMIGkBgNVHSMEgZwwgZmAFILtMd+T4YgH
  137. 1cgc+hVsVOV+480FoXakdDByMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGlu
  138. Z3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEgMB4GA1UECgwXQW1hem9uIFdlYiBTZXJ2
  139. aWNlcyBMTEMxGjAYBgNVBAMMEWVjMi5hbWF6b25hd3MuY29tggkAyXq4hX/OokUw
  140. DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQBhkNTBIFgWFd+ZhC/LhRUY
  141. 4OjEiykmbEp6hlzQ79T0Tfbn5A4NYDI2icBP0+hmf6qSnIhwJF6typyd1yPK5Fqt
  142. NTpxxcXmUKquX+pHmIkK1LKDO8rNE84jqxrxRsfDi6by82fjVYf2pgjJW8R1FAw+
  143. mL5WQRFexbfB5aXhcMo0AA==
  144. -----END CERTIFICATE-----`
  145. // awsSignatureAlgorithm is the signature algorithm used to verify the identity
  146. // document signature.
  147. const awsSignatureAlgorithm = x509.SHA256WithRSA
  148. type awsConfig struct {
  149. identityURL string
  150. signatureURL string
  151. tokenURL string
  152. tokenTTL string
  153. certificates []*x509.Certificate
  154. signatureAlgorithm x509.SignatureAlgorithm
  155. }
  156. func newAWSConfig(certPath string) (*awsConfig, error) {
  157. var certBytes []byte
  158. if certPath == "" {
  159. certBytes = []byte(awsCertificate)
  160. } else {
  161. if b, err := os.ReadFile(certPath); err == nil {
  162. certBytes = b
  163. } else {
  164. return nil, errors.Wrapf(err, "error reading %s", certPath)
  165. }
  166. }
  167. // Read all the certificates.
  168. var certs []*x509.Certificate
  169. for len(certBytes) > 0 {
  170. var block *pem.Block
  171. block, certBytes = pem.Decode(certBytes)
  172. if block == nil {
  173. break
  174. }
  175. if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
  176. continue
  177. }
  178. cert, err := x509.ParseCertificate(block.Bytes)
  179. if err != nil {
  180. return nil, errors.Wrap(err, "error parsing AWS IID certificate")
  181. }
  182. certs = append(certs, cert)
  183. }
  184. if len(certs) == 0 {
  185. return nil, errors.New("error parsing AWS IID certificate: no certificates found")
  186. }
  187. return &awsConfig{
  188. identityURL: awsIdentityURL,
  189. signatureURL: awsSignatureURL,
  190. tokenURL: awsAPITokenURL,
  191. tokenTTL: awsAPITokenTTL,
  192. certificates: certs,
  193. signatureAlgorithm: awsSignatureAlgorithm,
  194. }, nil
  195. }
  196. type awsPayload struct {
  197. jose.Claims
  198. Amazon awsAmazonPayload `json:"amazon"`
  199. SANs []string `json:"sans"`
  200. document awsInstanceIdentityDocument
  201. }
  202. type awsAmazonPayload struct {
  203. Document []byte `json:"document"`
  204. Signature []byte `json:"signature"`
  205. }
  206. type awsInstanceIdentityDocument struct {
  207. AccountID string `json:"accountId"`
  208. Architecture string `json:"architecture"`
  209. AvailabilityZone string `json:"availabilityZone"`
  210. BillingProducts []string `json:"billingProducts"`
  211. DevpayProductCodes []string `json:"devpayProductCodes"`
  212. ImageID string `json:"imageId"`
  213. InstanceID string `json:"instanceId"`
  214. InstanceType string `json:"instanceType"`
  215. KernelID string `json:"kernelId"`
  216. PendingTime time.Time `json:"pendingTime"`
  217. PrivateIP string `json:"privateIp"`
  218. RamdiskID string `json:"ramdiskId"`
  219. Region string `json:"region"`
  220. Version string `json:"version"`
  221. }
  222. // AWS is the provisioner that supports identity tokens created from the Amazon
  223. // Web Services Instance Identity Documents.
  224. //
  225. // If DisableCustomSANs is true, only the internal DNS and IP will be added as a
  226. // SAN. By default it will accept any SAN in the CSR.
  227. //
  228. // If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
  229. // with the same instance will be accepted. By default only the first request
  230. // will be accepted.
  231. //
  232. // If InstanceAge is set, only the instances with a pendingTime within the given
  233. // period will be accepted.
  234. //
  235. // IIDRoots can be used to specify a path to the certificates used to verify the
  236. // identity certificate signature.
  237. //
  238. // Amazon Identity docs are available at
  239. // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
  240. type AWS struct {
  241. *base
  242. ID string `json:"-"`
  243. Type string `json:"type"`
  244. Name string `json:"name"`
  245. Accounts []string `json:"accounts"`
  246. DisableCustomSANs bool `json:"disableCustomSANs"`
  247. DisableTrustOnFirstUse bool `json:"disableTrustOnFirstUse"`
  248. IMDSVersions []string `json:"imdsVersions"`
  249. InstanceAge Duration `json:"instanceAge,omitempty"`
  250. IIDRoots string `json:"iidRoots,omitempty"`
  251. Claims *Claims `json:"claims,omitempty"`
  252. Options *Options `json:"options,omitempty"`
  253. config *awsConfig
  254. ctl *Controller
  255. }
  256. // GetID returns the provisioner unique identifier.
  257. func (p *AWS) GetID() string {
  258. if p.ID != "" {
  259. return p.ID
  260. }
  261. return p.GetIDForToken()
  262. }
  263. // GetIDForToken returns an identifier that will be used to load the provisioner
  264. // from a token.
  265. func (p *AWS) GetIDForToken() string {
  266. return "aws/" + p.Name
  267. }
  268. // GetTokenID returns the identifier of the token.
  269. func (p *AWS) GetTokenID(token string) (string, error) {
  270. payload, err := p.authorizeToken(token)
  271. if err != nil {
  272. return "", err
  273. }
  274. // If TOFU is disabled create an ID for the token, so it cannot be reused.
  275. // The timestamps, document and signatures should be mostly unique.
  276. if p.DisableTrustOnFirstUse {
  277. sum := sha256.Sum256([]byte(token))
  278. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  279. }
  280. // Use provisioner + instance-id as the identifier.
  281. unique := fmt.Sprintf("%s.%s", p.GetIDForToken(), payload.document.InstanceID)
  282. sum := sha256.Sum256([]byte(unique))
  283. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  284. }
  285. // GetName returns the name of the provisioner.
  286. func (p *AWS) GetName() string {
  287. return p.Name
  288. }
  289. // GetType returns the type of provisioner.
  290. func (p *AWS) GetType() Type {
  291. return TypeAWS
  292. }
  293. // GetEncryptedKey is not available in an AWS provisioner.
  294. func (p *AWS) GetEncryptedKey() (kid, key string, ok bool) {
  295. return "", "", false
  296. }
  297. // GetIdentityToken retrieves the identity document and it's signature and
  298. // generates a token with them.
  299. func (p *AWS) GetIdentityToken(subject, caURL string) (string, error) {
  300. // Initialize the config if this method is used from the cli.
  301. if err := p.assertConfig(); err != nil {
  302. return "", err
  303. }
  304. var idoc awsInstanceIdentityDocument
  305. doc, err := p.readURL(p.config.identityURL)
  306. if err != nil {
  307. return "", errors.Wrap(err, "error retrieving identity document:\n Are you in an AWS VM?\n Is the metadata service enabled?\n Are you using the proper metadata service version?")
  308. }
  309. if err := json.Unmarshal(doc, &idoc); err != nil {
  310. return "", errors.Wrap(err, "error unmarshaling identity document")
  311. }
  312. sig, err := p.readURL(p.config.signatureURL)
  313. if err != nil {
  314. return "", errors.Wrap(err, "error retrieving identity document:\n Are you in an AWS VM?\n Is the metadata service enabled?\n Are you using the proper metadata service version?")
  315. }
  316. signature, err := base64.StdEncoding.DecodeString(string(sig))
  317. if err != nil {
  318. return "", errors.Wrap(err, "error decoding identity document signature")
  319. }
  320. if err := p.checkSignature(doc, signature); err != nil {
  321. return "", err
  322. }
  323. audience, err := generateSignAudience(caURL, p.GetIDForToken())
  324. if err != nil {
  325. return "", err
  326. }
  327. // Create unique ID for Trust On First Use (TOFU). Only the first instance
  328. // per provisioner is allowed as we don't have a way to trust the given
  329. // sans.
  330. unique := fmt.Sprintf("%s.%s", p.GetIDForToken(), idoc.InstanceID)
  331. sum := sha256.Sum256([]byte(unique))
  332. // Create a JWT from the identity document
  333. signer, err := jose.NewSigner(
  334. jose.SigningKey{Algorithm: jose.HS256, Key: signature},
  335. new(jose.SignerOptions).WithType("JWT"),
  336. )
  337. if err != nil {
  338. return "", errors.Wrap(err, "error creating signer")
  339. }
  340. now := time.Now()
  341. payload := awsPayload{
  342. Claims: jose.Claims{
  343. Issuer: awsIssuer,
  344. Subject: subject,
  345. Audience: []string{audience},
  346. Expiry: jose.NewNumericDate(now.Add(5 * time.Minute)),
  347. NotBefore: jose.NewNumericDate(now),
  348. IssuedAt: jose.NewNumericDate(now),
  349. ID: strings.ToLower(hex.EncodeToString(sum[:])),
  350. },
  351. Amazon: awsAmazonPayload{
  352. Document: doc,
  353. Signature: signature,
  354. },
  355. }
  356. tok, err := jose.Signed(signer).Claims(payload).CompactSerialize()
  357. if err != nil {
  358. return "", errors.Wrap(err, "error serializing token")
  359. }
  360. return tok, nil
  361. }
  362. // Init validates and initializes the AWS provisioner.
  363. func (p *AWS) Init(config Config) (err error) {
  364. switch {
  365. case p.Type == "":
  366. return errors.New("provisioner type cannot be empty")
  367. case p.Name == "":
  368. return errors.New("provisioner name cannot be empty")
  369. case p.InstanceAge.Value() < 0:
  370. return errors.New("provisioner instanceAge cannot be negative")
  371. }
  372. // Add default config
  373. if p.config, err = newAWSConfig(p.IIDRoots); err != nil {
  374. return err
  375. }
  376. // validate IMDS versions
  377. if len(p.IMDSVersions) == 0 {
  378. p.IMDSVersions = []string{"v2", "v1"}
  379. }
  380. for _, v := range p.IMDSVersions {
  381. switch v {
  382. case "v1":
  383. // valid
  384. case "v2":
  385. // valid
  386. default:
  387. return errors.Errorf("%s: not a supported AWS Instance Metadata Service version", v)
  388. }
  389. }
  390. config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
  391. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  392. return
  393. }
  394. // AuthorizeSign validates the given token and returns the sign options that
  395. // will be used on certificate creation.
  396. func (p *AWS) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  397. payload, err := p.authorizeToken(token)
  398. if err != nil {
  399. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSign")
  400. }
  401. doc := payload.document
  402. // Template options
  403. data := x509util.NewTemplateData()
  404. data.SetCommonName(payload.Claims.Subject)
  405. if v, err := unsafeParseSigned(token); err == nil {
  406. data.SetToken(v)
  407. }
  408. // Enforce known CN and default DNS and IP if configured.
  409. // By default we'll accept the CN and SANs in the CSR.
  410. // There's no way to trust them other than TOFU.
  411. var so []SignOption
  412. if p.DisableCustomSANs {
  413. dnsName := fmt.Sprintf("ip-%s.%s.compute.internal", strings.ReplaceAll(doc.PrivateIP, ".", "-"), doc.Region)
  414. so = append(so,
  415. dnsNamesValidator([]string{dnsName}),
  416. ipAddressesValidator([]net.IP{
  417. net.ParseIP(doc.PrivateIP),
  418. }),
  419. emailAddressesValidator(nil),
  420. urisValidator(nil),
  421. )
  422. // Template options
  423. data.SetSANs([]string{dnsName, doc.PrivateIP})
  424. }
  425. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultIIDLeafTemplate)
  426. if err != nil {
  427. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSign")
  428. }
  429. return append(so,
  430. p,
  431. templateOptions,
  432. // modifiers / withOptions
  433. newProvisionerExtensionOption(TypeAWS, p.Name, doc.AccountID, "InstanceID", doc.InstanceID),
  434. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  435. // validators
  436. defaultPublicKeyValidator{},
  437. commonNameValidator(payload.Claims.Subject),
  438. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  439. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  440. ), nil
  441. }
  442. // AuthorizeRenew returns an error if the renewal is disabled.
  443. // NOTE: This method does not actually validate the certificate or check it's
  444. // revocation status. Just confirms that the provisioner that created the
  445. // certificate was configured to allow renewals.
  446. func (p *AWS) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  447. return p.ctl.AuthorizeRenew(ctx, cert)
  448. }
  449. // assertConfig initializes the config if it has not been initialized
  450. func (p *AWS) assertConfig() (err error) {
  451. if p.config != nil {
  452. return
  453. }
  454. p.config, err = newAWSConfig(p.IIDRoots)
  455. return err
  456. }
  457. // checkSignature returns an error if the signature is not valid.
  458. func (p *AWS) checkSignature(signed, signature []byte) error {
  459. for _, crt := range p.config.certificates {
  460. if err := crt.CheckSignature(p.config.signatureAlgorithm, signed, signature); err == nil {
  461. return nil
  462. }
  463. }
  464. return errors.New("error validating identity document signature")
  465. }
  466. // readURL does a GET request to the given url and returns the body. It's not
  467. // using pkg/errors to avoid verbose errors, the caller should use it and write
  468. // the appropriate error.
  469. func (p *AWS) readURL(url string) ([]byte, error) {
  470. var resp *http.Response
  471. var err error
  472. // Initialize IMDS versions when this is called from the cli.
  473. if len(p.IMDSVersions) == 0 {
  474. p.IMDSVersions = []string{"v2", "v1"}
  475. }
  476. for _, v := range p.IMDSVersions {
  477. switch v {
  478. case "v1":
  479. resp, err = p.readURLv1(url)
  480. if err == nil && resp.StatusCode < 400 {
  481. return p.readResponseBody(resp)
  482. }
  483. case "v2":
  484. resp, err = p.readURLv2(url)
  485. if err == nil && resp.StatusCode < 400 {
  486. return p.readResponseBody(resp)
  487. }
  488. default:
  489. return nil, fmt.Errorf("%s: not a supported AWS Instance Metadata Service version", v)
  490. }
  491. if resp != nil {
  492. resp.Body.Close()
  493. }
  494. }
  495. // all versions have been exhausted and we haven't returned successfully yet so pass
  496. // the error on to the caller
  497. if err != nil {
  498. return nil, err
  499. }
  500. return nil, fmt.Errorf("request for metadata returned non-successful status code %d",
  501. resp.StatusCode)
  502. }
  503. func (p *AWS) readURLv1(url string) (*http.Response, error) {
  504. client := http.Client{}
  505. req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
  506. if err != nil {
  507. return nil, err
  508. }
  509. resp, err := client.Do(req)
  510. if err != nil {
  511. return nil, err
  512. }
  513. return resp, nil
  514. }
  515. func (p *AWS) readURLv2(url string) (*http.Response, error) {
  516. client := http.Client{}
  517. // first get the token
  518. req, err := http.NewRequest(http.MethodPut, p.config.tokenURL, http.NoBody)
  519. if err != nil {
  520. return nil, err
  521. }
  522. req.Header.Set(awsMetadataTokenTTLHeader, p.config.tokenTTL)
  523. resp, err := client.Do(req)
  524. if err != nil {
  525. return nil, err
  526. }
  527. defer resp.Body.Close()
  528. if resp.StatusCode >= 400 {
  529. return nil, fmt.Errorf("request for API token returned non-successful status code %d", resp.StatusCode)
  530. }
  531. token, err := io.ReadAll(resp.Body)
  532. if err != nil {
  533. return nil, err
  534. }
  535. // now make the request
  536. req, err = http.NewRequest(http.MethodGet, url, http.NoBody)
  537. if err != nil {
  538. return nil, err
  539. }
  540. req.Header.Set(awsMetadataTokenHeader, string(token))
  541. resp, err = client.Do(req)
  542. if err != nil {
  543. return nil, err
  544. }
  545. return resp, nil
  546. }
  547. func (p *AWS) readResponseBody(resp *http.Response) ([]byte, error) {
  548. defer resp.Body.Close()
  549. b, err := io.ReadAll(resp.Body)
  550. if err != nil {
  551. return nil, err
  552. }
  553. return b, nil
  554. }
  555. // authorizeToken performs common jwt authorization actions and returns the
  556. // claims for case specific downstream parsing.
  557. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  558. func (p *AWS) authorizeToken(token string) (*awsPayload, error) {
  559. jwt, err := jose.ParseSigned(token)
  560. if err != nil {
  561. return nil, errs.Wrapf(http.StatusUnauthorized, err, "aws.authorizeToken; error parsing aws token")
  562. }
  563. if len(jwt.Headers) == 0 {
  564. return nil, errs.InternalServer("aws.authorizeToken; error parsing token, header is missing")
  565. }
  566. var unsafeClaims awsPayload
  567. if err := jwt.UnsafeClaimsWithoutVerification(&unsafeClaims); err != nil {
  568. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; error unmarshaling claims")
  569. }
  570. var payload awsPayload
  571. if err := jwt.Claims(unsafeClaims.Amazon.Signature, &payload); err != nil {
  572. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; error verifying claims")
  573. }
  574. // Validate identity document signature
  575. if err := p.checkSignature(payload.Amazon.Document, payload.Amazon.Signature); err != nil {
  576. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; invalid aws token signature")
  577. }
  578. var doc awsInstanceIdentityDocument
  579. if err := json.Unmarshal(payload.Amazon.Document, &doc); err != nil {
  580. return nil, errs.Wrap(http.StatusUnauthorized, err, "aws.authorizeToken; error unmarshaling aws identity document")
  581. }
  582. switch {
  583. case doc.AccountID == "":
  584. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document accountId cannot be empty")
  585. case doc.InstanceID == "":
  586. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document instanceId cannot be empty")
  587. case doc.PrivateIP == "":
  588. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document privateIp cannot be empty")
  589. case doc.Region == "":
  590. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document region cannot be empty")
  591. }
  592. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  593. // more than a few minutes.
  594. now := time.Now().UTC()
  595. if err = payload.ValidateWithLeeway(jose.Expected{
  596. Issuer: awsIssuer,
  597. Time: now,
  598. }, time.Minute); err != nil {
  599. return nil, errs.Wrapf(http.StatusUnauthorized, err, "aws.authorizeToken; invalid aws token")
  600. }
  601. // validate audiences with the defaults
  602. if !matchesAudience(payload.Audience, p.ctl.Audiences.Sign) {
  603. return nil, errs.Unauthorized("aws.authorizeToken; invalid token - invalid audience claim (aud)")
  604. }
  605. // Validate subject, it has to be known if disableCustomSANs is enabled
  606. if p.DisableCustomSANs {
  607. if payload.Subject != doc.InstanceID &&
  608. payload.Subject != doc.PrivateIP &&
  609. payload.Subject != fmt.Sprintf("ip-%s.%s.compute.internal", strings.ReplaceAll(doc.PrivateIP, ".", "-"), doc.Region) {
  610. return nil, errs.Unauthorized("aws.authorizeToken; invalid token - invalid subject claim (sub)")
  611. }
  612. }
  613. // validate accounts
  614. if len(p.Accounts) > 0 {
  615. var found bool
  616. for _, sa := range p.Accounts {
  617. if sa == doc.AccountID {
  618. found = true
  619. break
  620. }
  621. }
  622. if !found {
  623. return nil, errs.Unauthorized("aws.authorizeToken; invalid aws identity document - accountId is not valid")
  624. }
  625. }
  626. // validate instance age
  627. if d := p.InstanceAge.Value(); d > 0 {
  628. if now.Sub(doc.PendingTime) > d {
  629. return nil, errs.Unauthorized("aws.authorizeToken; aws identity document pendingTime is too old")
  630. }
  631. }
  632. payload.document = doc
  633. return &payload, nil
  634. }
  635. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  636. func (p *AWS) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  637. if !p.ctl.Claimer.IsSSHCAEnabled() {
  638. return nil, errs.Unauthorized("aws.AuthorizeSSHSign; ssh ca is disabled for aws provisioner '%s'", p.GetName())
  639. }
  640. claims, err := p.authorizeToken(token)
  641. if err != nil {
  642. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSSHSign")
  643. }
  644. doc := claims.document
  645. signOptions := []SignOption{}
  646. // Enforce host certificate.
  647. defaults := SignSSHOptions{
  648. CertType: SSHHostCert,
  649. }
  650. // Validated principals.
  651. principals := []string{
  652. doc.PrivateIP,
  653. fmt.Sprintf("ip-%s.%s.compute.internal", strings.ReplaceAll(doc.PrivateIP, ".", "-"), doc.Region),
  654. }
  655. // Only enforce known principals if disable custom sans is true.
  656. if p.DisableCustomSANs {
  657. defaults.Principals = principals
  658. } else {
  659. // Check that at least one principal is sent in the request.
  660. signOptions = append(signOptions, &sshCertOptionsRequireValidator{
  661. Principals: true,
  662. })
  663. }
  664. // Certificate templates.
  665. data := sshutil.CreateTemplateData(sshutil.HostCert, doc.InstanceID, principals)
  666. if v, err := unsafeParseSigned(token); err == nil {
  667. data.SetToken(v)
  668. }
  669. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, sshutil.DefaultIIDTemplate)
  670. if err != nil {
  671. return nil, errs.Wrap(http.StatusInternalServerError, err, "aws.AuthorizeSSHSign")
  672. }
  673. signOptions = append(signOptions, templateOptions)
  674. return append(signOptions,
  675. p,
  676. // Validate user SignSSHOptions.
  677. sshCertOptionsValidator(defaults),
  678. // Set the validity bounds if not set.
  679. &sshDefaultDuration{p.ctl.Claimer},
  680. // Validate public key
  681. &sshDefaultPublicKeyValidator{},
  682. // Validate the validity period.
  683. &sshCertValidityValidator{p.ctl.Claimer},
  684. // Require all the fields in the SSH certificate
  685. &sshCertDefaultValidator{},
  686. // Ensure that all principal names are allowed
  687. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), nil),
  688. ), nil
  689. }