Accessing the nessus API with python – Interacting with server and client

Accessing the nessus API with python - Interacting with server and client

The nessrest module in Python is a library that can be used to interact with the REST API of the Nessus vulnerability scanner. It provides a high-level interface for creating and submitting requests to the API, as well as for parsing and processing responses. The nessrest module can be used to scan hosts and networks, manage scans, and retrieve vulnerability information. It can also be used to automate tasks, such as generating reports and exporting data.

The nessrest module is available on GitHub at https://github.com/tenable/nessrest. To use the module, you will need to install it using pip or easy_install. You will also need to create a Nessus account and obtain an API access token.

Here is an example of how to use the nessrest module to scan a host:

Python
import ness6rest

# Create a Nessus client
client = ness6rest.NessusClient('https://localhost:8080', 'api_key')

# Scan a host
client.scan_host('192.168.1.10')

This code will scan the host with the IP address 192.168.1.10 and return the results of the scan.

The nessrest module is a powerful tool that can be used to automate many Nessus tasks. It is a valuable tool for security professionals who need to manage and scan large networks.

Nessus Scanner Script

The provided Python script utilizes the ness6rest library to interact with Nessus, a vulnerability scanner. The script performs the following actions:

Python
#!/usr/bin/env python3

import ness6rest
import argparse

# Nessus server URL
nessus_url = "https://localhost:8834"

# Command-line argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('--login',  required=True)
parser.add_argument('--password', required=True)
args = parser.parse_args()

# Initialize Nessus scanner
scan = ness6rest.Scanner(url=nessus_url, login=args.login, password=args.password, insecure=True)

# Print a list of scans
print(scan.scan_list())

# Retrieve and print details of each scan
scans = scan.scan_list()['scans']
for detail_scan in scans:
    print(scan.scan_details(detail_scan['name']))

Explanation:

Shebang and Imports:

  • #!/usr/bin/env python3: Specifies the Python interpreter to be used.
  • import ness6rest: Imports the ness6rest library, which provides a Python interface for Nessus 6 RESTful API.
  • import argparse: Imports the argparse module for parsing command-line arguments.

Nessus Server URL:

Python
   nessus_url = "https://localhost:8834"
  • Defines the URL of the Nessus server. The script assumes the Nessus server is running locally on the default HTTPS port (8834). You may need to adjust this URL based on your Nessus server configuration.

Command-line Argument Parsing:

Python
   parser = argparse.ArgumentParser()
   parser.add_argument('--login',  required=True)
   parser.add_argument('--password', required=True)
   args = parser.parse_args()
  • Uses the argparse module to parse command-line arguments. The script expects --login and --password arguments, which are required.

Initialize Nessus Scanner:

Python
   scan = ness6rest.Scanner(url=nessus_url, login=args.login, password=args.password, insecure=True)
  • Creates an instance of the ness6rest.Scanner class, initializing it with the Nessus server URL, login credentials, and allowing an insecure connection (via insecure=True).

Print List of Scans:

Python
   print(scan.scan_list())
  • Calls the scan_list method to retrieve and print a list of available scans on the Nessus server.

Retrieve and Print Scan Details:

Python
   scans = scan.scan_list()['scans']
   for detail_scan in scans:
       print(scan.scan_details(detail_scan['name']))
  • Iterates through the list of scans obtained from scan_list.
  • Calls the scan_details method for each scan, providing the scan name, and prints the details of each scan.

Note:

  • The script assumes that Nessus is running on the specified URL (https://localhost:8834). Adjust the nessus_url variable if your Nessus server is located elsewhere or uses a different port.
  • The --login and --password command-line arguments are required for authenticating with the Nessus server.
  • Ensure the ness6rest library is installed before running the script (pip install nessrest).
  • Be cautious with storing sensitive information like login credentials. Consider using more secure methods, such as environment variables or configuration files, to handle authentication information.

Nessus Client Connect with nessus server

The provided Python script is a basic client for interacting with the Nessus API. It uses the requests library to perform HTTP requests to a Nessus server. The script is designed to log in to Nessus, retrieve server status, list scans, and print details about vulnerabilities.

Python
#!/usr/bin/env python3

import requests
import json
import argparse

class NessusClient():
    # Constructor to initialize NessusClient object
    def __init__(self, nessusServer, nessusPort):
        self.nessusServer = nessusServer
        self.nessusPort = nessusPort
        self.url = 'https://' + str(nessusServer) + ':' + str(nessusPort)
        self.token = None
        self.headers = {}
        self.bodyRequest = {}

    # Method to perform GET request
    def get_request(self, url):
        response = requests.get(url, data=self.bodyRequest, headers=self.headers, verify=False)
        return json.loads(response.content)

    # Method to perform POST request
    def post_request(self, url):
        response = requests.post(url, data=self.bodyRequest, headers=self.headers, verify=False)
        return json.loads(response.content)

    # Method to make a generic API request
    def request_api(self, service, params={}):
        self.headers = {'Host': str(self.nessusServer) + ':' + str(self.nessusPort),
                        'Content-type': 'application/x-www-form-urlencoded',
                        'X-Cookie': 'token=' + self.token}
        content = self.get_request(self.url + service)
        return content

    # Method to log in to the Nessus server
    def login(self, nessusUser, nessusPassword):
        headers = {'Host': str(self.nessusServer) + ':' + str(self.nessusPort),
                   'Content-type': 'application/x-www-form-urlencoded'}
        params = {'username': nessusUser, 'password': nessusPassword}
        self.bodyRequest.update(params)
        self.headers.update(headers)
        content = self.post_request(self.url + "/session")
        if "token" in content:
            self.token = content['token']
        return content

# Command-line argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('--user', required=True)
parser.add_argument('--password', required=True)
args = parser.parse_args()

# Extracting user and password from command-line arguments
user = args.user
password = args.password

# Creating a NessusClient instance
client = NessusClient('127.0.0.1', '8834')

# Logging in to Nessus server
client.login(user, password)

# Retrieving and printing Nessus server status
print(client.request_api('/server/status'))

# Retrieving a list of scans
scans = client.request_api('/scans')['scans']

# Printing details about each scan and its vulnerabilities
for scan in scans:
    vulnerabilities = client.request_api('/scans/' + str(scan['id']))['vulnerabilities']
    for vuln in vulnerabilities:
        print(vuln['plugin_family'], vuln['plugin_name'])

Explanation with Headings:

NessusClient Class:

Constructor (__init__):

  • Initializes a NessusClient object with the Nessus server address (nessusServer) and port (nessusPort).
  • Sets up the URL, token, headers, and bodyRequest attributes.

GET and POST Request Methods (get_request, post_request):

  • These methods perform HTTP GET and POST requests, respectively, using the requests library.
  • verify=False is used to ignore SSL certificate verification.

Generic API Request Method (request_api):

  • Makes a generic API request using the specified service and parameters.
  • Utilizes the get_request method and adds necessary headers.

Login Method (login):

  • Logs in to the Nessus server by sending a POST request to the /session endpoint.
  • Updates the token attribute if the login is successful.

Main Section:

Command-line Argument Parsing:

  • Uses argparse to parse command-line arguments (--user and --password).

Creating NessusClient Instance:

  • Creates an instance of the NessusClient class with the Nessus server address and port.

Logging In:

  • Calls the login method to authenticate with the Nessus server.

Retrieving and Printing Server Status:

  • Calls the request_api method to get and print the server status.

Retrieving List of Scans:

  • Calls the request_api method to get a list of scans.

Printing Vulnerabilities:

  • Iterates through the list of scans, retrieves details, and prints vulnerabilities for each scan.
Python
#!/usr/bin/env python3

import requests
import json
import argparse

class NessusClient():
    def __init__(self, nessusServer, nessusPort):
        self.nessusServer = nessusServer
        self.nessusPort = nessusPort
        self.url='https://'+str(nessusServer)+':'+str(nessusPort)
        self.token = None
        self.headers = {}
        self.bodyRequest = {}

    def get_request(self, url):
        response = requests.get(url, data=self.bodyRequest, headers=self.headers, verify=False)
        return json.loads(response.content)

    def post_request(self, url):
        response = requests.post(url, data=self.bodyRequest, headers=self.headers, verify=False)
        return json.loads(response.content)


    def request_api(self, service, params={}):
        self.headers={'Host': str(self.nessusServer)+':'+str(self.nessusPort),
                          'Content-type':'application/x-www-form-urlencoded',
                          'X-Cookie':'token='+self.token}
        print(self.headers)
        content = self.get_request(self.url+service)
        return content

    def login(self, nessusUser, nessusPassword):
        headers={'Host': str(self.nessusServer)+':'+str(self.nessusPort),
                          'Content-type':'application/x-www-form-urlencoded'}
        params={'username':nessusUser, 'password':nessusPassword}
        self.bodyRequest.update(params)
        self.headers.update(headers)
        print(self.headers)
        content = self.post_request(self.url+"/session")
        if "token" in content:
            self.token = content['token']
        return content



parser = argparse.ArgumentParser()
parser.add_argument('--user',  required=True)
parser.add_argument('--password', required=True)
args = parser.parse_args()

user=args.user
password=args.password

client = NessusClient('127.0.0.1','8834')
client.login(user,password)
print(client.request_api('/server/status'))
scans = client.request_api('/scans')['scans']

print(scans)

for scan in scans:
    vulnerabilities= client.request_api('/scans/'+str(scan['id']))['vulnerabilities']
    for vuln in vulnerabilities:
        print(vuln['plugin_family'],vuln['plugin_name'])

Note:

  • The script uses the requests library for making HTTP requests. Ensure it is installed (pip install requests).
  • The verify=False parameter in the requests is used to ignore SSL certificate verification. It might be necessary for self-signed certificates or testing environments but should be used with caution in production.
  • The script demonstrates basic functionality and can be extended for more complex interactions with the Nessus API.
Total
0
Shares

Leave a Reply

Previous Post
Understanding the Nessus vulnerability scanner

Understanding and Installing the Nessus vulnerability scanner

Next Post
The OpenVAS vulnerability scanner in python

The OpenVAS vulnerability scanner in python

Related Posts