Skip to content

Commit

Permalink
[pfsensible-generate-module] Some more error handling around connecti…
Browse files Browse the repository at this point in the history
…ng/logging in
  • Loading branch information
opoplawski committed Feb 7, 2025
1 parent 44651a8 commit a2f81e2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions GENERATING_MODULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
The process of writing basic pfsensible modules is hopefully greatly simplified by using
the pfsensible-generate-module script. The basic workflow is as follows:

* You need a test pfSense instance with ssh access enabled.
* Navigate in the pfSense web interface to the area you want to write a module for. This should be a page where you can edit
settings or one where you are adding an item.
* Copy the URL of the page - you will pass it to the `--url` option of the script.
Expand Down
18 changes: 16 additions & 2 deletions misc/pfsensible-generate-module
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,30 @@ if args.url is not None:
client = requests.Session()

# Retrieve the CSRF token first
r = client.get(login_url, verify=False)
try:
r = client.get(login_url, verify=False)
except requests.exceptions.ConnectionError as e:
print(f'Failed to connect to {login_url}: {e}', file=sys.stderr)
sys.exit(1)

csrf = re.search(".*name='__csrf_magic' value=\"([^\"]+)\".*", r.text, flags=re.MULTILINE).group(1)

# Login to the web interface
login_data = dict(login='Login', usernamefld=args.user, passwordfld=args.password, __csrf_magic=csrf)
r = client.post(login_url, data=login_data, verify=False)
csrf = re.search(".*name='__csrf_magic' value=\"([^\"]+)\".*", r.text, flags=re.MULTILINE).group(1)
if (args.verbose >= 4):
print(f'Login URL returned {r} {r.text}')
html = lxml.html.fromstring(r.text)
# <div class="col-sm-4 nowarning msgbox text-center text-danger"><h4>Username or Password incorrect</h4></div>
alert = html.xpath('//div[contains(@class,"text-danger")]/*[1]/text()')
if len(alert) > 0:
print(f'Login failed with "{alert[0]}"', file=sys.stderr)
sys.exit(1)

# Retrieve the configuration web page and parse it
r = client.get(args.url, verify=False)
if (args.verbose >= 4):
print(f'{args.url} returned {r} {r.text}')
html = lxml.html.fromstring(r.text)

elif args.urlfile is not None:
Expand Down

0 comments on commit a2f81e2

Please sign in to comment.