Original publication: View on Sweetcode (Archived)
by Wendy Segura
5 years ago | In IT Infrastructure | Python
Tenable Nessus is a network vulnerability scanner, and you use it to scan your assets to expose common vulnerabilities and misconfigurations. In this post, I will talk about how to use Nessus on EC2.
The tools we will be using are the Tenable Python SDK, AWS Python SDK, and Boto3 to launch a scan on AWS EC2. The first thing we need is our target — in this case, AWS EC2’s IP address is needed to use them as targets for the scan.
Since we are utilizing the AWS Python SDK, the first step is to connect to your AWS account, from which we will retrieve the EC2 IP addresses. You can use as many targets as you want, but for this example, I will take a random set of 5 EC2 targets.
Before jumping into the code, ensure you have installed Boto3 and have access to the AWS CLI:
import boto3
import random
import datetime
def ec2_connect():
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
return instances
Now filter instances and get a random sample of 5 public IP addresses:
def filter_ec2_instance(ec2_connect):
public_ips = [
each_instance.public_ip_address
for each_instance in ec2_connect
if each_instance.public_ip_address
]
return random.sample(public_ips, 5)
Create a target list for the Tenable scan:
def target_list(filter_ec2_instance):
return ','.join(filter_ec2_instance)
Generate your Tenable API access and secret key before proceeding.
import argparse
import os
import time
from tenable_io.client import TenableIOClient
parser = argparse.ArgumentParser(
description='configuration of Nessus Tenable account'
)
parser.add_argument('-a', '--tenable_key', required=True, help='access key')
parser.add_argument('-k', '--tenable_secret', required=True, help='secret key')
args = parser.parse_args()
tenable_key = args.tenable_key
tenable_secret = args.tenable_secret
Connect to the Tenable client:
def tenable_client():
return TenableIOClient(tenable_key, tenable_secret)
Create and launch the scan:
def create_scan(tenable_client):
timestr = time.strftime("%Y%m%d-%H%M%S")
scan_name = f"scanjob_{timestr}"
scan = tenable_client().scan_helper.create(
name=scan_name,
text_targets='target_list',
template='basic'
)
return scan
def launch_scan(create_scan):
output_path = f"/path/to/{create_scan.name}.pdf"
create_scan.launch().download(output_path)
assert os.path.isfile(output_path)
return output_path
Execution:
def main():
targets = filter_ec2_instance(ec2_connect())
scan = create_scan(tenable_client())
launch_scan(scan)
if __name__ == '__main__':
main()
Save this script and run it with your Tenable keys:
./script_name.py -a [Tenable Access Key] -k [Tenable Secret Key]
The generated scan report will appear in your specified path and in the Tenable console. You can also adapt the script for email notifications or AWS Lambda automation.