Skip to content

Instantly share code, notes, and snippets.

@ffturan
Created October 22, 2020 01:06
Show Gist options
  • Save ffturan/619f47d8393a635afe322f79b8e13d05 to your computer and use it in GitHub Desktop.
Save ffturan/619f47d8393a635afe322f79b8e13d05 to your computer and use it in GitHub Desktop.
Analyze AWS VPC flow logs with Athena
# Export log format:
# ${version} ${account-id} ${interface-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${protocol} ${packets} ${bytes} ${start} ${end} ${action} ${log-status} ${vpc-id} ${subnet-id} ${instance-id} ${tcp-flags} ${type} ${pkt-srcaddr} ${pkt-dstaddr
CREATE EXTERNAL TABLE IF NOT EXISTS vpc_flow_logs_myawsaccount (
version int,
account string,
interfaceid string,
sourceaddress string,
destinationaddress string,
sourceport int,
destinationport int,
protocol int,
numpackets int,
numbytes bigint,
starttime int,
endtime int,
action string,
logstatus string,
vpcid string,
subnetid string,
instanceid string,
tcpflags int,
traffictype string,
packetsourceaddress string,
packetdestinationaddress string
)
PARTITIONED BY (dt string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ' '
LOCATION 's3://your-vpc-flow-logs-s3-bucket/AWSLogs/<aws account id>/vpcflowlogs/us-east-1/'
TBLPROPERTIES ("skip.header.line.count"="1");
# Create Partition
ALTER TABLE vpc_flow_logs_myawsaccount
ADD PARTITION (dt='2020-10-20')
location 's3://your-vpc-flow-logs-s3-bucket/AWSLogs/<aws account id>/vpcflowlogs/us-east-1/2020/10/20';
# Sample Queries
SELECT dt,SUM(numbytes) AS bytecount, SUM(numpackets) AS packetcount, sourceaddress, sourceport, destinationaddress, destinationport
FROM vpc_flow_logs_myawsaccount WHERE action='REJECT'
GROUP BY dt,sourceaddress,sourceport,destinationaddress,destinationport
ORDER BY bytecount DESC
Limit 50;
SELECT dt,SUM(numbytes) AS bytecount, SUM(numpackets) AS packetcount, sourceaddress, destinationaddress, destinationport
FROM vpc_flow_logs_myawsaccount WHERE action='ACCEPT' AND destinationport=22
GROUP BY dt,sourceaddress,destinationaddress,destinationport
ORDER BY bytecount DESC
Limit 500;
SELECT dt,sourceaddress, sourceport,destinationaddress, destinationport
FROM vpc_flow_logs_myawsaccount WHERE action='ACCEPT' AND destinationaddress LIKE '8.8.%.%'
GROUP BY dt,sourceaddress,sourceport,destinationaddress, destinationport
Limit 1000;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment