aws.go 26 KB

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