Skip to content

Instantly share code, notes, and snippets.

@brianfoody
Created April 19, 2022 05:17
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 brianfoody/d94430b04561b4a7269bbbcc965ef968 to your computer and use it in GitHub Desktop.
Save brianfoody/d94430b04561b4a7269bbbcc965ef968 to your computer and use it in GitHub Desktop.
IAM Least Access Crafter
import * as AWS from "aws-sdk";
import { retry } from "ts-retry-promise";
import { v4 } from "uuid";
import { makeApiGatewayScanner } from "./adapters/makeApiGatewayScanner";
const iam = new AWS.IAM();
var sts = new AWS.STS();
export const getAccountId = async (): Promise<string | undefined> => {
const identity = await sts.getCallerIdentity().promise();
return identity.Account;
};
const exec = async () => {
const roleName = `${v4()}-IAMCrafter`;
console.log("roleName");
console.log(roleName);
const role = await iam
.createRole({
RoleName: roleName,
AssumeRolePolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: { AWS: `arn:aws:iam::${await getAccountId()}:root` },
Action: "sts:AssumeRole"
}
]
})
})
.promise();
const policy = await iam
.createPolicy({
PolicyName: `${roleName}Policy`,
PolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: ["apigateway:GET"],
Resource: "*"
}
]
})
})
.promise();
const POLICY_ARN = policy.Policy!.Arn!;
await iam
.attachRolePolicy({
RoleName: roleName,
PolicyArn: POLICY_ARN
})
.promise();
console.log("role");
console.log(role);
const assumed = await retry(
async () =>
sts
.assumeRole({
RoleArn: `arn:aws:iam::${await getAccountId()}:role/${roleName}`,
RoleSessionName: v4() + "-IAMCrafter"
})
.promise(),
{
retries: 3
}
);
try {
const scanner = makeApiGatewayScanner({ credentials: assumed.Credentials });
const results = await scanner.scanForPossibleInsecurePaths();
console.log("results");
console.log(results);
} catch (e) {
console.log("Failed with err;");
console.log(e);
} finally {
console.log(`Deleting attached role`);
await iam
.detachRolePolicy({
RoleName: roleName,
PolicyArn: POLICY_ARN
})
.promise();
await iam.deleteRole({ RoleName: roleName }).promise();
await iam.deletePolicy({ PolicyArn: POLICY_ARN }).promise();
}
};
exec();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment