List Security Hub alerts using Python script

by Daniel Pham

List Security Hub alerts using Python script. In this article, I will share with you how to use Python script to list all alerts on Security Hub of an EC2 instance.

What happened to Security Hub?

If you have worked on AWS long enough or in a security role, you will have used Security Hub.

When I worked on Security Hub, we received a lot of alerts related to an EC2 instance running in the region.

This is not good for a security-sensitive environment, and it is very expensive when every alert is charged.

The situation is that I alerted about EC2 having a lot of CVE alerts on Security Hub.

But reporting to the parties will always require specific evidence. You cannot say it without showing them that it is true and happening.

The problem is that by default on AWS Console, Security Hub will only show 20 alerts per page. I have 23 pages for this EC2 instance.

So I cannot copy or take 23 pictures to send to the parties. That is not good.

List Security Hub alerts with Python script

Immediately, I thought of writing a Python script to do this. With 23 alert pages, I would have about 400-500 alerts that need to be listed.

With that many alerts, I can’t do it manually. Definitely not.

Oh, don’t ask why there are so many, because the parties involved install a lot of software in EC2 instances and patching all the software is not simple.

Here is the Python script to do this.

import boto3
import openpyxl
from openpyxl import Workbook

def get_ec2_findings(instance_arn):
    # Initialize Security Hub client
    client = boto3.client('securityhub')

    # Use paginator to iterate through all result pages
    paginator = client.get_paginator('get_findings')

    # Filter findings related to the EC2 instance and additional conditions
    page_iterator = paginator.paginate(
        Filters={
            'ResourceId': [{
                'Value': instance_arn,
                'Comparison': 'EQUALS'
            }],
            'WorkflowStatus': [{
                'Value': 'NEW',
                'Comparison': 'EQUALS'
            }],
            'RecordState': [{
                'Value': 'ACTIVE',
                'Comparison': 'EQUALS'
            }]
        }
    )

    # Aggregate list of findings from all pages
    all_findings = []
    for page in page_iterator:
        all_findings.extend(page['Findings'])
    
    return all_findings

def summarize_findings_by_severity(findings):
    # Initialize severity count
    severity_count = {
        "CRITICAL": 0,
        "HIGH": 0,
        "MEDIUM": 0,
        "LOW": 0,
        "INFORMATIONAL": 0
    }

    # Count findings by severity level
    for finding in findings:
        severity = finding['Severity'].get('Label', 'INFORMATIONAL')
        if severity in severity_count:
            severity_count[severity] += 1

    return severity_count

def export_findings_to_excel(findings, severity_summary, file_name):
    # Create a new workbook
    wb = Workbook()
    ws = wb.active
    ws.title = "Security Hub Findings"

    # Column headers
    headers = ["Id", "Title", "Description", "Severity", "Resource Type", "Resource Id", "Created At", "Updated At"]
    ws.append(headers)

    # Write findings data to Excel
    for finding in findings:
        finding_data = [
            finding.get('Id', 'N/A'),
            finding.get('Title', 'N/A'),
            finding.get('Description', 'N/A'),
            finding['Severity'].get('Label', 'N/A'),
            finding['Resources'][0].get('Type', 'N/A'),
            finding['Resources'][0].get('Id', 'N/A'),
            finding.get('CreatedAt', 'N/A'),
            finding.get('UpdatedAt', 'N/A')
        ]
        ws.append(finding_data)

    # Create a new sheet for the summary
    summary_ws = wb.create_sheet(title="Severity Summary")

    # Write summary headers
    summary_ws.append(["Severity Level", "Count"])

    # Write severity count data
    for severity, count in severity_summary.items():
        summary_ws.append([severity, count])

    # Save the Excel file
    wb.save(file_name)
    print(f"Findings and severity summary exported to {file_name}")

if __name__ == "__main__":
    # ARN of the EC2 instance to check. For ex: arn:aws:ec2:us-west-2:123456789012:instance/i-0abcd1234efgh5678
    instance_arn = "arn-ec2-instance"
    
    # Get list of findings
    findings = get_ec2_findings(instance_arn)

    # Summarize findings by severity
    severity_summary = summarize_findings_by_severity(findings)

    # Export results to Excel file
    export_findings_to_excel(findings, severity_summary, "security_hub_findings.xlsx")

The python script will:

  • The script retrieves security findings related to an EC2 instance from AWS Security Hub.
  • Summarize findings by severity.
  • Export findings and summaries to Excel for easy tracking and analysis.

How to use Python script to list Security Hub alerts

Copy the script content above to your computer and name the file main.py for example, put it in a folder.

Of course, your computer needs to have Python and AWS CLI installed. I will assume that you know how to use Python and AWS CLI. If not, please refer to the 2 links below.

Then, go to the folder where the script is located. Create a virtual env, yes, with Python it is always best to use a virtual env so as not to conflict with other things.

python -m venv venv

Activate venv.

source venv/bin/activate

Then, you will need to install some packages with pip.

pip install boto3 openpyxl

And then you log in to AWS with AWS CLI, if you have multiple AWS accounts (ie multiple profiles) then you should export the profile before executing the script.

export AWS_PROFILE=devopslite

Finally you execute the script.

python main.py

After a few minutes, you will receive a notification like the image below.

List Security Hub alerts using Python script
Run the Python script to list Security Hub alerts.

The resulting excel file will be like the image below, you will have 2 tabs. The first tab is a detailed list of alerts on the Security Hub of the EC2 instance. The second tab will be the total number of alerts based on the level Severity.

List Security Hub alerts using Python script
The first tab contains a detailed list of alerts.
List Security Hub alerts using Python script
The second tab contains the total number of alerts counted based on Severity level.

Now I can send this list to the stakeholders so they can check it.

Conclusion

The above script is a quick one I wrote for a small daily task of mine.

This might help someone who is doing the same job as me.

0 0 votes
Article Rating

You may also like

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

0
Would love your thoughts, please comment.x
()
x

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.