aws.go 25 KB

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