4
0

aws.go 26 KB

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