aws.go 26 KB

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