Giter Site home page Giter Site logo

ndejong / pfsense_fauxapi Goto Github PK

View Code? Open in Web Editor NEW
354.0 43.0 62.0 852 KB

REST based API interface for pfSense 2.3.x and 2.4.x to facilitate devops

License: Apache License 2.0

Shell 4.61% Makefile 1.44% PHP 93.96%
pfsense api restful-api pfsense-fauxapi devops

pfsense_fauxapi's Introduction

FauxAPI - v1.4

A REST API interface for pfSense 2.3.x, 2.4.x, 2.5.x to facilitate devops:-

Additionally available are a set of client libraries that hence make programmatic access and management of pfSense hosts for devops tasks feasible.

Important

  • You MUST (manually) setup your /etc/fauxapi/credentials.ini file on the pfSense host before you continue, see the API Authentication section below.
  • You MUST (manually) setup a /etc/fauxapi/pfsense_function_calls.txt file if you want to use the function_call API method. You may wish to copy the sample /etc/fauxapi/pfsense_function_calls.sample.txt as a starting point.

API Action Summary

  • alias_update_urltables - Causes the pfSense host to immediately update any urltable alias entries from their (remote) source URLs.
  • config_backup - Causes the system to take a configuration backup and add it to the regular set of system change backups.
  • config_backup_list - Returns a list of the currently available system configuration backups.
  • config_get - Returns the full system configuration as a JSON formatted string.
  • config_patch - Patch the system config with a granular piece of new configuration.
  • config_reload - Causes the pfSense system to perform an internal reload of the config.xml file.
  • config_restore - Restores the pfSense system to the named backup configuration.
  • config_set - Sets a full system configuration and (by default) reloads once successfully written and tested.
  • function_call - Call directly a pfSense PHP function with API user supplied parameters.
  • gateway_status - Returns gateway status data.
  • interface_stats - Returns statistics and information about an interface.
  • rule_get - Returns the numbered list of loaded pf rules from a pfctl -sr -vv command on the pfSense host.
  • send_event - Performs a pfSense "send_event" command to cause various pfSense system actions.
  • system_reboot - Reboots the pfSense system.
  • system_stats - Returns various useful system stats.
  • system_info - Returns various useful system info.

Approach

At its core FauxAPI simply reads the core pfSense config.xml file, converts it to JSON and returns to the API caller. Similarly it can take a JSON formatted configuration and write it to the pfSense config.xml and handles the required reload operations. The ability to programmatically interface with a running pfSense host(s) is enormously useful however it should also be obvious that this provides the API user the ability to create configurations that can break your pfSense system.

FauxAPI provides easy backup and restore API interfaces that by default store configuration backups on all configuration write operations thus it is very easy to roll-back even if the API user manages to deploy a "very broken" configuration.

Multiple sanity checks take place to make sure a user provided JSON config will correctly convert into the (slightly quirky) pfSense XML config.xml format and then reload as expected in the same way. However, because it is not a real per-action application-layer interface it is still possible for the API caller to create configuration changes that make no sense and can potentially disrupt your pfSense system - as the package name states, it is a "Faux" API to pfSense filling a gap in functionality with the current pfSense product.

Because FauxAPI is a utility that interfaces with the pfSense config.xml there are some cases where reloading the configuration file is not enough and you may need to "tickle" pfSense a little more to do what you want. This is not common however a good example is getting newly defined network interfaces or VLANs to be recognized. These situations are easily handled by calling the send_event action with the payload interface reload all - see the example included below and refer to a the resolution to Issue #10

NB: As at FauxAPI v1.2 the function_call action has been introduced that now provides the ability to issue function calls directly into pfSense.

Installation

Until the FauxAPI is added to the pfSense FreeBSD-ports tree you will need to install manually from root as shown:-

set fauxapi_base_package_url='https://raw.githubusercontent.com/ndejong/pfsense_fauxapi_packages/master'
set fauxapi_latest=`fetch -qo - ${fauxapi_base_package_url}/LATEST`
fetch ${fauxapi_base_package_url}/${fauxapi_latest}
pkg-static install ${fauxapi_latest}

Installation and de-installation is quite straight forward, further examples can be found in the README.md located here.

Refer to the published package SHA256SUMS

Hint: if not already, consider installing the jq tool on your local machine (not pfSense host) to pipe and manage JSON outputs from FauxAPI - https://stedolan.github.io/jq/

NB: you MUST at least setup your /etc/fauxapi/credentials.ini file on the pfSense host before you continue, see the API Authentication section below.

Client libraries

Python

A Python interface to pfSense was perhaps the most desired end-goal at the onset of the FauxAPI package project. Anyone that has tried to parse the pfSense config.xml files using a Python based library will understand that things don't quite work out as expected or desired.

The Python client-library can be easily installed from PyPi as such

pip3 install pfsense-fauxapi

Package Status: PyPi Build Status

Use of the package should be easy enough as shown

import pprint, sys
from PfsenseFauxapi.PfsenseFauxapi import PfsenseFauxapi
PfsenseFauxapi = PfsenseFauxapi('<host-address>', '<fauxapi-key>', '<fauxapi-secret>')

aliases = PfsenseFauxapi.config_get('aliases')
## perform some kind of manipulation to `aliases` here ##
pprint.pprint(PfsenseFauxapi.config_set(aliases, 'aliases'))

It is recommended to review the Python code examples to observe worked examples with the client library. Of small note is that the Python library supports the ability to get and set single sections of the pfSense system, not just the entire system configuration as with the Bash library.

Python examples

  • usergroup-management.py - example code that provides the ability to get_users, add_user, manage_user, remove_user and perform the same functions on groups.
  • update-aws-aliases.py - example code that pulls in the latest AWS ip-ranges.json data, parses it and injects them into the pfSense aliases section if required.
  • function-iterate.py - iterates (almost) all the FauxAPI functions to confirm operation.

Command Line

As distinct from the Bash library as described below the Python pip also introduces a command-line tool to interact with the API, which makes a wide range of actions possible directly from the command line, for example

fauxapi --host 192.168.1.200 gateway_status | jq .

Bash

The Bash client library makes it possible to add a line with source pfsense-fauxapi.sh to your bash script and then access a pfSense host configuration directly as a JSON string

source pfsense-fauxapi.sh
export fauxapi_auth=$(fauxapi_auth <fauxapi-key> <fauxapi-secret>)

fauxapi_config_get <host-address> | jq .data.config > /tmp/config.json
## perform some kind of manipulation to `/tmp/config.json` here ##
fauxapi_config_set <host-address> /tmp/config.json

It is recommended to review the commented out samples in the provided fauxapi-sample.sh file that cover all possible FauxAPI calls to gain a better idea on usage.

NodeJS/TypeScript

A NodeJS client has been developed by a third party and is available here

PHP

A PHP client has been developed by a third party and is available here

API Authentication

A deliberate design decision to decouple FauxAPI authentication from both the pfSense user authentication and the pfSense config.xml system. This was done to limit the possibility of an accidental API change that removes access to the host. It also seems more prudent to only establish API user(s) manually via the FauxAPI /etc/fauxapi/credentials.ini file - happy to receive feedback about this approach.

The two sample FauxAPI keys (PFFAexample01 and PFFAexample02) and their associated secrets in the sample credentials.sample.ini file are hard-coded to be inoperative, you must create entirely new values before your client scripts will be able to issue commands to FauxAPI.

You can start your own /etc/fauxapi/credentials.ini file by copying the sample file provided in credentials.sample.ini

API authentication itself is performed on a per-call basis with the auth value inserted as an additional fauxapi-auth HTTP request header, it can be calculated as such:-

fauxapi-auth: <apikey>:<timestamp>:<nonce>:<hash>

For example:-
fauxapi-auth: PFFA4797d073:20161119Z144328:833a45d8:9c4f96ab042f5140386178618be1ae40adc68dd9fd6b158fb82c99f3aaa2bb55

Where the <hash> value is calculated like so:-

<hash> = sha256(<apisecret><timestamp><nonce>)

NB: that the timestamp value is internally passed to the PHP strtotime function which can interpret a wide variety of timestamp formats together with a timezone. A nice tidy timestamp format that the strtotime PHP function is able to process can be obtained using bash command date --utc +%Y%m%dZ%H%M%S where the Z date-time seperator hence also specifies the UTC timezone.

This is all handled in the client libraries provided, but as can be seen it is relatively easy to implement even in a Bash shell script.

Getting the API credentials right seems to be a common source of confusion in getting started with FauxAPI because the rules about valid API keys and secret values are pedantic to help make ensure poor choices are not made.

The API key + API secret values that you will need to create in /etc/fauxapi/credentials.ini have the following rules:-

  • <apikey_value> and <apisecret_value> may have alphanumeric chars ONLY!
  • <apikey_value> MUST start with the prefix PFFA (pfSense Faux API)
  • <apikey_value> MUST be >= 12 chars AND <= 40 chars in total length
  • <apisecret_value> MUST be >= 40 chars AND <= 128 chars in length
  • you must not use the sample key/secret in the credentials.ini since they are hard coded to fail.

To make things easier consider using the following shell commands to generate valid values:-

apikey_value

echo PFFA`head /dev/urandom | base64 -w0 | tr -d /+= | head -c 20`

apisecret_value

echo `head /dev/urandom | base64 -w0 | tr -d /+= | head -c 60`

NB: Make sure the client side clock is within 60 seconds of the pfSense host clock else the auth token values calculated by the client will not be valid - 60 seconds seems tight, however, provided you are using NTP to look after your system time it's quite unlikely to cause issues - happy to receive feedback about this.

Shout Out: Seeking feedback on the API authentication, many developers seem to stumble here - if you feel something could be improved without compromising security then submit an Issue ticket via Github.

API Authorization

The file /etc/fauxapi/credentials.ini additionally provides a method to restrict the API actions available to the API key using the permit configuration parameter. Permits are comma delimited and may contain * wildcards to match more than one rule as shown in the example below.

[PFFAexample01]
secret = abcdefghijklmnopqrstuvwxyz0123456789abcd
permit = alias_*, config_*, gateway_*, rule_*, send_*, system_*, function_*
comment = example key PFFAexample01 - hardcoded to be inoperative

Debugging

FauxAPI comes with awesome debug logging capability, simply insert __debug=true as a URL request parameter and the response data will contain rich debugging log data about the flow of the request.

If you are looking for more debugging at various points feel free to submit a pull request or lodge an issue describing your requirement and I'll see what can be done to accommodate.

Logging

FauxAPI actions are sent to the system syslog via a call to the PHP syslog() function thus causing all FauxAPI actions to be logged and auditable on a per action (callid) basis which provide the full basis for the call, for example:-

Jul  3 04:37:59 pfSense php-fpm[55897]: {"INFO":"20180703Z043759 :: fauxapi\\v1\\fauxApi::__call","DATA":{"user_action":"alias_update_urltables","callid":"5b3afda73e7c9","client_ip":"192.168.1.5"},"source":"fauxapi"}
Jul  3 04:37:59 pfSense php-fpm[55897]: {"INFO":"20180703Z043759 :: valid auth for call","DATA":{"apikey":"PFFAdevtrash","callid":"5b3afda73e7c9","client_ip":"192.168.1.5"},"source":"fauxapi"}

Enabling debugging yields considerably more logging data to assist with tracking down issues if you encounter them - you may review the logs via the pfSense GUI as usual unser Status->System Logs->General or via the console using the clog tool

$ clog /var/log/system.log | grep fauxapi

Configuration Backups

All configuration edits through FauxAPI create configuration backups in the same way as pfSense does with the webapp GUI.

These backups are available in the same way as edits through the pfSense GUI and are thus able to be reviewed and diff'd in the same way under Diagnostics->Backup & Restore->Config History.

Changes made through the FauxAPI carry configuration change descriptions that name the unique callid which can then be tied to logs if required for full usage audit and change tracking.

FauxAPI functions that cause write operations to the system config config.xml return reference to a backup file of the configuration immediately previous to the change.

API REST Actions

The following REST based API actions are provided, example cURL call request examples are provided for each. The API user is perhaps more likely to interface with the client libraries as documented above rather than directly with these REST end-points.

The framework around the FauxAPI has been put together with the idea of being able to easily add more actions at a later time, if you have ideas for actions that might be useful be sure to get in contact.

NB: the cURL requests below use the '--insecure' switch because many pfSense deployments do not deploy certificate chain signed SSL certificates. A reasonable improvement in this regard might be to implement certificate pinning at the client side to hence remove scope for man-in-middle concerns.


alias_update_urltables

  • Causes the pfSense host to immediately update any urltable alias entries from their (remote) source URLs. Optionally update just one table by specifying the table name, else all tables are updated.
  • HTTP: GET
  • Params:
    • table (optional, default = null)

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=alias_update_urltables"

Example Response

{
  "callid": "598ec756b4d09",
  "action": "alias_update_urltables",
  "message": "ok",
  "data": {
    "updates": {
      "bruteforceblocker": {
        "url": "https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/bruteforceblocker.ipset",
        "status": [
          "no changes."
        ]
      }
    }
  }
}

config_backup

  • Causes the system to take a configuration backup and add it to the regular set of pfSense system backups at /cf/conf/backup/
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=config_backup"

Example Response

{
  "callid": "583012fea254f",
  "action": "config_backup",
  "message": "ok",
  "data": {
    "backup_config_file": "/cf/conf/backup/config-1479545598.xml"
  }
}

config_backup_list

  • Returns a list of the currently available pfSense system configuration backups.
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=config_backup_list"

Example Response

{
  "callid": "583065cb670db",
  "action": "config_backup_list",
  "message": "ok",
  "data": {
    "backup_files": [
      {
        "filename": "/cf/conf/backup/config-1479545598.xml",
        "timestamp": "20161119Z144635",
        "description": "[email protected]: update via fauxapi for callid: 583012fea254f",
        "version": "15.5",
        "filesize": 18535
      },
      ....

config_get

  • Returns the system configuration as a JSON formatted string. Additionally, using the optional config_file parameter it is possible to retrieve backup configurations by providing the full path to it under the /cf/conf/backup path.
  • HTTP: GET
  • Params:
    • config_file (optional, default=/cf/config/config.xml)

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=config_get"

Example Response

{
    "callid": "583012fe39f79",
    "action": "config_get",
    "message": "ok",
    "data": {
      "config_file": "/cf/conf/config.xml",
      "config": {
        "version": "15.5",
        "staticroutes": "",
        "snmpd": {
          "syscontact": "",
          "rocommunity": "public",
          "syslocation": ""
        },
        "shaper": "",
        "installedpackages": {
          "pfblockerngsouthamerica": {
            "config": [
             ....

Hint: use jq to parse the response JSON and obtain the config only, as such:-

cat /tmp/faux-config-get-output-from-curl.json | jq .data.config > /tmp/config.json

config_patch

  • Allows the API user to patch the system configuration with the existing system config
  • A config_patch call allows the API user to supply the partial configuration to be updated which is quite different to the config_set function that requires the full configuration to be posted.
  • HTTP: POST
  • Params:
    • do_backup (optional, default = true)
    • do_reload (optional, default = true)

Example Request

cat > /tmp/config_patch.json <<EOF
{
  "system": {
    "dnsserver": [
      "8.8.8.8",
      "8.8.4.4"
    ],
    "hostname": "newhostname"
  }
}
EOF

curl \
    -X POST \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    --header "Content-Type: application/json" \
    --data @/tmp/config_patch.json \
    "https://<host-address>/fauxapi/v1/?action=config_patch"

Example Response

{
  "callid": "5b3b506f72670",
  "action": "config_patch",
  "message": "ok",
  "data": {
    "do_backup": true,
    "do_reload": true,
    "previous_config_file": "/cf/conf/backup/config-1530613871.xml"
  }

config_reload

  • Causes the pfSense system to perform a reload action of the config.xml file, by default this happens when the config_set action occurs hence there is normally no need to explicitly call this after a config_set action.
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=config_reload"

Example Response

{
  "callid": "5831226e18326",
  "action": "config_reload",
  "message": "ok"
}

config_restore

  • Restores the pfSense system to the named backup configuration.
  • HTTP: GET
  • Params:
    • config_file (required, full path to the backup file to restore)

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=config_restore&config_file=/cf/conf/backup/config-1479545598.xml"

Example Response

{
  "callid": "583126192a789",
  "action": "config_restore",
  "message": "ok",
  "data": {
    "config_file": "/cf/conf/backup/config-1479545598.xml"
  }
}

config_set

  • Sets a full system configuration and (by default) takes a system config backup and (by default) causes the system config to be reloaded once successfully written and tested.
  • NB1: be sure to pass the FULL system configuration here, not just the piece you wish to adjust! Consider the config_patch or config_item_set functions if you wish to adjust the configuration in more granular ways.
  • NB2: if you are pulling down the result of a config_get call, be sure to parse that response data to obtain the config data only under the key .data.config
  • HTTP: POST
  • Params:
    • do_backup (optional, default = true)
    • do_reload (optional, default = true)

Example Request

curl \
    -X POST \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    --header "Content-Type: application/json" \
    --data @/tmp/config.json \
    "https://<host-address>/fauxapi/v1/?action=config_set"

Example Response

{
  "callid": "5b3b50e8b1bc6",
  "action": "config_set",
  "message": "ok",
  "data": {
    "do_backup": true,
    "do_reload": true,
    "previous_config_file": "/cf/conf/backup/config-1530613992.xml"
  }
}

function_call

  • Call directly a pfSense PHP function with API user supplied parameters. Note that is action is a VERY raw interface into the inner workings of pfSense and it is not recommended for API users that do not have a solid understanding of PHP and pfSense. Additionally, not all pfSense functions are appropriate to be called through the FauxAPI and only very limited testing has been performed against the possible outcomes and responses. It is possible to harm your pfSense system if you do not 100% understand what is going on.
  • Functions to be called via this interface MUST be defined in the file /etc/pfsense_function_calls.txt only a handful very basic and read-only pfSense functions are enabled by default.
  • You can start your own /etc/fauxapi/pfsense_function_calls.txt file by copying the sample file provided in pfsense_function_calls.sample.txt
  • HTTP: POST
  • Params: none

Example Request

curl \
    -X POST \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    --header "Content-Type: application/json" \
    --data "{\"function\": \"get_services\"}" \
    "https://<host-address>/fauxapi/v1/?action=function_call"

Example Response

{
  "callid": "59a29e5017905",
  "action": "function_call",
  "message": "ok",
  "data": {
    "return": [
      {
        "name": "unbound",
        "description": "DNS Resolver"
      },
      {
        "name": "ntpd",
        "description": "NTP clock sync"
      },
      ....

gateway_status

  • Returns gateway status data.
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=gateway_status"

Example Response

{
  "callid": "598ecf3e7011e",
  "action": "gateway_status",
  "message": "ok",
  "data": {
    "gateway_status": {
      "10.22.33.1": {
        "monitorip": "8.8.8.8",
        "srcip": "10.22.33.100",
        "name": "GW_WAN",
        "delay": "4.415ms",
        "stddev": "3.239ms",
        "loss": "0.0%",
        "status": "none"
      }
    }
  }
}

interface_stats

  • Returns interface statistics data and information - the real interface name must be provided not an alias of the interface such as "WAN" or "LAN"
  • HTTP: GET
  • Params:
    • interface (required)

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=interface_stats&interface=em0"

Example Response

{
  "callid": "5b3a5bce65d01",
  "action": "interface_stats",
  "message": "ok",
  "data": {
    "stats": {
      "inpkts": 267017,
      "inbytes": 21133408,
      "outpkts": 205860,
      "outbytes": 8923046,
      "inerrs": 0,
      "outerrs": 0,
      "collisions": 0,
      "inmcasts": 61618,
      "outmcasts": 73,
      "unsuppproto": 0,
      "mtu": 1500
    }
  }
}

rule_get

  • Returns the numbered list of loaded pf rules from a pfctl -sr -vv command on the pfSense host. An empty rule_number parameter causes all rules to be returned.
  • HTTP: GET
  • Params:
    • rule_number (optional, default = null)

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=rule_get&rule_number=5"

Example Response

{
  "callid": "583c279b56958",
  "action": "rule_get",
  "message": "ok",
  "data": {
    "rules": [
      {
        "number": 5,
        "rule": "anchor \"openvpn/*\" all",
        "evaluations": "14134",
        "packets": "0",
        "bytes": "0",
        "states": "0",
        "inserted": "21188",
        "statecreations": "0"
      }
    ]
  }
}

send_event

  • Performs a pfSense "send_event" command to cause various pfSense system actions as is also available through the pfSense console interface. The following standard pfSense send_event combinations are permitted:-
    • filter: reload, sync
    • interface: all, newip, reconfigure
    • service: reload, restart, sync
  • HTTP: POST
  • Params: none

Example Request

curl \
    -X POST \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    --header "Content-Type: application/json" \
    --data "[\"interface reload all\"]" \
    "https://<host-address>/fauxapi/v1/?action=send_event"

Example Response

{
  "callid": "58312bb3398bc",
  "action": "send_event",
  "message": "ok"
}

system_reboot

  • Just as it says, reboots the system.
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=system_reboot"

Example Response

{
  "callid": "58312bb3487ac",
  "action": "system_reboot",
  "message": "ok"
}

system_stats

  • Returns various useful system stats.
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=system_stats"

Example Response

{
  "callid": "5b3b511655589",
  "action": "system_stats",
  "message": "ok",
  "data": {
    "stats": {
      "cpu": "20770421|20494981",
      "mem": "20",
      "uptime": "1 Day 21 Hours 25 Minutes 48 Seconds",
      "pfstate": "62/98000",
      "pfstatepercent": "0",
      "temp": "",
      "datetime": "20180703Z103358",
      "cpufreq": "",
      "load_average": [
        "0.01",
        "0.04",
        "0.01"
      ],
      "mbuf": "1016/61600",
      "mbufpercent": "2"
    }
  }
}

system_info

  • Returns various useful system info.
  • HTTP: GET
  • Params: none

Example Request

curl \
    -X GET \
    --silent \
    --insecure \
    --header "fauxapi-auth: <auth-value>" \
    "https://<host-address>/fauxapi/v1/?action=system_info"

Example Response

{
    "callid": "5e1d8ceb8ff47",
    "action": "system_info",
    "message": "ok",
    "data": {
        "info": {
            "sys": {
                "platform": {
                    "name": "VMware",
                    "descr": "VMware Virtual Machine"
                },
                "serial_no": "",
                "device_id": "719e8c91c2c43b820400"
            },
            "pfsense_version": {
                "product_version_string": "2.4.5-DEVELOPMENT",
                "product_version": "2.4.5-DEVELOPMENT",
                "product_version_patch": "0"
            },
            "pfsense_remote_version": {
                "version": "2.4.5.a.20200112.1821",
                "installed_version": "2.4.5.a.20191218.2354",
                "pkg_version_compare": "<"
            },
            "os_verison": "FreeBSD 11.3-STABLE",
            "cpu_type": {
                "cpu_model": "Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz",
                "cpu_count": "4",
                "logic_cpu_count": "4 package(s)",
                "cpu_freq": ""
            },
            "kernel_pti_status": "enabled",
            "mds_mitigation": "inactive",
            "bios": {
                "vendor": "Phoenix Technologies LTD",
                "version": "6.00",
                "date": "07/29/2019"
            }
        }
    }
}

Versions and Testing

The FauxAPI has been developed against the following pfSense versions

  • 2.3.x - 2.3.2, 2.3.3, 2.3.4, 2.3.5
  • 2.4.x - 2.4.3, 2.4.4, 2.4.5
  • 2.5.x - 2.5.0-DEVELOPMENT-amd64-20200527-1410

FauxAPI has not been tested against 2.3.0 or 2.3.1. Additionally, it is apparent the pfSense packaging technique changed significantly prior to 2.3.x so it is unlikely it will be backported to anything prior to 2.3.0.

Testing is reasonable but does not achieve 100% code coverage within the FauxAPI codebase. Two client side test scripts (1x Bash, 1x Python) that both demonstrate and test all possible server side actions are provided. Under the hood FauxAPI, performs real-time sanity checks and tests to make sure the user supplied configurations will save, load and reload as expected.

Shout Out: Anyone that happens to know of any test harness or test code for pfSense please get in touch - I'd very much prefer to integrate with existing pfSense test infrastructure if it already exists.

Releases

v1.0 - 2016-11-20

  • initial release

v1.1 - 2017-08-12

  • 2x new API actions alias_update_urltables and gateway_status
  • update documentation to address common points of confusion, especially the requirement to provide the full config file not just the portion to be updated.
  • testing against pfSense 2.3.2 and 2.3.3

v1.2 - 2017-08-27

  • new API action function_call allowing the user to reach deep into the inner code infrastructure of pfSense, this feature is intended for people with a solid understanding of PHP and pfSense.
  • the credentials.ini file now provides a way to control the permitted API actions.
  • various update documentation updates.
  • testing against pfSense 2.3.4

v1.3 - 2018-07-02

  • add the config_patch function providing the ability to patch the system config, thus allowing API users to make granular configuration changes.
  • added a "previous_config_file" response attribute to functions that cause write operations to the running config.xml
  • add the interface_stats function to help in determining the usage of an interface to (partly) address Issue #20
  • added a "number" attibute to the "rules" output making the actual rule number more explict as described in Issue #13
  • addressed a bug with the system_stats function that was preventing it from returning, caused by an upstream change(s) in the pfSense code.
  • rename the confusing "owner" field in credentials.ini to "comment", legacy configuration files using "owner" are still supported.
  • added a "source" attribute to the logs making it easier to grep fauxapi events, for example clog /var/log/system.log | grep fauxapi
  • plenty of documentation fixes and updates
  • added documentation highlighting features and capabilities that existed but were not previously obvious
  • added the extras path in the project repo as a better place to keep non-package files, client-libs, examples, build-tools etc
  • testing against pfSense 2.3.5
  • testing against pfSense 2.4.3

v1.4 - 2020-05-31

  • Added system_info function to return various useful system information.
  • include include phpsessionmanager.inc since it is commonly required in other function calls
  • testing against pfSense 2.4.5
  • testing against pfSense 2.5.0 (pfSense-CE-2.5.0-DEVELOPMENT-amd64-20200527-1410.iso)

FauxAPI License

Copyright 2016-2020 Nicholas de Jong

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

pfsense_fauxapi's People

Contributors

ndejong avatar rulerof avatar slayercat avatar travisghansen avatar y-aok 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

pfsense_fauxapi's Issues

No response...

Hi,

Just test the API against a pfsense 2.3.2-RELEASE-p1 with bash cli.
I obtain the fauxapi-auth, but the curl process gives no response, with no error message.

I setup the package as describe from your github(download package and install it manually).

if i remove the silent option from curl command :

% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- 0:00:39 --:--:-- 0

No data is transmitted...

Thanks for your help

Clarification

Hi,

Firstly, I think this is great, thanks for the initiative!

I was wondering - could you confirm if for config changes, I would need to supply the entire modified config in the payload? Lets say I want to modify my aliases, would I need to make the modification to the json file in its entirety, and then submit it?

Thanks!
James

Too much logging

It would be nice if get/status API calls do not log or if logging can be disabled for those. Our general system log is now clogged up with API calls (gateway_status).

API calls which change the config should always be logged.

How to apply when I config_set() the new configuration file

I am currently writing a client for managing the "Host Overrides" table in "Services/DNS Forwarder" page and I succeed in posting a new JSON format configuration file via the config_set() API, which is proven by the instant change of table revealed in the web page (after my client emit that config_set() API).

However, it seems that though the shown table in the web page changes, the actual DNS behavior does not change as expected. Therefore, I am wondering if there is some mechanism I had ignored, like pressing the "apply" button when I manually change the table in the web page.

Another question: I still do not understand the difference between config_set() and config_reload(). The docs say that the former will call the latter when the code is "written and tested". What does it mean?

Thanks

Uninstall Instructions?

Could you please provide uninstall instructions please? I didn't see them anywhere, and it's not showing up in the package manager.

Thanks!

Call for getting interface status

Hello,
It would be nice if this API would have a call for retrieving the status of all interfaces and gateways (including up/down, uptime for PPPoE, last ping delay, packetloss, all the stuff pfSense measures).
Has anyone looked into this? Does anyone know where this data is saved? I may look into implement this myself, I really need it. Please share anything you may already know about this.

Kind regards.

Help with authentication

Hi, I've been trying to authenticate using your guide to no avail.

As per the below:

fauxapi-auth: <apikey>:<timestamp>:<nonce>:<hash>

For example:-
fauxapi-auth: PFFA4797d073:20161119Z144328:833a45d8:9c4f96ab042f5140386178618be1ae40adc68dd9fd6b158fb82c99f3aaa2bb55

I have the following code:

apisecret="longsecrethere"
timestamp=`date +%Y%m%dZ%H%M%S`
nonce="**what is this and how do i get it?**"
hash=`echo ${apisecret}${timestamp}${nonce} | shasum -a 256 | tr -d "[:space:]-"`

curl -X GET --silent --insecure --header "fauxapi-auth: PFFAwZz0dFMaX1nrlr095Ei2:${timestamp}:${nonce}:${hash}" "https://192.168.1.1/fauxapi/v1/?action=rule_get"

With the above I'm getting failed auth. Any help on how to use the mentioned is appreciated

Services / DNS Resolver

How could i add/remove/list all the dns hosts overrides ?
Can you give me a example, thank you.

function_call

Hello,
i try to take an function_call in bash but i got the error "api action is not defined" ...
i tried as curl call to but its the same error.

any idea?
thanks

Edit which pfctl command the rule_get call does

Hi there! First things first, awesome work on this one!

I would like to know if I can get the equivalent of the pfctl -vvs rules command from the faux_api call, but the call does pfctl -sr -vv instead. Is there any way I can amend this to use the option I need?

Need this because the -vvs gives a nice list with the rule number included, while -sr -vv does not. I need this so I am able to parse the rules according to its rule number in a single call. Any help would be appreciated

Trying to block the host using command line

Following is the command,

curl -X POST --silent --insecure --header "Content Type: application/json" --header "fauxapi-auth:XXX" http://XX.XXX.XXX.XX:XXXX/fauxapi/v1/\?action=function_call --data '{"function":"easyrule_block_host_add","args":["XXX.XXX.XXX.XX/32","wan","inet"]}'

Fatal error: Call to undefined function ifridx() in /etc/inc/easyrule.inc on line 158

Call Stack:
0.0001 119380 1. {main}() /usr/local/www/fauxapi/v1/index.php:0
0.0022 290008 2. fauxapi\v1\fauxApi->function_call() /usr/local/www/fauxapi/v1/index.php:32
0.0022 290480 3. fauxapi\v1\fauxApi->__call() /usr/local/www/fauxapi/v1/index.php:32
0.0035 297880 4. fauxapi\v1\fauxApiActions->function_call() /etc/inc/fauxapi/fauxapi.inc:83
0.0036 298416 5. fauxapi\v1\fauxApiPfsenseInterface->function_call() /etc/inc/fauxapi/fauxapi_actions.inc:388
0.0092 402684 6. call_user_func_array:{/etc/inc/fauxapi/fauxapi_pfsense_interface.inc:689}() /etc/inc/fauxapi/fauxapi_pfsense_interface.inc:689
0.0092 402996 7. easyrule_block_host_add() /etc/inc/fauxapi/fauxapi_pfsense_interface.inc:689
0.0096 404376 8. easyrule_block_rule_create() /etc/inc/easyrule.inc:289

I has been resolved by adding "require_once('filter.inc');" in easyrule.inc

https timeout issue with FauxAPI

I have a simple example that is simply trying to print a config_get() and I get the following error.

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='192.168.1.1', port=443): Max retries exceeded with url: /fauxapi/v1/?action=config_get& (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6871baeba8>: Failed to establish a new connection: [Errno 110] Connection timed out'))

Code is below

#!/usr/bin/python
import os, sys, json
from PfsenseFauxapi.PfsenseFauxapi import PfsenseFauxapi

def usage():
    print()
    print('usage: ' + sys.argv[0] + ' <host>')
    print()
    print('pipe JSON output through jq for easy pretty print output:-')
    print(' $ ' + sys.argv[0] + ' <host> | jq .')
    print()
    sys.exit(1)

if(len(sys.argv) != 2) or not os.getenv('FAUXAPI_APIKEY') or not os.getenv('FAUXAPI_APISECRET'):
    usage()

# config
fauxapi_host=sys.argv[1]
fauxapi_apikey=os.getenv('FAUXAPI_APIKEY')
fauxapi_apisecret=os.getenv('FAUXAPI_APISECRET')

FauxapiLib = PfsenseFauxapi(fauxapi_host, fauxapi_apikey, fauxapi_apisecret, debug=True)


# system_stats
# =============================================================================
print(FauxapiLib.system_stats())

Checking the system logs even with debug set to true I have no indication the script was even able to reach the firewall and I don't see drops from my machine.

I checked and the time for the pfsense server and my machine are within 60 seconds of each other, let me know if any other info is needed to help with this.

Return pfSense version?

Is it possible to return the pfSense version using FauxAPI? If not would be a useful function when looking to see if a box needs updating to latest version, especially in regards to security updates etc.

How could I reach the DHCP Leases table?

I'm currently trying to build a device presence detection (for integration with SmartThings) and I want to know if a device is present in the DHCP leases table (status="online").

At first it seems it's not available directly in fauxapi, but I'm wondering if it's something which can be easily added.

Since I'm definitely not familiar with PHP nor developping for pfSense (I'm a dotnet guy), I don't know where to start to add this in fauxapi.

How to get or set static DHCP MAC/IP/Hostname assignments

My apologies if this is the wrong way to ask a question or make a request.

Could your API be made to get or set static DHCP mappings in pfSense?

I have a CSV of mappings I'd like to import and then have pfSense maintain them, using the pfSense Web UI to add/delete.

I'd also like to export the current mappings to a CSV to upload into my remote WiFI access points (running Tomato) so their client lists will accurately reflect the IPs and hostnames of the connected clients.

Keep Getting Error after trying to use Patch_config

I tried to use FauxApi's patch_config , passing to it a json as data, Here's the actual command :

curl -X POST --silent --insecure -L --header "fauxapi-auth: <fauxapi-auth-val>" --header "Content-Type: application/json" --data @patch.json "http://192.168.100.2/fauxapi/v1/?action=config_patch"

The reason for -L is to allow forwarding (due to the pfsense having been moved) , The is dynamically generated (the problem is not related to authentication).

The error i keep getting is :
PHP ERROR: Type: 4096, File: /etc/inc/fauxapi/fauxapi_pfsense_interface.inc, Line: 135, Message: Argument 2 passed to fauxapi\v1\fauxApiPfsenseInterface::array_merge_recursive_distinct() must be of the type array, null given, called in /etc/inc/fauxapi/fauxapi_pfsense_interface.inc on line 121 and defined @ 2018-10-27 01:39:36

To be sure. the file patch.json is existing in the same path where i'm running the command, and has a valid json of a new list of CA's

Set Firewall Rule?

Sorry for opening these issues... wasn't sure how else to communicate. I'm developing an EventGhost plugin using your fauxapi library provided here. I really need to be able to set firewall rules (such as enable/disable existing rules) much like you do when you get the rules providing the rule number. Do you know if this is possible? This would be so very helpful! I understand you could pull/modify/restore the entire configuration, and then reboot - but I need something much quicker - like set the rule, then do a filter reload kind of thing. TIA

API KEY & API STRING Creation

Hi,
I am facing some confusion regarding this play how to create API string i am trying to sync this firewall with 3rd party tool.

Here is my Credentials. ini file config.

;; PFFAexample01 is hardcoded to be inoperative
[PFFAfahad09800552]
secret = 8897562242abcdefghijklmnopqrtsuvwxyz09812345
permit = alias_, config_, gateway_, rule_, send_, system_, function_*
comment = PFFAfahad09800552 - hardcoded to be inoperative

How i can check this one working? What is the roll of Python in it? What next configuration i need to do after this? How this API string create in below format?

fauxapi-auth: PFFA4797d073:20161119Z144328:833a45d8:9c4f96ab042f5140386178618be1ae40adc68dd9fd6b158fb82c99f3aaa2bb55

Is this example Auth ??

system_load_config needs to detect proper port for curl exec

Just getting started with this package and noticed it's exec'ing curl like this: curl --silent --insecure "http://127.0.0.1/index.php?__fauxapi_callid=5b8ac08e9846d\

This causes the app to stall for me as I run the webgui on 8080. If we could make that a bit more dynamic that would be great. Thanks!

Update PFSense

Hello,

Is there any intentions on adding the ability to update the PFsense server via this API?

We have a few hundred PFsense's deployed throughout our environments, and let me tell you. That is one of the largest saviors of time we could possibly get.

easyrule_block_host_add works only with name 'WAN'

curl -X POST --silent --insecure --header "Content Type: application/json" --header "fauxapi-auth:XXX" http://XX.XXX.XXX.XX:XXXX/fauxapi/v1/\?action=function_call --data '{"function":"easyrule_block_host_add","args":["XXX.XXX.XXX.XX/32","wan","inet"]}'

Above command adds

Alias

with the name

"WAN"

and also creates

Rule

in rules section. But if I change the 2nd argument (i.e. int) with something different name function only creates the alias but no rules get added.
Also its very vague if the network gets blocked even if the alias and rule added with 'WAN' name. I need to change the name manually by GUI to make blocking work 100%.

Not getting response for config_get or rule_get

Hi,
My API call for system_stats, config_reload, etc are working fine but it fails for config_get and rule_get. In the logs I can see the request reaches pfsense and also it is a valid request, but after about a min it says authentication failed 401 Unauthorized because of timeout.
This is my request:
curl -k -s -X GET -H "fauxapi-auth: ${fauxapi_auth}" http://${fauxapi_host}/fauxapi/v1/?action=rule_get

Note: Just to add, I am using http instead of https because I was getting certificate issues with https.

manage rule

rule_update Rule_ID(1) type:(UDP/TCP/ICMP/ALL/OTHER) Port(80;443;21:22) Description (TEST)
return (True?False)

rule_create type:(UDP/TCP/ICMP/ALL/OTHER) Port(80;443;21:22) Description (TEST)
return (Rule_ID?-1)

rule_delect Rule_ID(1)
return (True?False)

rule_search source(192.168.1) || destination(192.1681.2)
return Serialization(List)

User certificates OpenVPN client overrides

Are there any functions to do the following:
1) create a user certificate '/system_certmanager.php?act=new'
2) create an openvpn client specific override '/vpn_openvpn_csc.php?act=new'
3) exporting the client certificate package '/vpn_openvpn_export.php'

Function_Call portal_allow

Hi everybody!
I would like to compliment you greatly on your work.

I'm trying to authenticate users on the captive portal using function_call with portal_allow function.
Unfortunately it doesn't works.

I think the problem is the cpzone, with portal_allow called by the API PfSense doesn't recognize in which zone I want to authenticate the user.

Is there anybody who can help me?

Configurations don't apply after config_restore

Hi,
I have created config backups for applying rules to WAN interface.
Backup1.xml : Apply icmp and tcp pass rules on WAN
Backup2.xml : Remove icmp and tcp pass rules on WAN

I am calling the backup files using config_restore, the configurations are reflected in config.xml but the rules are not working on the interface. I tried config_reload too, but that's not working too.

Quesiton: How to create a user with fauxapi

HI,

I was trying to create a user with fauxapi. From dev shell you can create a new user by running the following command:

$config['system']['user'][] = <name>

The only .inc file that makes sense of creatin a user is auth.inc line 480.
I have tried with several functions with the method function_call() from fauxapi, but it doesn't create the user.
Have you been able to generate a user via fauxapi? I have been trying all day, eventhough the function is passing the arguments properly, and in the debugging is showing but the 200 ok, the user is not being created. Fo you have any clue on how to do this?

Best regards,

Jose Gerardo Pineda

APIKEY and APIKEYSECRET confusion

I am unable to understand these two terms. in first apikey is being used while taking taking hash apisecret is being used.

fauxapi-auth: :::
= sha256()

What if i use below as it is. I use it, it gives no error.

curl
-X GET
--silent
--insecure
--header "fauxapi-auth: PFFA4797d073:20161119Z144328:833a45d8:9c4f96ab042f5140386178618be1ae40adc68dd9fd6b158fb82c99f3aaa2bb55"
"https://192.168.10.10/fauxapi/v1/?action=config_get"

authentication problem

Hi,
I am entirely new to "pfsense" and "fauxApi".
I have pfsense installed in a VM and i am trying to get its config details using RESTClient.
I always get a "Unauthorized"error whenever i try to do "config_get" or any other operation.
I am pretty sure the issue is with the "fauxapi_auth" that i provide in the header but the issue is i don't understand how to solve it. I did try giving certain values in the credentials.ini file but still the same error.
It will be very helpful if anyone could provide me a solution.

Having FauxAPI Python Library on PyPI?

Have you thought about putting FauxAPI Python Library on PyPI, that way one can just pip install pfsense_fauxapi and have all of the dependencies (requests) and library installed super easily?

bash client: alias and firewall rules patching

Hi,
I don’t know howw to contact you for clarification.
I hope this is a good way.
I’ve setup fauxapi to a test installation.
I’m trying to use bash client to make changes to the existing configuration and see how it works on the device.
I see the same issue with pfsense version 2.4.3 and 2.4.4.p3

I’m able to get the config using the script with
system_config=$(fauxapi_config_get ${fauxapi_host})

I’m facing two problems:
One with real alias value , on with rules patching

Real Alias Value
I’m able to change the value of an alias with
fauxapi_config_patch $fauxapi_host /root/Desktop/pfs_alias.cfg
(the file contains the json needed that changes the only alias from 192.168.204.55 to 192.168.204.54)

but the change is only aesthetical (the alis value is displayed correctly in the gui, but the value in diagnostic>Tables>Alias_name is still the old one (the only way to change it is mannually via Status>Filter Reload> Reload Filter)

Rules patching
the other problem is that when i try to patch the firewall rules (even with a unmodifyed copy of the same rules) I get an error like this one

_{
"callid": "5d4a943c378b4",
"action": "config_patch",
"message": "failed to patch config data",
"logs": [
{
"INFO": "20190807Z110500 :: fauxapi\v1\fauxApi::__call",
"DATA": {
"user_action": "config_patch",
"callid": "5d4a943c378b4",
"client_ip": "192.168.204.54"
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApi::__check_user_action_call"
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiAuth::is_authenticated"
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiAuth::load_credentials"
},
{
"DEBUG": "20190807Z110500 :: valid auth for call",
"DATA": {
"apikey": "PFFATestUser",
"callid": "5d4a943c378b4",
"client_ip": "192.168.204.54"
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiAuth::is_authorized"
},
{
"DEBUG": "20190807Z110500 :: permit allows action",
"DATA": {
"action": "config_patch",
"permit": "",
"permits": [
"
"
]
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApi::_check_user_action_call() checks all passed"
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiActions::config_patch"
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_patch",
"DATA": {
"do_backup": true,
"do_reload": true
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_load",
"DATA": {
"config_file": "/cf/conf/config.xml"
}
},
{
"INFO": "20190807Z110500 :: config_patch merged with current config, attempting to save"
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_save",
"DATA": {
"do_backup": true,
"do_reload": true
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_backup",
"DATA": "/cf/conf/config.xml"
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::get_next_backup_config_filename",
"DATA": {
"type": "pfsense"
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_load",
"DATA": {
"config_file": "/cf/conf/config.xml"
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_load",
"DATA": {
"config_file": "/cf/conf/backup/config-1565168700.xml"
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_load",
"DATA": {
"config_file": "/cf/conf/config.xml"
}
},
{
"DEBUG": "20190807Z110500 :: attempting to (re)load a temp copy of the config supplied",
"DATA": {
"config_temp_file": "/tmp/fauxApi_wpSDSf"
}
},
{
"DEBUG": "20190807Z110500 :: fauxapi\v1\fauxApiPfsenseInterface::config_load",
"DATA": {
"config_file": "/tmp/fauxApi_wpSDSf"
}
},
{
"ERROR": "20190807Z110500 :: saved config does not match config when saved and reloaded"
}
]
}

Thanks for any suport you can provide.

Newly created VLAN/Interface is "down"

I noted a very similar issue #2 and I am sending (via bash client for testing currently) the full json document that was previously retrieved, with the sections added for the new VLAN/Interface (and also DHCP config) I wanted to send.

I will try to clearly lay out what I did here: -

First I set up a clean server and downloaded the config.xml using your API.

Then I added VLAN 75 on interface igb1.
I then added the interface (opt1), set an IP. (IPv4)
I then enabled DHCP Server on this interface and added a simple range.

At this point I re-downloaded config.xml and used diff to see the result of my changes above.

I then duplicated the newly added sections but changed (on the duplicate elements): -
VLAN ID from 75 to 76
IP Address to be a non-conflicting subnet.
opt1 to opt2
and the vlan interface from igb1_vlan75 to igb1_vlan76

I then set this new config and got an OK response.
{"callid":"593b30536e267","action":"config_set","message":"ok","data":{"do_backup":true,"do_reload":true}}

When looking in the GUI after posting the new config via the API, I can see that what I added has been created but the interface shows as down.

Going in with ssh and running ipconfig shows me that it did not actually create the vlan tagged interface "igb1_vlan76"

Any idea what I did wrong?
Any help you can offer would be very much appreciated.

config-cleaned.zip

PFSense 2.4.4 Potential Issues

Recently upgraded PFSense to 2.4.4 and started getting the following exception using faux v1.3.3:

Fatal error: Uncaught Error: Call to undefined function fauxapi\v1\split() in /etc/inc/fauxapi/fauxapi_auth.inc:48
Stack trace: #0 /etc/inc/fauxapi/fauxapi.inc(131): fauxapi\v1\fauxApiAuth->is_authenticated() 
#1 /etc/inc/fauxapi/fauxapi.inc(63): fauxapi\v1\fauxApi->__check_user_action_call(Object(fauxapi\v1\fauxApiActions), 'config_get', Array, '')
#2 /usr/local/www/fauxapi/v1/index.php(32): fauxapi\v1\fauxApi->__call('config_get', Array)
#3 {main} thrown in /etc/inc/fauxapi/fauxapi_auth.inc on line 48 PHP ERROR: Type: 1, File: /etc/inc/fauxapi/fauxapi_auth.inc, Line: 48,
Message: Uncaught Error: Call to undefined function fauxapi\v1\split() in /etc/inc/fauxapi/fauxapi_auth.inc:48
Stack trace: #0 /etc/inc/fauxapi/fauxapi.inc(131): fauxapi\v1\fauxApiAuth->is_authenticated() 
#1 /etc/inc/fauxapi/fauxapi.inc(63): fauxapi\v1\fauxApi->__check_user_action_call(Object(fauxapi\v1\fauxApiActions), 'config_get', Array, '')
#2 /usr/local/www/fauxapi/v1/index.php(32): fauxapi\v1\fauxApi->__call('config_get', Array)
#3 {main} thrown

Interface down when initially created via FauxAPI

When creating an interface with the following JSON:

{'wan': {'enable': '', 'if': 'igb0', 'descr': 'pfSYNC', 'ipaddr': '<IP>', 'subnet': '30', 'spoofmac': ''}, 'lan': {'enable': '', 'if': 'igb1', 'ipaddr': '<IP>', 'subnet': '24', 'ipaddrv6': '', 'subnetv6': '', 'media': '', 'mediaopt': '', 'track6-interface': 'wan', 'track6-prefix-id': '0', 'gateway': 'GW_LAN', 'gatewayv6': ''}, 'opt1': {'descr': 'WANBOND', 'if': 'lagg0', 'enable': '', 'spoofmac': '', 'mtu': '9000'}, 'opt2': {'descr': 'WAN', 'if': 'lagg0_vlan1112', 'enable': '', 'ipaddr': '<IP>', 'subnet': '29', 'gateway': 'WANv4GW', 'spoofmac': ''}, 'opt3': {'descr': 'VL3301Pub', 'if': 'lagg0_vlan3301', 'spoofmac': '', 'enable': 'True', 'blockpriv': '', 'blockbogons': '', 'ipaddr': '<IP>', 'subnet': '30'}}

The interfaces appear on the pfSense dashboard as down and doesn't come up unless i disable and re-enable the interface via the GUI. This occurs despite using config.reload().

Is this expected behaviour and if not, can you suggest a possible cause?

Regards,
Ochuko

Authentication Failed even when apikey is in configuration.ini

Hi,

I am faicng an authenticaiton issue. I get the following error

{"ERROR":"20180712Z175234 :: apikey not defined in credential file","DATA":{"apikey":"PFFAzM7GB9aBoXSEwsAH6tZV","filename":"\/etc\/fauxapi\/credentials.ini"},"source":"fauxapi"}

My configuraiton.ini (/etc/fauxapi/configuration.ini) has the following:

[PFFAzM7GB9aBoXSEwsAH6tZV]
secret= zvhBVMGdUF3V03fJLFyMkdOTpMB7uLARwbrZm6g1DXLOPOjqOKe5oMIhOo7t
permit = permit = alias_*, config_*, gateway_*, rule_*, send_*, system_*, function_*
comment = admin token

And this is the curl call:

curl -X GET --silent --insecure --header "fauxapi-auth: PFFAzM7GB9aBoXSEwsAH6tZV:20180712Z174348:833a45d8:ae6af6e76532ca8c37edceb87f492ca827387c250998125265909b7834271961" "https://172.16.20.20/fauxapi/v1/?action=config_get&__debug=true"

I changed the values several times and the error still appears.
Could you please provide some guidance on what may be wrong?

config_reload not working

I use config_patch to change the content of an alias and it works great but the new configuration is not active in pFsense so I would like to use a config_reload request to activate my new configuration but config_reload does not work, the request is successful but the new pfsense config is not loaded.

pfsense 2.4.4.p3

I am using the following URI
https://$pfsense/fauxapi/v1/?action=config_reload&__debug=true

The API request is successful as seen in the response:

StatusDescription : OK
Content           : {"callid":"5ce267915ba49","action":"config_reload","message":"ok","logs":[{"DEBUG":"20190520Z103841 :: fauxapi\\v1\\fauxApi::__call","DATA":{"user_action":"config_reload","callid":"5ce267915ba49","cli...
RawContent        : HTTP/1.1 200 OK
                    Transfer-Encoding: chunked
                    Connection: keep-alive
                    fauxapi-callid: 5ce267915ba49
                    Strict-Transport-Security: max-age=31536000
                    X-Content-Type-Options: nosniff
                    Content-Type: applicat...
Forms             : {}
Headers           : {Server, Transfer-Encoding, Content-Type, Date...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 1302
PSComputerName    :xxxxxxxxxx

but nothing is logged in pfsense System Logs (despite the presence of debug=true, while config_patch is present) and my new config is not loaded.

image

Thanks for your help,

API manage Alias IP

Hello all,

There is a possibility to manage IP Alias, with this API? I saw the option with URL Alias.

thanks

Problem calling function

Trying to block the host using command line but getting exception,
command :
curl -X POST --silent --insecure --header "Content Type: application/json" --header "fauxapi-auth:XXX" http://xx.xxx.xxx.xx:xxxx/fauxapi/v1/\?action=function_call --data '{"function":"easyrule_block_alias_add","host":"xxx.xxx.xxx.xx","$int":"wan"}'

Response :

{"callid":"5a3ab9fa764ac","action":"function_call","message":"problem calling function","logs":[{"INFO":"20171220Z192858 :: fauxapi\v1\fauxApi::__call","DATA":{"user_action":"function_call","callid":"5a3ab9fa764ac","client_ip":"xx.xxx.xxx.xx"}},{"INFO":"20171220Z192858 :: valid auth for call","DATA":{"apikey":"PFFAwZz0dFMaX1nrlr095Ei2","callid":"5a3ab9fa764ac","client_ip":"xx.xxx.xxx.xx"}},{"ERROR":"20171220Z192858 :: function not defined as valid in function calls reference file","DATA":{"function":"easyrule_block_alias_add","function calls reference file":"/etc/fauxapi/pfsense_function_calls.txt"}}],"error":{"error":{"xdebug_message":"\nException: function not defined as valid in function calls reference file in /etc/inc/fauxapi/fauxapi_pfsense_interface.inc on line 633\n\nCall Stack:\n 0.0001 119368 1. {main}() /usr/local/www/fauxapi/v1/index.php:0\n 0.0022 289984 2. fauxapi\v1\fauxApi->function_call() /usr/local/www/fauxapi/v1/index.php:32\n 0.0022 290456 3. fauxapi\v1\fauxApi->__call() /usr/local/www/fauxapi/v1/index.php:32\n 0.0031 297616 4. fauxapi\v1\fauxApiActions->function_call() /etc/inc/fauxapi/fauxapi.inc:83\n 0.0032 298228 5. fauxapi\v1\fauxApiPfsenseInterface->function_call() /etc/inc/fauxapi/fauxapi_actions.inc:388\n"}}}

Get traffic bandwidth on wan interface

Hi
Is there a way to get the consumed speed on wan interface like the data we get under Status -> Traffic Graph?
Bandwidth In and Bandwidth Out

Thanks

NodeJS/TypeScript Client Library

Hi, We wrote a client sdk in nodejs/typescript for the FauxAPI. You can find it here. Would it be a good thing to include the library in your project? If so, is a pull request the best approach for that?

Server returned HTTP response code: 500 for REST API call

I'm trying to access the function_call API by making the HTTP request using JAVA code as follows,

phpFn = 'easyrule_block_alias_getid' and fnParams='wan'

HttpURLConnection con = (HttpURLConnection)url.openConnection();
		con.setRequestProperty("fauxapi-auth", getAuth());
		con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.9,hi;q=0.8");
		con.setRequestProperty("Cache-Control", "max-age=0");
		con.setRequestProperty("Connection", "keep-alive");
		con.setRequestProperty("Upgrade-Insecure-Requests", "11");
		con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36");
		con.setRequestProperty("Origin", "");
		con.setAllowUserInteraction(true);
		con.setRequestMethod("POST");
		con.setDoInput(true);
		con.setDoOutput(true);

		OutputStream os = con.getOutputStream();
		BufferedWriter writer = new BufferedWriter(
		        new OutputStreamWriter(os, "UTF-8"));
		writer.write("{\"function\":\""+phpFn+"\",\"int\":\""+fnParams[0]+"\"}");
		writer.flush();
		writer.close();
		os.close();
		con.connect();

same code works for the

get_services
function of the

function_call

API.

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.