aws.go 28 KB

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