Skip to content

Instantly share code, notes, and snippets.

@moofish32
Created April 15, 2019 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moofish32/f9e71c323e20bbcec94a02098a140915 to your computer and use it in GitHub Desktop.
Save moofish32/f9e71c323e20bbcec94a02098a140915 to your computer and use it in GitHub Desktop.
cdk aspect for checking for an ingress control issue
import cdk = require('@aws-cdk/cdk');
import ec2 = require('@aws-cdk/aws-ec2');
export class IngressControlCheck implements cdk.IAspect {
constructor(private readonly cidr: string, private readonly port: number) { }
public visit(construct: cdk.Construct) {
if (cdk.CfnResource.isCfnResource(construct) && this.isCfnSecurityGroup(construct)) {
this.check(construct);
}
}
private extractProperties(resource: cdk.CfnResource): any {
const cfn = (resource as any)._toCloudFormation();
const cfnResource = resource.node.resolve(cfn)['Resources'];
console.log(cfnResource);
for (const key of Object.keys(cfnResource)) {
if ((cfnResource as any)[key]['Properties'] !== undefined) {
console.log((cfnResource as any)[key].Properties);
return (cfnResource as any)[key].Properties;
}
}
return undefined;
}
public check(sg: ec2.CfnSecurityGroup) {
const props = this.extractProperties(sg);
if (props !== undefined && Array.isArray(props['SecurityGroupIngress'])) {
for (const rule of props['SecurityGroupIngress']) {
const cidr = rule.CidrIp;
const fromPort = Number(rule.FromPort);
const toPort = Number(rule.ToPort);
if (this.cidr === cidr && (fromPort <= this.port && toPort >= this.port)) {
const ruleString = JSON.stringify(rule);
throw new Error(`${sg.node.path} includes a rule allowing access from ${this.cidr} to port ${this.port}: rule [${ruleString}]`);
}
}
}
}
private isCfnSecurityGroup(resource: cdk.CfnResource): resource is ec2.CfnSecurityGroup {
return resource.resourceType === ec2.CfnSecurityGroup.resourceTypeName
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment