aws.go 21 KB

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