GithubHelp home page GithubHelp logo

nessrest's Introduction

ness6rest.py - a REST interface to Nessus 6

Build Status PyPI Version

Dependencies:

  • Nessus 6.4.x
  • Python 2.7+ or 3.3+
  • requests module (install via pip)
  • The dependencies can be satisfied via pip install -r requirements.txt

Quick Install

pip install nessrest

Features:

  • Logins

    scan = ness6rest.Scanner(url="https://nessusscanner:8834", login="username", password="password")
    
    creds = [credentials.WindowsPassword(username="administrator", password="foobar"),
             credentials.WindowsPassword(username="administrator", password="barfoo"),
             credentials.SshPassword(username="nessususer", password="foobar")]
    
    scan.policy_add_creds(credentials=creds)
  • Build policies

    scan.upload(upload_file="file.audit")
    scan._policy_add_audit(category="Windows", filename="file.audit")
    scan.policy_add(name="Scripted Scan", plugins="21156")
  • Launch scans

    scan.scan_add(targets="192.168.0.1")
    scan.scan_run()
  • Schedule scans

    scan.scan_add(targets="192.168.0.1", start="YYYYMMDDTHHMMSS")
  • Parse scan results

    scan.scan_results()
  • Download KB for target

    kbs = scan.download_kbs()
    
    for hostname in kbs.keys():
        f = open(hostname, "w")
        f.write(kbs[hostname])
        f.close()
  • Output for ticketing/wiki format

Feature Requests:

  • Deleting of a schedule
  • Ability to change "tag" from CLI via config/CLI arg
  • Enforce supported versions of Nessus

Notes:

  • Proxies are not supported, although transparent proxies should work... transparently

nessrest - an example client

Suggested installation:

  • Find the path to your "site-packages" with: python -c "import sys; print(sys.path)"
  • Symlink ness6rest.py in the Git repo in the "site-packages" or "dist-packages" directory.
  • Test by issuing import ness6rest inside the Python interactive interpreter.

Specifying a ca_bundle

If you are using a corporate or self-signed SSL certificate, you can specify the path to a ca_bundle to use for verification by passing it to the Scanner initializer:

scan = ness6rest.Scanner(url="https://nessusscanner:8834", login="username", password="password", ca_bundle="/path/to/ca_bundle.pem")

If you are using the ness_rest client, you can pass this path on the command line using the --ca_bundle option.

Self-signed certificates

If you're running Nessus with a self-signed certificate, and you wish to disable SSL certificate checking, you can pass insecure=True to the Scanner initializer:

scan = ness6rest.Scanner(url="https://nessusscanner:8834", login="username", password="password", insecure=True)

If you're using the nessrest example client, it has an --insecure option that will do this.

Note that this will disable invalid SSL cerficate errors and should be used with caution.

Configuration file:

  • Copy ness_rest.conf.example to ness_rest.conf and configure for your scanner.
  • There are several valid paths for the location of the config file(in order):
  • The path passed from the CLI with --config
  • A permanent config file is searched for in the following locations:
    • $HOME/.ness_rest.conf
    • $HOME/.ness_rest/ness_rest.conf
    • /etc/ness_rest.conf
    • /etc/ness_rest/ness_rest.conf
    • $PWD/ness_rest.conf

Building modules:

  • To build a package to install via pip or easy_install, execute:
    • python setup.py sdist
  • The resulting build will be in $PWD/dist/nessrest-<version>.tar.gz

nessrest's People

Contributors

akobata avatar aleksandarristic avatar alexfrancow avatar benbergman avatar eest avatar frankbb avatar ianlovering avatar invisiblethreat avatar johndekroon avatar jpvriel avatar matteverson avatar mokuso avatar ppanczyk avatar rcarrillo avatar stefanoj3 avatar streckc avatar xorrbit avatar xychix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nessrest's Issues

nessus_download_all.py - 'PDF not yet supported'

I've noted that retrieval of reports as PDF is not yet supported via nessus_download_all.py (possible also the API).
Comments in code read

      # PDF not yet supported
      # python API wrapper nessrest returns the PDF as a string object instead of a byte object, making writing and correctly encoding the file a chore...
      # other formats can be written out in text mode

Are there plans to have this implemented?

does not work for version 6.4.3?

Nessus version: 6.4.3 (#35) LINUX

I tried the following:

#!/usr/bin/env python

from nessrest import ness6rest

scan = ness6rest.Scanner(url="https://127.0.0.1:8834", login="LOGIN", password="PASSWORD", insecure=True)
scan.action(action="scans", method="get")

And I get the following result

*****************START ERROR*****************
JSON    :
{}
{}
HEADERS :
{'X-Cookie': 'token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-type': 'application/json', 'Accept': 'text/plain'}
URL     : https://127.0.0.1:8834/scanners 
METHOD  : get
RESPONSE: 403


{
  "error": "You are not authorized to perform this request"
}
******************END ERROR******************

I use the same login/pass as to login to the UI btw. /scanners doesn't seem like the correct endpoint... But not sure though. Any ideas?

nessrest problem download a scan to pdf, html or csv. File output is corrupt.

Using mod: from nessrest import ness6rest
Objective: download a scan to a pdf, html or csv
I could not find the nessrest function to do this, so I use the function in python program: nessus6_scan_demo.py
Problem: every format output comes out corrupt file

import json
import requests
from nessrest import ness6rest
โ€œโ€โ€
Download scan results fuinction

โ€œโ€โ€
def add(name, desc, targets, pid):
scan = {'uuid': pid, 'settings': { 'name': name, 'description': desc, 'text_targets': targets}}
data = connect('POST', '/scans', data=scan)
return data['scan']

def get_history_ids(sid):
params = {'history_id': hid}
data = connect('GET', '/scans/{0}'.format(sid), params)
return data['info']

def export(sid, hid):
data = {'history_id': hid, 'format': 'nessus'}
data = connect('POST', '/scans/{0}/export'.format(sid), data=data)
fid = data['file']
while export_status(sid, fid) is False:
time.sleep(5)
return fid

def download(sid, fid):
data = connect('GET', '/scans/{0}/export/{1}/download'.format(sid, fid))
filename = 'nessus_{0}_{1}.nessus'.format(sid, fid)
print('Saving scan results to {0}.'.format(filename))
with open(filename, 'w') as f:
f.write(data)

scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozo", password="+=*&^%werT", insecure=True)
print("scan=%s"%(scan))

scan.policy_add(name="Test_Scan2_777.777.7.77",plugins="21156")
scan.scan_add(targets="777.777.7.77")
scan.scan_run()
''' Parse scan results '''
print(scan.scan_results())

print('')
scan_id = scan_data['id']
print(โ€˜'scan_id='%s'%(scan_id))
history_ids = get_history_ids(scan_id)
history_id = history_ids[scan_uuid]
print('history_id=%s'%(history_id))
print('Exporting the completed scan.')
file_id = export(scan_id, history_id)
download(scan_id, file_id)
print('Finish')

----------------------------------------------------------------------------------------

Run above python script
ERROR At: TypeError: must be str, not bytes f.write(data)
So I change it to: f.write(str(data))

-----------------------------------nessus------------------------------------------------

Run program again
It write the following file to my pc: nessus_67_1103118399.nessus
Buy I cannot display a nessus file on my window box. So I did the following

----------------------------------pdf----------------------------------------------------

Line: filename = 'nessus_{0}{1}.nessus'.format(sid, fid)
Change to: filename = 'nessus
{0}_{1}.pdf'.format(sid, fid)
Run program
It saves a pdf file: nessus_64_1006323990.pdf
I tried to read it using Adobe Reader, It could not display it.

----------------------------------html----------------------------------------------------

I tried: filename = 'nessus_{0}_{1}.html'.format(sid, fid)
Run
It saves a pdf file: nessus_61_1603712528.html
I tried to display it in explorer browser, but it look like the html was truncated.

--------------------------------csv----------------------------------------------------

I tried: filename = 'csv_{0}_{1}.csvl'.format(sid, fid)
Run
When I display the csv file on windows, it is unreadable, all the data is on line one.

-----------------------------------------------------------------------------------------

So I did the following change to: f.write(data)

f.write(data)

f.write(str(data))

f.write(data.decode('utf-8'))
Run
All of the output are corrupt.

--------------------------------------------------------------------------------------------

In mod: from nessrest import ness6rest

Do you have a working example, on downloading a scan to pdf, html or csv file?

Thanks for your help
Pythoncode17

Issue with getting scan result

Hi, I am trying to run a simple scan, and then download the report in the nessus format. i am using scan_download(), but all i get back is the content of the policy itself. May i have some help on figuring this out please? i am trying to get the report in nessus format after the scan is completed. Thanks in advance!

Here is the scan download piece of my script

scanner.scan_add(targets="127.0.0.1")
scanner.scan_run()
file = open("/tmp/ness_faraday_Nessus.nessus", "w")
file.write(scanner.download_scan())
file.close()

here is a tiny sample of the output

Good MDM Settings
66963
Good MDM Settings[entry]:Port :
Port :
entry


nessrest SSL Connection problem SSL certificate fail handshake

Objective: use nessrest to login to server Nessus 6.7.0, to perform a scan.

Problem: Our python program can not log in.

We are currently using:

โ€ข Python 3.4
โ€ข Security Center 5.3.2
โ€ข Nessus 6.7.0

Python Program: nessus_1.py

! /usr/local/bin/python

import json
import requests
from nessrest import ness6rest
scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL")
print('Exit Program')

Run nessus_1.py python program
Traceback (most recent call last):
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 544, in urlopen
body=body, headers=headers)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 341, in _make_request
self._validate_conn(conn)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 762, in validate_conn
conn.connect()
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connection.py", line 238, in connect
ssl_version=resolved_ssl_version)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\util\ssl
.py", line 256, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "C:\Python34\lib\ssl.py", line 364, in wrap_socket
_context=self)
File "C:\Python34\lib\ssl.py", line 578, in init
self.do_handshake()
File "C:\Python34\lib\ssl.py", line 805, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\adapters.py", line 370, in send
timeout=timeout
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 574, in urlopen
raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 211, in action
verify=verify, headers=headers)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\api.py", line 49, in request
response = session.request(method=method, url=url, *_kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 461, in request
resp = self.send(prep, *_send_kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "E:\tenable\nessus_1.py", line 6, in
scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL")
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 110, in init
self._login(login, password)
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 128, in _login
retry=False)
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 244, in action
raise SSLException('%s for %s.' % (ssl_error, url))
nessrest.ness6rest.SSLException: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598) for https://777.777.7.77:8834/session.

Python Program: nessus_2.py (Try insecure=True)

! /usr/local/bin/python

import json
import requests
from nessrest import ness6rest
scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL", insecure=True)
print('Finish')

Run nessus_2.py python program
_START ERROR_
JSON :
{}
{}
HEADERS :
{'X-Cookie': 'token=b2c217df90e152226fe81df5c8f1f814ac0dd86c070d5a2b', 'Content-type': 'application/json', 'Accept': 'text/plain'}
URL : https://777.777.7.77:8834/scanners
METHOD : get
RESPONSE: 403

{
"error": "You are not authorized to perform this request"
}

_END ERROR_
Finish

Python Program: nessus_3.py (try disable SSL Certificate)

! /usr/local/bin/python

import json
import requests
from nessrest import ness6rest

dissable SSL Certificate

requests.packages.urllib3.disable_warnings()
scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL", insecure=True)
print('Finish')

Run nessus_3.py python program
_START ERROR_
JSON :
{}
{}
HEADERS :
{'Content-type': 'application/json', 'Accept': 'text/plain', 'X-Cookie': 'token=9161ce642add6f95118b0e1f12328d611e7ca43de4a90120'}
URL : https://777.777.7.77:8834/scanners
METHOD : get
RESPONSE: 403

{
"error": "You are not authorized to perform this request"
}

_END ERROR_
Finish

Python Program: nessus_4.py (try using access_key and secret_key )

! /usr/local/bin/python

import json
import requests
from nessrest import ness6rest
access_key = '7777c8c98a1fdcb8a02dc2ccc2ad10d50f43a29ed2ee3f58a92b99ef2aeb74a3'
secret_key = '666664982d8aaf74f9351b544c5f06439a9a80a88f28cfeeb27105cda14b1da4'
headers = {'Content-type': 'application/json','X-ApiKeys': 'accessKey='+access_key+'; secretKey='+secret_key}

_dissable SSL Certificate

requests.packages.urllib3.disable_warnings()

scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL")
print('Exit Program')

Run nessus_4.py python program
Traceback (most recent call last):
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 544, in urlopen
body=body, headers=headers)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 341, in _make_request
self._validate_conn(conn)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 762, in validate_conn
conn.connect()
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connection.py", line 238, in connect
ssl_version=resolved_ssl_version)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\util\ssl
.py", line 256, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "C:\Python34\lib\ssl.py", line 364, in wrap_socket
_context=self)
File "C:\Python34\lib\ssl.py", line 578, in init
self.do_handshake()
File "C:\Python34\lib\ssl.py", line 805, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\adapters.py", line 370, in send
timeout=timeout
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 574, in urlopen
raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 211, in action
verify=verify, headers=headers)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\api.py", line 49, in request
response = session.request(method=method, url=url, *_kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 461, in request
resp = self.send(prep, *_send_kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "E:\tenable\nessus_4.py", line 12, in
scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL")
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 110, in init
self._login(login, password)
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 128, in _login
retry=False)
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 244, in action
raise SSLException('%s for %s.' % (ssl_error, url))
nessrest.ness6rest.SSLException: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598) for https://777.777.7.77:8834/session.

Python Program: nessus_5.py (try using ca_bundle, PEM certificate in the same directory)

! /usr/local/bin/python

import json
import requests
from nessrest import ness6rest

_dissable SSL Certificate

requests.packages.urllib3.disable_warnings()

PEM certifcate is store same directory as program

scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL", ca_bundle="neust_swt2.pem")
print('Exit Program')

Run nessus_5.py python program
Traceback (most recent call last):
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\util\ssl_.py", line 244, in ssl_wrap_socket
context.load_verify_locations(ca_certs)
FileNotFoundError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\adapters.py", line 370, in send
timeout=timeout
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 544, in urlopen
body=body, headers=headers)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 341, in _make_request
self._validate_conn(conn)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connectionpool.py", line 762, in validate_conn
conn.connect()
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\connection.py", line 238, in connect
ssl_version=resolved_ssl_version)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\packages\urllib3\util\ssl
.py", line 246, in ssl_wrap_socket
raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 211, in action
verify=verify, headers=headers)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\api.py", line 49, in request
response = session.request(method=method, url=url, *_kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 461, in request
resp = self.send(prep, *_send_kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "C:\Users\homersimpson\AppData\Roaming\Python\Python34\site-packages\requests\adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [Errno 2] No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "E:\tenable\nessus_5.py", line 9, in
scan = ness6rest.Scanner(url="https://777.777.7.77:8834", login="bozoclown", password="!++6678awoL", ca_bundle="neust_swt2.pem")
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 110, in init
self._login(login, password)
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 128, in _login
retry=False)
File "C:\Python34\lib\site-packages\nessrest\ness6rest.py", line 244, in action
raise SSLException('%s for %s.' % (ssl_error, url))
nessrest.ness6rest.SSLException: [Errno 2] No such file or directory for https://777.777.7.77:8834/session.

We tried Tenable Support, but they know nothing.

The GitHub forum is are only hope.

Thank You for your time.

Impossible to run a standard "basic network scan" via nessrest?

Hello,

I try to use nessrest to run a basic network scan, just like I would do in Nessus original GUI, where you do not have to create a policy to do that. Now I try to do that using nessrest, but as I get it, you cannot run a scan with a template only, you need to specify a policy.
This wouldn't be that big problem, if I could easily create a policy that will lead to a basic network scan, but I cannot find the plugin IDs that I have to pass to scan.policy_add to achieve this.

Is it possible to run a basic network scan via nessrest without creating a policy? If not, which plugin IDs are needed to create the policy to achieve a basic network scan?

Add --max_checks --network_timeout to ness_rest

Under-spec'd hosts will sometimes are very slow to respond. This is especially true of small VMs that are running java apps.

This will allow for the easing of multiple concurrent checks and the increasing of network timeouts.

"error": "Invalid Credentials"

scan.policy_set(name='port')
scans = scan.scan_add(targets='123.123.123.123,12.12.12.12',name='test223')
scan.scan_run()
scan.scan_results()

when i put many targets like 66.

_START ERROR_
Traceback (most recent call last):
File "/Users/wx/PycharmProjects/untitled/ds.py", line 44, in
JSON :
scan.scan_results()
{}
File "/Users/wx/python-env/lib/python2.7/site-packages/nessrest/ness6rest.py", line 902, in scan_results
{}
HEADERS :
self._scan_status()
File "/Users/wx/python-env/lib/python2.7/site-packages/nessrest/ness6rest.py", line 705, in _scan_status
{'X-Cookie': 'token=017', 'Content-type': 'application/json', 'Accept': 'text/plain'}
for scan in self.res["scans"]:
URL : https://1.1.1.1:8834/scans?folder_id=196
KeyError: 'scans'
METHOD : get
RESPONSE: 401

{
"error": "Invalid Credentials"
}

_END ERROR_
_START ERROR_
JSON :
{}
{}
HEADERS :
{'X-Cookie': 'token=017', 'Content-type': 'application/json', 'Accept': 'text/plain'}
URL : https://0.0.0.0:8834/session
METHOD : delete
RESPONSE: 401

{
"error": "Invalid Credentials"
}

_END ERROR_

Process finished with exit code 1

if i put two targets i not error

Cannot connect: Unknown_Protocol.

Hey all, sorry if this is a dumb question.

Currently I am using the restful API and I am trying to switch to this python method. However, for some reason, I am not able to connect to the host via my python script. it complains ab out the 'protocol. Not sure if it may be related to me switching my server to use port 443 instead of the default 8834.

Here is the odd error I get on it.

[SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:590) for https://ec2-ip-ip-ip-ip.compute-1.amazonaws.com:443/session.

If I do something like this, my API calls work using the regular resful api.

user@$ curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"username","password":"password"}' https://ec2-ip-ip-ip-ip.compute-1.amazonaws.com/scans

But, if I try this with my python script, it just sits and idles and eventually spits out the above error.


from nessrest import ness6rest

print 'Setting Connection Details'
nessus_url = "https://ec2-ip-ip-ip-ip.compute-1.amazonaws.com"
login = "username"
password = "password"

print 'connecting'
scan = ness6rest.Scanner(url=nessus_url, login=login, password=password, insecure=True)

print 'setting policy'
scan.policy_set(name="TestPolicy")

print 'setting target'
scan.scan_add(targets="ec2-10-100-10-72.compute-1.amazonaws.com")

print 'starting scan'
scan.scan_run()

I have also tried replacing the nessus URL to look like this, but to no avail.

nessus_url = "https://ec2-ip-ip-ip-ip.compute-1.amazonaws.com:443"

EDIT: When I try from another EC2 instance, it works fine. One thing I am thinking of, is my company blocks all non-standard ports. So only ports like 80, 443, 3389, 22, etc are open. So this is part of the reason I ask about ports, it seems like its having issues. But its hard for me to say. But my companies firewall is the whole reason I put Nessus on port 443.

EDIT2: Here is some ipython output.

---------------------------------------------------------------------------
SSLException                              Traceback (most recent call last)
<ipython-input-8-3c76815f5f15> in <module>()
----> 1 scan = ness6rest.Scanner(url="https://ec2-ip-ip-ip-ip.compute-1.amazonaws.com", login="username", password="password")

/Library/Python/2.7/site-packages/nessrest/ness6rest.pyc in __init__(self, url, login, password, api_akey, api_skey, insecure, ca_bundle)
    110         else:
    111             # Initial login to get our token for all subsequent transactions
--> 112             self._login(login, password)
    113
    114             # Register a call to the logout action automatically

/Library/Python/2.7/site-packages/nessrest/ness6rest.pyc in _login(self, login, password)
    128                     extra={"username": self.auth[0], "password": self.auth[1]},
    129                     private=True,
--> 130                     retry=False)
    131
    132         try:

/Library/Python/2.7/site-packages/nessrest/ness6rest.pyc in action(self, action, method, extra, files, json_req, download, private, retry)
    244                 return req.content
    245         except requests.exceptions.SSLError as ssl_error:
--> 246             raise SSLException('%s for %s.' % (ssl_error, url))
    247         except requests.exceptions.ConnectionError:
    248             raise Exception("Could not connect to %s.\nExiting!\n" % url)

Integers, not strings...

ness_rest -t ips -p id -n name --format -c ~/.ness_rest.conf
Scan name : NAme_02
Scan UUID : 5942be18-a841-a3a7-4fc8-3061b97623c360867d930bcec832
..............................
..............................
..............................
..................
Complete! Run time: 216 seconds.
results

Traceback (most recent call last):
File "/usr/local/bin/ness_rest", line 240, in
scan.scan_results()
File "/usr/local/lib/python2.7/site-packages/nessrest/ness6rest.py", line 646, in scan_results
for host in self.res["comphosts"]:
TypeError: list indices must be integers, not str

Fetch scan information

Could you please improve the documentation for this library, for example by adding code snippets for the various actions that can be performed.

Thanks,
Alex

DELETE /scans/{scan_id}/history returns an error

When trying to delete scan result history via the API, I'm getting an error. Specifically, I ran the following in the Python interactive interpreter:

>>> scanner.action(action="scans/1/history", method="DELETE", extra={'history_id':1})
*****************START ERROR*****************
JSON    :
{"history_id": 1}
{}
HEADERS :
{'X-ApiKeys': 'accessKey=791188a5491fa435581582080682c237acea64d2b3d2154c8fcaacf7932778d9; secretKey=d6d1499513383ca4e09a5026d22a36f5e6736bd60762bd60d334b92eccfa00e0', 'Content-type': 'application/json', 'Accept': 'text/plain'}
URL     : https://localhost:8834/scans/1/history 
METHOD  : DELETE
RESPONSE: 405


{
  "error": "The requested method is not allowed for this URL"
}

******************END ERROR******************

I also tried using Nessus' API documentation's built-in tester to try it, with the same result:

nessus_deletehistory

I realize this means the problem is probably with Nessus' API itself, but I'm not sure where the best place would be to report that.

Problem with Nessus REST API mod: from pynessus import Nessus

I trying to login to our nessus server using a python
My OS: Window 7
Using: Python 3.4
Using: Nessus 6.7.0

pip install pynessus
Successfully installed pynessus-0.9.1

My program

from pynessus import Nessus
localhost="https://777.777.7.77:8834"
server = Nessus(localhost, 8834)
if server.login(User("swgoat", "IknowNothingSeenothingHearnothing!")):
print("Success!")
else:
print("Fail!")

Program returns error when I run it:
File "E:\quarterly\RestApi.py", line 1, in
from pynessus import Nessus
ImportError: cannot import name 'Nessus'

So I tried

pip install python-nessus
ImportError: No module named 'nessus'

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in C:\Users\ngillem\AppData\Local\Temp\1\pip-build-clt5hx5_\python-nessus\

How can I get this to run.

Modify Existing Policy

Hello, I just started playing around with nessrest, and I love it. It makes interacting with the Nessus API much easier. However, I can't seem to figure out how to modify an existing Nessus policy with this module. Does anyone know how do that?

SSL: UNKNOWN_PROTOCOL

Getting SSL error even after using --insecure=True handle.

>>> ness6rest.Scanner(url="https://ohcinnessusscan:8834", login=os.environ['username'], password=os.environ['password'], insecure=True)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/vgori/my-venv-py2.7/lib/python2.7/site-packages/nessrest/ness6rest.py", line 112, in __init__
    self._login(login, password)
  File "/Users/vgori/my-venv-py2.7/lib/python2.7/site-packages/nessrest/ness6rest.py", line 130, in _login
    retry=False)
  File "/Users/vgori/my-venv-py2.7/lib/python2.7/site-packages/nessrest/ness6rest.py", line 246, in action
    raise SSLException('%s for %s.' % (ssl_error, url))
nessrest.ness6rest.SSLException: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:590) for https://ohcinnessusscan:8834/session.
>>> 
>>> ness6rest.Scanner(url="https://10.160.23.22:8834", login=os.environ['username'], password=os.environ['password'], insecure=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/vgori/my-venv-py2.7/lib/python2.7/site-packages/nessrest/ness6rest.py", line 112, in __init__
    self._login(login, password)
  File "/Users/vgori/my-venv-py2.7/lib/python2.7/site-packages/nessrest/ness6rest.py", line 130, in _login
    retry=False)
  File "/Users/vgori/my-venv-py2.7/lib/python2.7/site-packages/nessrest/ness6rest.py", line 246, in action
    raise SSLException('%s for %s.' % (ssl_error, url))
nessrest.ness6rest.SSLException: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:590) for https://10.160.23.22:8834/session

scan_details pulls nothing

Trying to use scan_details to try to pull the UUIDs of already existing scans. However, I pull nothing. Since I don't get an error from incorrect name (which I did when there was a typo) it tells me that the scan is being detect and accessed, but nothing reports out. The scan is there, and has results in it, so not sure if I am not using it properly or if there is a different way for me to get the UUID from al already existing scan.

In [8]: test_scan = scan.scan_details('Scan 1 - Test')
In [9]: print db_scan
None
In [10]: test_scan?
Type: NoneType
String form: None
Docstring:

EDIT: After doing some digging, I have noticed that the JSON outputs like this.

u,'Scan1-Test'

Here, I am able to get working uuids

In [19]: for scans in scan.res["scans"]:
...: print scans["uuid"]

But the minute I do this, it breaks.

In [22]: for scans in scan.res["scans"]:
...: if scans["name"] == 'Scan1-Test':
...: print scans["uuid"]

And I get what I need, partially, with a trick like this.

In [24]: for scans in scan.res["scans"]:
...: if '1' in scans["name"]:
...: print scans["uuid"]
...: else:
...: print 'nothing'
...:
41235231e-6b53-8f24-1ac4-ef08c2ertewrert436336db2312a4

So potential problem with the JSON unicoding?

Rest API python 3.5.2

The rest api for nessus occasionally, about half the time, throws exceptions when running on python 3.5.2. But the api runs on python 3.4.4 works correctly.

req.text hanging on download_scan->action

req.text on line 217 of ness6rest.py was hanging with high CPU usage when calling download_scan and returning a 61MB csv scan.

Here is an example trace when I hit Ctrl-C:
^CTraceback (most recent call last):
File "examplescript.py", line 117, in
fp.write(scanner.download_scan(export_format=args.format))
File "build/bdist.linux-x86_64/egg/nessrest/ness6rest.py", line 959, in download_scan
File "build/bdist.linux-x86_64/egg/nessrest/ness6rest.py", line 217, in action
File "/usr/lib/python2.7/site-packages/requests/models.py", line 765, in text
encoding = self.apparent_encoding
File "/usr/lib/python2.7/site-packages/requests/models.py", line 640, in apparent_encoding
return chardet.detect(self.content)['encoding']
File "/usr/lib/python2.7/site-packages/chardet/init.py", line 30, in detect
u.feed(aBuf)
File "/usr/lib/python2.7/site-packages/chardet/universaldetector.py", line 119, in feed
if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt:
File "/usr/lib/python2.7/site-packages/chardet/escprober.py", line 74, in feed
codingState = codingSM.next_state(wrap_ord(c))
File "/usr/lib/python2.7/site-packages/chardet/codingstatemachine.py", line 46, in next_state
byteCls = self._mModel['classTable'][wrap_ord(c)]
File "/usr/lib/python2.7/site-packages/chardet/compat.py", line 31, in wrap_ord
if sys.version_info < (3, 0) and isinstance(a, base_str):
KeyboardInterrupt

I changed line 217 to read "else:" and it is functional now, but i'm not certain if other features needed the previous logic "elif not req.text:", though it would seem to be mostly implied that it is not req.text if it already failed the first if condition.

The code section now reads:
if not download and req.text:
self.res = req.json()
else:
self.res = {}

No way to use template policies?

For PCI internal scans, we normally use the Internal PCI Network Scan template policy. However, it looks like the script only looks for user policies.

Error : (104, 'ECONNRESET') Facing this error.

I see below error while send request to download file. Can you please suggest what it could be ? Login timeout already set to 1020. So session cannot expire.

Download for file id 1711515533.
.
Error : (104, 'ECONNRESET')

Add support to feed uuid to get results.

I know its simple enough, but right now its a bit of a work around.

With the API as its built right now, I dont have the ability to download a scan that has existed. The only way to really download results is to kick off a scan, and then tell the script to download the file of the scans it kicked off. I run scans with thousands of hosts that can take a couple of days, so a script that runs and checks this is not entirely feasible. I also kick off more than one scan at once, so that also makes it hard to download results because the scan.self becomes the latest scan.

Right now, I have basically manually taken the download_scan function and manually filled it in from ID results I pulled elsewhere, but a function where I can call a second script to download specific scans based on ScanID/UUID later would be helpful.

Error: Invalid credentials on download attempt after longer scans

I have a script that runs a scan and downloads the .nessus output to storage. Downloading works fine for a short scan (~7 minutes) but I am having issues with longer scans, getting an error after scan completion:

*****************START ERROR*****************
JSON    :
{}
{}
HEADERS :
{'Content-type': 'application/json', 'X-Cookie': 'token=61eb3c358f4e5b33ce1236357c3d4e5ed94a7f1f602d24db', 'Accept': 'text/plain'}
URL     : https://nessus:8834/scans?folder_id=237 
METHOD  : get
RESPONSE: 401


{
  "error": "Invalid Credentials"
}


******************END ERROR******************

It seems that the session is expiring but attempts to reauthenticate and download the scan are unsuccessful.

Unexpected error during scan, reauthenticating...
*****************START ERROR*****************
JSON    :
{"format": "nessus"}
{}
HEADERS :
{'Content-type': 'application/json', 'X-Cookie': 'token=12537a94f482c9a9287666eb23922d81fe640e18a4040cc5', 'Accept': 'text/plain'}
URL     : https://mercury-nessus:8834/scans/288/export 
METHOD  : post
RESPONSE: 409


{
  "error": "Can not export running scans"
}


******************END ERROR******************

I would appreciate any help, my script below:

#!/usr/bin/env python

import argparse
import myapp as k
import ness6rest
import os

''' 
    Nessus REST API reference at:
    https://github.com/tenable/nessrest/blob/master/nessrest/ness6rest.py
'''

parser = argparse.ArgumentParser(description='Run a Nessus scan')
parser.add_argument('client', help='existing client name')
parser.add_argument('project', help='existing project name')
args = parser.parse_args()

client = args.client
project = args.project

# get current hosts list from project dir
project_path=k.get_client_dir(client)+'/'+project+'/'
with open(project_path+'endpoints.txt', "r") as f:
    endpoints = f.read().replace('\n', ',')

print('Loaded {} endpoint(s): {}'.format(str(endpoints.count(',')), endpoints))

# sign into Nessus, set insecure flag for self-signed cert set up
print('Signing into Nessus host: '+k.NESSUS_URL)
scan = ness6rest.Scanner(url=k.NESSUS_URL, login=k.NESSUS_USER, \
                         password=k.NESSUS_PASS, insecure=True)

# TODO scan log
# TODO k.gen_scan_id method
timestamp = k.get_timestamp()
myapp_scan_id = k.get_scan_id(timestamp)
print(timestamp+' myapp_scan_id: '+myapp_scan_id)

# place scan within client folder in Nessus webapp
scan._scan_tag(name=client)

# TODO investigate use of the ness_rest.conf files for setting up scan parameters
# the policy applied below must match an existing Nessus Policy
nessus_policy='Myapp Standard'
scan.policy_set(nessus_policy)
print('Running Nessus scan with policy: {}'.format(nessus_policy))
scan.scan_add(targets=endpoints, name=myapp_scan_id)#, tag='hello')

# save scan_id for download after reauthentication
nessus_scan_id=scan.scan_id
scan.scan_run()
scan._scan_status()

# ADDED BLOCK BELOW TO LOGIN AGAIN BUT NOT SUCCESSFUL
# TODO scan session >10 minutes seems returns credentials invalid error???
scan = ness6rest.Scanner(url=k.NESSUS_URL, login=k.NESSUS_USER, \
                         password=k.NESSUS_PASS, insecure=True)
# recover the previous scan_id 
scan.scan_id=nessus_scan_id

# write the XML scan output to storage
scan_output_xml=scan.download_scan().decode('utf-8')
scan_output_path=project_path+k.date_path_yyyy_mm()+myapp_scan_id+'.nessus'
print('Writing: '+scan_output_path)
os.makedirs(os.path.dirname(scan_output_path), exist_ok=True)
with open(scan_output_path, 'w') as f:
    f.write(scan_output_xml)

UUID Error when running a test scan

Hi,

I am trying to run a basic scan which returns an invalid uuid error. Please help
The code :
scan = ness6rest.Scanner(url='', login='', password='', insecure=True)
scan.scan_add(targets='')
scan.scan_run()

Attached a screenshot of the error
err

Use all plugins

How to select all(Or atleast OS relevant) plugins for the scans?

Breakfix issue: TypeError

ness_rest -t -p -n Safari --format -c ~/.ness_rest.conf --ssh_user NOPE --ssh_pass NOPE
Traceback (most recent call last):
File "/usr/local/bin/ness_rest", line 190, in
password=get_cred('ssh_pass')))
File "/usr/local/lib/python2.7/site-packages/nessrest/credentials.py", line 42, in init
super(SshPassword, self).init()
TypeError: must be type, not classobj

`policy_exists` fails if no policies exist

Trying to run policy_exists with ness6rest.Scanner when no policies exist returns the following.

In [14]: scan.policy_exists('test')
TypeError                                 Traceback (most recent call last)
<ipython-input-14-1cb8ff8a73e0> in <module>()
----> 1 scan.policy_exists('test')

/.../lib/python3.5/site-packages/nessrest/ness6rest.py in policy_exists(self, name)
    334         self.action(action="policies", method="get")
    335
--> 336         for policy in self.res["policies"]:
    337             if policy["name"] == name:
    338                 self.policy_id = policy["id"]

TypeError: 'NoneType' object is not iterable

could switch to using self.res.get("policies", [])

Cannot use library if the user has 'Standard' or 'Basic' permissions

I'm trying to use this library in least-privilege environment where the external app needs read permissions but does not and should not be able to modify anything upstream. Even testing with a 'standard' user, I am failing to access the system because the first thing the login attempts to do is access the /scanners URL, which makes sense because of the class (Scanner) but for example if I wanted to create a Scan object, it still tries to reference a scanner first.

Can we fix this so that a least-privilege account can access scan data?

nessrest doesn't use default /etc/ssl/certs ca bundle path

On debian/ubuntu, /etc/ssl/certs is a well known location where the systemwide ca bundle resides.

  1. Should nessus use the default CA store?
  2. Or should the user always explicitly supply it?

E.g. a nessus server is not commonly deployed using a public CA, but internal org CAs are often included in the OS-wide CA store.

OpenSSL and browsers are okay with the default store

openssl s_client -connect <fqdn>:8834 -verify_return_error
...
    Verify return code: 0 (ok)

nessrest isn't happy

ness_rest -c ness_rest_local.conf -p 10921 -t <target ip>
...
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
...

The following with --ca_bundle works

ness_rest -c ness_rest_local.conf -p 10921 -t <target ip> --ca_bundle /etc/ssl/certs

PEP8 and coding styles

Hello,

I think that this repo can be much better if you guys add some coding conventions.
It will be much more clearer than current.

PEP8, for example.

Can I fork and PEP8 all the code?

Thanks!

TypeError: __str__ returned non-string (type Error)

hello

python 2.7

import nessrest
import ness6rest

scan = ness6rest.Scanner(url="https://127.0.0.1:8834", login="root", password="123")

scan.scan_add(targets="127.0.0.1")
scan.scan_run()

if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6

TypeError: str returned non-string (type Error)

HTML Reports Empty - Fixed

When running the samples in the scripts directory with an export format of html, the report was coming back empty. I found that the issue was that the export request did not request any "chapter" sections and it appeared the default is now none. So in ness6rest.py in the download_scan function I added another export_format check to add the "chapters" parameter:

    if (export_format=="db"):
        data = {"format":"db","password":dbpasswd}
    else:
        if (export_format=="html"):
            chapters="vuln_hosts_summary;vuln_by_host"
            data = {'format': export_format, "chapters": chapters}
        else:
            data = {'format': export_format}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.