Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
HariboDev committed Sep 1, 2021
0 parents commit cb61d68
Show file tree
Hide file tree
Showing 15 changed files with 2,194 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
*.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out
6 changes: 6 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
3 changes: 3 additions & 0 deletions AwsAccessKeys.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Harrison Cannon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# AWS Access Keys

Periodically check to see if an access key is required a rotation. This application uses the AWS CDK to create 2 stacks:
- CheckKeysLambdaStack
- EventBridgeStack

Emails:
- Warning emails sent every day, 7 days (default) before being deleted.
- Deletion email sent after the 7 days (default) stating the keys have been deleted.

![Architecture Diagram](AwsAccessKeys.svg "Architecture Diagram")

## Configuration

To configure the stack, edit the following variables:

- `ADMIN_EMAIL_ADDRESSES`
- Necessity: Required
- Type: `Array<string>`
- Location: `REPO_ROOT/lib/lambdas/check-keys.ts`
- Description: Admin email addresses if username doesn't confirm to regex email expression.
- `SOURCE_EMAIL_ADDRESS`
- Necessity: Required
- Type: `string`
- Location: `REPO_ROOT/lib/lambdas/check-keys.ts`
- Description: The sender email address to use in SES.
- `EventBridge.Schedule.cron()`
- Necessity: Optional
- Default: `0, 0, *, *, *` (midnight, every day)
- Type: `EventBridge.CronOptions`
- Location: `REPO_ROOT/lib/event-bridge.ts`
- Description: Cron expression for EventBridge to use.
- `WARNING_AGE`
- Necessity: Optional
- Default: `7171200000` (83 days in ms)
- Type: `number`
- Location: `REPO_ROOT/lib/lambdas/check-keys.ts`
- Description: Minimum age of keys when warning emails are sent.
- `DELETE_AGE`
- Necessity: Optional
- Default: `7776000000` (90 days in ms)
- Type: `number`
- Location: `REPO_ROOT/lib/lambdas/check-keys.ts`
- Description: Maximum age of keys. Keys this age will be deleted.

## Deployment

To deploy these stacks, execute:

```sh
$ cdk deploy --all
```

## Destroy

To destroy the stacks, execute:

```sh
$ cdk destroy --all
```
13 changes: 13 additions & 0 deletions bin/aws-access-keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/env node
import 'source-map-support/register';
import * as CDK from '@aws-cdk/core';
import { CheckKeysLambdaStack } from '../lib/check-keys-lambda-stack';
import { EventBridgeStack } from '../lib/event-bridge';

const app = new CDK.App();

const checkKeysLambdaStack = new CheckKeysLambdaStack(app, 'CheckKeysLambdaStack');

const eventBridgeStack = new EventBridgeStack(app, 'EventBridgeStack', {
checkKeysLambdaFunction: checkKeysLambdaStack._CheckKeysLambdaFunction
});
18 changes: 18 additions & 0 deletions cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"app": "npx ts-node --prefer-ts-exts bin/aws-access-keys.ts",
"context": {
"@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
"@aws-cdk/core:enableStackNameDuplicates": "true",
"aws-cdk:enableDiffNoFail": "true",
"@aws-cdk/core:stackRelativeExports": "true",
"@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true,
"@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true,
"@aws-cdk/aws-kms:defaultKeyPolicies": true,
"@aws-cdk/aws-s3:grantWriteWithoutAcl": true,
"@aws-cdk/aws-ecs-patterns:removeDefaultDesiredCount": true,
"@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
"@aws-cdk/aws-efs:defaultEncryptionAtRest": true,
"@aws-cdk/aws-lambda:recognizeVersionProps": true,
"@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true
}
}
77 changes: 77 additions & 0 deletions lib/check-keys-lambda-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as CDK from '@aws-cdk/core';
import * as LambdaNodeJS from '@aws-cdk/aws-lambda-nodejs';
import * as path from 'path';
import * as Lambda from '@aws-cdk/aws-lambda';
import * as IAM from '@aws-cdk/aws-iam';

export class CheckKeysLambdaStack extends CDK.Stack {

public readonly _CheckKeysLambdaFunction: LambdaNodeJS.NodejsFunction;

constructor(scope: CDK.Construct, id: string, props?: CDK.StackProps) {
super(scope, id, props);

// ===================================================================
// Resource: Lambda Function Props
// ===================================================================

const nodeJsFunctionProps: LambdaNodeJS.NodejsFunctionProps = {
bundling: {
externalModules: [
'aws-sdk'
],
nodeModules: [
'es6-template-strings'
],
},
depsLockFilePath: path.join(__dirname, 'lambdas', 'package-lock.json'),
runtime: Lambda.Runtime.NODEJS_14_X,
timeout: CDK.Duration.seconds(10)
};

// ===================================================================
// Resource: Lambda Function Roles
// ===================================================================

const checkKeysLambdaRole = new IAM.Role(this, 'checkKeysLambdaRole', {
roleName: 'checkKeysLambdaRole',
assumedBy: new IAM.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
IAM.ManagedPolicy.fromAwsManagedPolicyName('AWSLambdaExecute')
]
});

checkKeysLambdaRole.addToPrincipalPolicy(new IAM.PolicyStatement({
effect: IAM.Effect.ALLOW,
actions: [
'iam:ListUsers',
'iam:ListAccessKeys',
'iam:DeleteAccessKey'
],
resources: [
'*'
]
}));

checkKeysLambdaRole.addToPrincipalPolicy(new IAM.PolicyStatement({
effect: IAM.Effect.ALLOW,
actions: [
'ses:SendEmail',
'ses:SendRawEmail'
],
resources: [
'*'
]
}));

// ===================================================================
// Resource: Lambda Function
// ===================================================================

this._CheckKeysLambdaFunction = new LambdaNodeJS.NodejsFunction(this, 'checkKeysLambda', {
entry: path.join(__dirname, 'lambdas', 'check-keys.ts'),
...nodeJsFunctionProps,
role: checkKeysLambdaRole
});
}
}
35 changes: 35 additions & 0 deletions lib/event-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as CDK from '@aws-cdk/core';
import * as LambdaNodeJS from '@aws-cdk/aws-lambda-nodejs';
import * as EventBridge from '@aws-cdk/aws-events';
import * as Targets from '@aws-cdk/aws-events-targets';

interface EventBridgeProps extends CDK.StackProps {
checkKeysLambdaFunction: LambdaNodeJS.NodejsFunction;
}

export class EventBridgeStack extends CDK.Stack {
constructor(scope: CDK.Construct, id: string, props: EventBridgeProps) {
super(scope, id, props);

const checkKeysLambdaFunction = props.checkKeysLambdaFunction;

// ===================================================================
// Resource: EventBridge Rule
// ===================================================================

const lambdaEventTarget = new Targets.LambdaFunction(checkKeysLambdaFunction);

new EventBridge.Rule(this, 'CheckAccessKeysRule', {
schedule: EventBridge.Schedule.cron({
minute: '0',
hour: '0',
month: '*',
weekDay: '*',
year: '*',
}),
targets: [
lambdaEventTarget
]
})
}
}
124 changes: 124 additions & 0 deletions lib/lambdas/check-keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import * as AWS from 'aws-sdk';

const template = require('es6-template-strings');

const iam: AWS.IAM = new AWS.IAM();
const ses: AWS.SES = new AWS.SES({
region: 'eu-west-1'
});

const WARNING_AGE: number = 1000 * 60 * 60 * 24 * 83;
const DELETE_AGE: number = 1000 * 60 * 60 * 24 * 90;

const WARNING_BODY: string = [
'Hi,',
'',
'${user} access key is about to expire. Please rotate it.',
'',
'User: ${userName}',
'Access Key: ${accessKeyId}'
].join('\n');

const DELETE_BODY: string = [
'Hi,',
'',
'${user} access key has expired. Please note it has been deleted.',
'',
'User: ${userName}',
'Access Key: ${accessKeyId}'
].join('\n');

const adminEmails: Array<string> = [
'ADMIN_EMAIL_ADDRESSES'
];

const sendEmail = async (recipients: Array<string>, subject: string, keyMeta: AWS.IAM.AccessKeyMetadata, severityBody: string) => {
let body: string = template(severityBody, {
user: recipients === adminEmails ? `${keyMeta.UserName}\'s` : 'Your',
userName: keyMeta.UserName,
accessKeyId: keyMeta.AccessKeyId
})

var params: AWS.SES.SendEmailRequest = {
Destination: {
ToAddresses: recipients,
},
Message: {
Subject: { Data: subject },
Body: {
Text: { Data: body },
},
},
Source: "SOURCE_EMAIL_ADDRESS",
};

try {
await ses.sendEmail(params).promise();
console.log("Email sent");
} catch (error) {
console.log(error);
}
};

export const handler = async (event: any = {}): Promise<any> => {
let users: AWS.IAM.ListUsersResponse;
try {
users = await iam.listUsers().promise();
} catch (error) {
console.log(error)
return;
}

await Promise.all(users.Users.map(async (user: AWS.IAM.User) => {
let accessKeyParams: AWS.IAM.ListAccessKeysRequest = {
UserName: user.UserName
};

let userAccessKeys: AWS.IAM.ListAccessKeysResponse

try {
userAccessKeys = await iam.listAccessKeys(accessKeyParams).promise();
} catch (error) {
console.log(error);
return;
}

await Promise.all(userAccessKeys.AccessKeyMetadata.map(async (accessKey: AWS.IAM.AccessKeyMetadata) => {
if (!accessKey.CreateDate || accessKey.Status !== 'Active' || !accessKey.AccessKeyId) {
return;
}

let severity: string = '';

if (new Date().getTime() - accessKey.CreateDate.getTime() > DELETE_AGE) {
try {
let deleteParams: AWS.IAM.DeleteAccessKeyRequest = {
UserName: accessKey.UserName,
AccessKeyId: accessKey.AccessKeyId
};

await iam.deleteAccessKey(deleteParams).promise();

severity = DELETE_BODY;
} catch (error) {
console.log(error);
}
} else if (new Date().getTime() - accessKey.CreateDate.getTime() > WARNING_AGE) {
severity = WARNING_BODY;
}

if (!severity) {
return;
}

let regexpEmail: RegExp = new RegExp('^[^\\s@]+@[^\\s@]+\.[^\\s@]+$');
let recipientEmails: Array<string> = adminEmails;

if (regexpEmail.test(user.UserName)) {
recipientEmails = [user.UserName];
}

await sendEmail(recipientEmails, 'AWS IAM Access Key', accessKey, severity);
}));
}));
};
Loading

0 comments on commit cb61d68

Please sign in to comment.