Skip to content

Commit

Permalink
fix(iam): oidc provider fetches leaf certificate thumbprint instead o…
Browse files Browse the repository at this point in the history
…f root (#22802)

Currently, the implementation of the OIDC provider custom resource fetches the certificate chain using:

https://github.com/aws/aws-cdk/blob/9bde9f3149cbfa6e7b97204f54e7cef5c9127971/packages/%40aws-cdk/aws-iam/lib/oidc-provider/external.ts#L40

It then extracts the root certificate by detecting a circular reference in the `cert.issuerCertificate` property.

https://github.com/aws/aws-cdk/blob/9bde9f3149cbfa6e7b97204f54e7cef5c9127971/packages/%40aws-cdk/aws-iam/lib/oidc-provider/external.ts#L46

As it turns out, this results in the wrong certificate being extracted. I observed this while running an [EKS integration test](https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/aws-eks/test/integ.eks-service-account-sdk-call.ts).

The current certificate thumbprint that is extracted is: `AD7E1C28B064EF8F6003402014C3D0E3370EB58A`.
While the expected thumbprint is: `9E99A48A9960B14926BB7F3B02E22DA2B0AB7280`. (this is the value we used to [hardcode](https://github.com/aws/aws-cdk/blob/v2.50.0/packages/%40aws-cdk/aws-eks/lib/oidc-provider.ts#L49))

The [recommended way](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html) for extracting the correct thumbprint according to AWS is using `openssl s_client -showcerts`. When I tried this, I did in fact see that the last certificate returned by this command has the correct thumbprint. 

During investigation, I noticed that `socket.getPeerCertificate(true)` returns another additional certificate, acting as the root one. This is aligned with what the [comment](#8607 (comment)) made in the original issue. This additional certificate is not the correct one, and we should be using the one just before it in the chain. There is however no way to detect that "second to last" certificate in this way, because it doesn't resolve to a circular reference. 

After some digging, I switched the implementation to use `socket.getPeerX509Certificate()`, a new method that only exists in Node16. This method skips over the incorrect certificate, and results in the correct thumbprint. 

<img width="539" alt="Screen Shot 2022-11-06 at 10 04 51 PM" src="https://user-images.githubusercontent.com/1428812/200195623-6735377b-a82f-472f-884d-7bec450c32c6.png">

Fixes #8607

----

### All Submissions:

* [X] Have you followed the guidelines in our [Contributing guide?](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md)

### Adding new Unconventional Dependencies:

* [ ] This PR adds new unconventional dependencies following the process described [here](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md/#adding-new-unconventional-dependencies)

### New Features

* [ ] Have you added the new feature to an [integration test](https://github.com/aws/aws-cdk/blob/main/INTEGRATION_TESTS.md)?
	* [ ] Did you use `yarn integ` to deploy the infrastructure and generate the snapshot (i.e. `yarn integ` without `--dry-run`)?

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
iliapolo authored Nov 12, 2022
1 parent 0e97c15 commit 280b876
Show file tree
Hide file tree
Showing 105 changed files with 1,943 additions and 1,830 deletions.
7 changes: 0 additions & 7 deletions packages/@aws-cdk/aws-eks/lib/oidc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,11 @@ export class OpenIdConnectProvider extends iam.OpenIdConnectProvider {
* @param props Initialization properties
*/
public constructor(scope: Construct, id: string, props: OpenIdConnectProviderProps) {
/**
* For some reason EKS isn't validating the root certificate but a intermediate certificate
* which is one level up in the tree. Because of the a constant thumbprint value has to be
* stated with this OpenID Connect provider. The certificate thumbprint is the same for all the regions.
*/
const thumbprints = ['9e99a48a9960b14926bb7f3b02e22da2b0ab7280'];

const clientIds = ['sts.amazonaws.com'];

super(scope, id, {
url: props.url,
thumbprints,
clientIds,
});
}
Expand Down
17 changes: 7 additions & 10 deletions packages/@aws-cdk/aws-eks/test/bucket-pinger/bucket-pinger.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,27 @@
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as lambda from '@aws-cdk/aws-lambda';
import { CustomResource, Token, Duration } from '@aws-cdk/core';
import * as cr from '@aws-cdk/custom-resources';
import { Construct } from 'constructs';

export interface PingerProps {
readonly securityGroup?: ec2.SecurityGroup;
readonly vpc?: ec2.IVpc;
readonly subnets?: ec2.ISubnet[];
export interface BucketPingerProps {
readonly bucketName: string;
}
export class BucketPinger extends Construct {

private _resource: CustomResource;

constructor(scope: Construct, id: string, props: PingerProps) {
constructor(scope: Construct, id: string, props: BucketPingerProps) {
super(scope, id);

const func = new lambda.Function(this, 'Function', {
code: lambda.Code.fromAsset(`${__dirname}/function`),
handler: 'index.handler',
runtime: lambda.Runtime.PYTHON_3_9,
vpc: props.vpc,
vpcSubnets: props.subnets ? { subnets: props.subnets } : undefined,
securityGroups: props.securityGroup ? [props.securityGroup] : undefined,
timeout: Duration.minutes(1),
environment: {
BUCKET_NAME: props.bucketName,
},
});

if (!func.role) {
Expand All @@ -33,7 +30,7 @@ export class BucketPinger extends Construct {

func.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['s3:DeleteBucket', 's3:ListBucket'],
resources: ['arn:aws:s3:::*'],
resources: [`arn:aws:s3:::${props.bucketName}`],
}));

const provider = new cr.Provider(this, 'Provider', {
Expand Down
16 changes: 10 additions & 6 deletions packages/@aws-cdk/aws-eks/test/bucket-pinger/function/index.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import json
import logging
import boto3
import time
import os

logger = logging.getLogger()
logger.setLevel(logging.INFO)
Expand All @@ -11,17 +13,19 @@ def handler(event, context):
request_type = event['RequestType']
props = event['ResourceProperties']

s3_bucket_name = 'amazingly-made-sdk-call-created-eks-bucket'
s3_bucket_name = os.environ['BUCKET_NAME']
s3 = boto3.client('s3')

if request_type in ['Create', 'Update']:
logger.info(f'making sdk call to check if bucket with name {s3_bucket_name} exists')
while (True): # lambda will eventually time this out in case of consistent failures
try:
s3.head_bucket(Bucket=s3_bucket_name)
return {'Data': {'Value': f'confirmed that bucket with name {s3_bucket_name} exists' }}
except Exception as error:
logger.error(f'failed to head bucket with error: {str(error)}')
time.sleep(5)

try:
s3.head_bucket(Bucket=s3_bucket_name)
except Exception as error:
raise RuntimeError(f'failed to head bucket with error: {str(error)}')
return {'Data': {'Value': f'confirmed that bucket with name {s3_bucket_name} exists' }}

elif request_type == 'Delete':
logger.info(f'making sdk call to delete bucket with name {s3_bucket_name}')
Expand Down
3 changes: 0 additions & 3 deletions packages/@aws-cdk/aws-eks/test/cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2156,9 +2156,6 @@ describe('cluster', () => {
ClientIDList: [
'sts.amazonaws.com',
],
ThumbprintList: [
'9e99a48a9960b14926bb7f3b02e22da2b0ab7280',
],
Url: {
'Fn::GetAtt': [
'Cluster9EE0221C',
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 280b876

Please sign in to comment.