aws.go 21 KB

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