resource "aws_cloudwatch_event_rule" "new_service_alert" {
name = "new-service-alert"
description = "Trigger Lambda on new service creation or enabling"
event_pattern = jsonencode({
"source" : [
"aws.ec2", "aws.rds", "aws.config", "aws.guardduty",
"aws.securityhub", "aws.inspector2", "aws.eks", "aws.elasticloadbalancing",
"aws.cloudtrail", "aws.cloudwatch", "aws.ssm", "aws.marketplace", "aws.backup","aws.billingconsole"
],
"detail-type" : ["AWS API Call via CloudTrail"],
"detail" : {
"eventName" : [
{ "prefix" : "Enable" },
{ "prefix" : "Create" },
{ "prefix" : "Activate" },
"AcceptInvitation",
"EnableOrganizationAdminAccount",
"PurchaseReservedInstancesOffering",
"SubscribeToEvent",
"RunInstances",
"LaunchInstances"
]
}
})
}
resource "aws_lambda_permission" "allow_eventbridge" {
statement_id = "AllowExecutionFromEventBridge"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.alert_handler.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.new_service_alert.arn
}
resource "aws_cloudwatch_event_target" "lambda_target" {
rule = aws_cloudwatch_event_rule.new_service_alert.name
target_id = "InvokeLambda"
arn = aws_lambda_function.alert_handler.arn
}
data "archive_file" "lambda_zip" {
type = "zip"
source_dir = "${path.module}/lambda"
output_path = "${path.module}/lambda.zip"
}
resource "aws_lambda_function" "alert_handler" {
function_name = "new_service_alert_handler"
runtime = "nodejs18.x"
handler = "index.handler"
role = aws_iam_role.lambda_exec_role.arn
filename = data.archive_file.lambda_zip.output_path
source_code_hash = data.archive_file.lambda_zip.output_base64sha256
}
onst https = require('https');
const DINGTALK_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=?";
exports.handler = async (event) => {
console.log('Received event:', JSON.stringify(event, null, 2));
// 获取事件相关的信息
const service = event.detail?.eventName || 'UnknownEvent';
const eventTime = detail.eventTime || new Date().toISOString();
const sourceService = event.source || 'UnknownSource';
const identity = event.detail?.userIdentity || {};
const user = identity.arn || identity.principalId || 'UnknownUser';
const ignoredUser = identity.sessionContext?.sessionIssuer?.userName || 'UnknownUser';
const time = event.time || new Date().toISOString();
const region = event.region || 'UnknownRegion';
const consoleLink = `https://console.aws.amazon.com/cloudtrail/home?region=${region}#/events`;
const ignoredRoles = ['AWSServiceRoleForECS']; //添加忽略的role
if (ignoredRoles.some(role => ignoredUser.includes(role))) {
console.log('Ignored event from AWS service role:', ignoredUser);
return;
}
const ignoredServices = ['CreateLaunchTemplate']; //添加忽略的服务事件
if (ignoredServices.some(ignoredService => service.includes(ignoredService))) {
console.log('Ignored event from AWS service event:', service);
return;
}
const message = {
msgtype: "markdown",
markdown: {
title: "⚠️新服务启用警告",
text:
`### ⚠️AWS新服务启用警告n` +
`- **事件类型**: ${service}n` +
`- **来源服务**: ${sourceService}n` +
`- **操作者**: ${user}n` +
`- **时间**: ${eventTime}nn` +
`点击查看事件详情(CloudTrail)](${consoleLink})`
}
};
// 发送钉钉消息
const sendMessage = (data) => {
return new Promise((resolve, reject) => {
const req = https.request(DINGTALK_WEBHOOK, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve(body);
});
});
req.on('error', (error) => {
reject(error);
});
req.write(JSON.stringify(data));
req.end();
});
};
try {
const response = await sendMessage(message);
console.log('Message sent to DingTalk:', response);
} catch (error) {
console.error('Error sending message to DingTalk:', error);
}
};
原文始发于微信公众号(安全无界):AWS实现自动监控新服务
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论