aws.go 28 KB

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