Repository: pfsensible/core Branch: master Commit: 62b56a13829c Files: 211 Total size: 2.8 MB Directory structure: gitextract_2409rtmf/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ └── workflows/ │ └── main.yml ├── .gitignore ├── CHANGELOG.rst ├── GENERATING_MODULES.md ├── LICENSE ├── README.md ├── changelogs/ │ ├── .plugin-cache.yaml │ ├── 134_openvpn_digest.yml │ ├── changelog.yaml │ ├── config.yaml │ └── fragments/ │ ├── 129_sshguard_whitelist.yaml │ ├── 217_pfsense_setup_webguicert.yml │ ├── 219_parse_address_ipv6.yml │ ├── 223_fix_openvpn_alias_expansion.yml │ ├── 224_add_dco_for_plus_versions.yml │ ├── 226_dns_resolver.yaml │ ├── 228_interface_diff.yml │ ├── 238_pfsense_openvpn_server.yml │ ├── 239_sync_config.yml │ ├── 242_gateway_loss.yml │ ├── 243_openvpn_client.yml │ ├── 245_arg_route.yaml │ ├── 248_class_level_imports.yaml │ ├── 251_setup_hardware.yaml │ ├── rule_pass_before_deny_ordering.yml │ └── rule_protocol_any_with_ports.yml ├── examples/ │ ├── ipsec/ │ │ ├── README.md │ │ ├── filter_plugins/ │ │ │ └── pfsense.py │ │ ├── hosts │ │ ├── ipsecs.yaml │ │ ├── more.ipsecs.yaml │ │ └── setup_ipsec.yml │ ├── lookup/ │ │ ├── README.md │ │ ├── hosts │ │ ├── pfsense_definitions.yaml │ │ └── setup_all_rules.yml │ ├── pfsense.yml │ ├── pfsense_setup.yml │ └── roles/ │ ├── pfsense/ │ │ └── tasks/ │ │ ├── fail2ban.yml │ │ └── main.yml │ └── pfsense_setup/ │ ├── tasks/ │ │ ├── main.yml │ │ └── setup_user.yml │ └── templates/ │ └── nslcd.conf.j2 ├── galaxy.yml ├── meta/ │ └── runtime.yml ├── misc/ │ ├── .coveragerc │ ├── ansible2local │ ├── local2ansible │ ├── mkpfcollection │ ├── mkpfsensible │ ├── pfsense_module.py.j2 │ ├── pfsensible-generate-module │ ├── pytest │ ├── run_ansible_sanity_tests │ └── setup_units_tests ├── plugins/ │ ├── lookup/ │ │ └── pfsense.py │ ├── module_utils/ │ │ ├── __init__.py │ │ ├── alias.py │ │ ├── arg_route.py │ │ ├── arg_validate.py │ │ ├── default_gateway.py │ │ ├── dhcp_server.py │ │ ├── gateway.py │ │ ├── haproxy_backend.py │ │ ├── haproxy_backend_server.py │ │ ├── interface.py │ │ ├── interface_group.py │ │ ├── ipsec.py │ │ ├── ipsec_p2.py │ │ ├── ipsec_proposal.py │ │ ├── module_base.py │ │ ├── module_config_base.py │ │ ├── nat_outbound.py │ │ ├── nat_port_forward.py │ │ ├── openvpn_client.py │ │ ├── openvpn_override.py │ │ ├── openvpn_server.py │ │ ├── pfsense.py │ │ ├── route.py │ │ ├── rule.py │ │ ├── rule_separator.py │ │ └── vlan.py │ └── modules/ │ ├── pfsense_aggregate.py │ ├── pfsense_alias.py │ ├── pfsense_authserver_ldap.py │ ├── pfsense_authserver_radius.py │ ├── pfsense_ca.py │ ├── pfsense_cert.py │ ├── pfsense_default_gateway.py │ ├── pfsense_dhcp_server.py │ ├── pfsense_dhcp_static.py │ ├── pfsense_dns_resolver.py │ ├── pfsense_gateway.py │ ├── pfsense_gateway_group.py │ ├── pfsense_group.py │ ├── pfsense_haproxy_backend.py │ ├── pfsense_haproxy_backend_server.py │ ├── pfsense_interface.py │ ├── pfsense_interface_group.py │ ├── pfsense_ipsec.py │ ├── pfsense_ipsec_aggregate.py │ ├── pfsense_ipsec_p2.py │ ├── pfsense_ipsec_proposal.py │ ├── pfsense_log_settings.py │ ├── pfsense_nat_outbound.py │ ├── pfsense_nat_port_forward.py │ ├── pfsense_openvpn_client.py │ ├── pfsense_openvpn_override.py │ ├── pfsense_openvpn_server.py │ ├── pfsense_phpshell.py │ ├── pfsense_rewrite_config.py │ ├── pfsense_route.py │ ├── pfsense_rule.py │ ├── pfsense_rule_separator.py │ ├── pfsense_setup.py │ ├── pfsense_shellcmd.py │ ├── pfsense_user.py │ └── pfsense_vlan.py ├── setup.cfg └── tests/ ├── plays/ │ ├── README.md │ ├── ansible.cfg │ ├── host_vars/ │ │ └── pfsense-test.yml │ ├── hosts │ ├── openvpn.yml │ ├── tasks/ │ │ ├── test_interface_create.yml │ │ ├── test_interface_group_create.yml │ │ ├── test_interface_group_ifconfig_groups.yml │ │ ├── test_openvpn_override_create.yml │ │ ├── test_openvpn_override_delete.yml │ │ ├── test_openvpn_override_file_exists.yml │ │ ├── test_openvpn_server_create.yml │ │ └── test_openvpn_server_delete.yml │ └── templates/ │ ├── openvpn-override.j2 │ └── openvpn-server-config.ovpn.j2 ├── sanity/ │ ├── ignore-2.14.txt │ ├── ignore-2.15.txt │ ├── ignore-2.16.txt │ └── ignore-2.17.txt └── unit/ └── plugins/ ├── lookup/ │ └── test_pfsense.py ├── module_utils/ │ ├── fixtures/ │ │ └── pfsense_setup_config.xml │ └── test_pfsense.py └── modules/ ├── __init__.py ├── fixtures/ │ ├── 2.4/ │ │ ├── pfsense_ipsec_aggregate_config.xml │ │ ├── pfsense_ipsec_config.xml │ │ └── pfsense_ipsec_proposal_config.xml │ ├── pfsense_aggregate_config.xml │ ├── pfsense_alias_config.xml │ ├── pfsense_alias_null_config.xml │ ├── pfsense_authserver_config.xml │ ├── pfsense_ca_config.xml │ ├── pfsense_cert_config.xml │ ├── pfsense_dhcp_server_config.xml │ ├── pfsense_dhcp_static_config.xml │ ├── pfsense_dns_resolver_config_full.xml │ ├── pfsense_dns_resolver_config_init.xml │ ├── pfsense_gateway_config.xml │ ├── pfsense_haproxy_backend_config.xml │ ├── pfsense_haproxy_backend_server_config.xml │ ├── pfsense_interface_config.xml │ ├── pfsense_ipsec_aggregate_config.xml │ ├── pfsense_ipsec_config.xml │ ├── pfsense_ipsec_p2_config.xml │ ├── pfsense_ipsec_proposal_config.xml │ ├── pfsense_nat_outbound.xml │ ├── pfsense_nat_port_forward_config.xml │ ├── pfsense_openvpn_config.xml │ ├── pfsense_route_config.xml │ ├── pfsense_rule_config.xml │ ├── pfsense_rule_separator_config.xml │ ├── pfsense_setup_config.xml │ ├── pfsense_syslog_config.xml │ ├── pfsense_user_config.xml │ └── pfsense_vlan_config.xml ├── pfsense_module.py ├── test_pfsense_aggregate.py ├── test_pfsense_alias.py ├── test_pfsense_alias_null.py ├── test_pfsense_authserver_ldap.py ├── test_pfsense_authserver_radius.py ├── test_pfsense_ca.py ├── test_pfsense_cert.py ├── test_pfsense_dhcp_server.py ├── test_pfsense_dhcp_static.py ├── test_pfsense_dns_resolver.py ├── test_pfsense_gateway.py ├── test_pfsense_haproxy_backend.py ├── test_pfsense_haproxy_backend_server.py ├── test_pfsense_interface.py ├── test_pfsense_interface_group.py ├── test_pfsense_ipsec.py ├── test_pfsense_ipsec_aggregate.py ├── test_pfsense_ipsec_p2.py ├── test_pfsense_ipsec_proposal.py ├── test_pfsense_log_settings.py ├── test_pfsense_nat_outbound.py ├── test_pfsense_nat_port_forward.py ├── test_pfsense_openvpn_override.py ├── test_pfsense_openvpn_server.py ├── test_pfsense_route.py ├── test_pfsense_rule.py ├── test_pfsense_rule_create.py ├── test_pfsense_rule_misc.py ├── test_pfsense_rule_noop.py ├── test_pfsense_rule_separator.py ├── test_pfsense_rule_update.py ├── test_pfsense_setup.py ├── test_pfsense_user.py └── test_pfsense_vlan.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: opoplawski # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] #patreon: # Replace with a single Patreon username #open_collective: # Replace with a single Open Collective username #ko_fi: # Replace with a single Ko-fi username #tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel #community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry #liberapay: # Replace with a single Liberapay username #issuehunt: # Replace with a single IssueHunt username #lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry #polar: # Replace with a single Polar username #buy_me_a_coffee: # Replace with a single Buy Me a Coffee username #thanks_dev: # Replace with a single thanks.dev username #custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Expected behavior** A clear and concise description of what you expected to happen. **Playbook** Please paste a minimal playbook to reproduce the issue: ``` ``` **Output** Please paste the ansible output run with `-vv`: ``` ``` **Environment** - What version of pfsensible.core? - What version of ansible? - What version of pfSense? **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/workflows/main.yml ================================================ name: CI # Controls when the workflow will run on: # Triggers the workflow on push or pull request events push: pull_request: # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: # This workflow contains a single job called "build" build: # The type of runner that the job will run on # ubuntu-latest fails: https://github.com/actions/runner/issues/2364 runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ['3.10'] ansible-version: ['2.14', '2.15', '2.16', '2.17'] # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: Checkout project uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Cache pip modules uses: actions/cache@v4 env: cache-name: cache-pip with: path: | ~/.cache key: ${{ runner.os }}-build-${{ env.cache-name }}-python-${{ matrix.python-version }} - name: Cache ansible setup uses: actions/cache@v4 env: cache-name: cache-ansible with: path: | ~/work/ansible-pfsense/ansible-pfsense/ansible key: build-${{ env.cache-name }}-ansible-${{ matrix.ansible-version }} # Runs a set of commands using the runners shell - name: Install ansible and deps run: | pip install ansible-core==${{ matrix.ansible-version }}.* dnspython parameterized pyyaml ansible-galaxy collection install community.internal_test_tools - name: Run ansible tests run: | pwd dir=$(pwd) mkdir -p ~/.ansible/collections/ansible_collections/pfsensible cd ~/.ansible/collections/ansible_collections/pfsensible cp -al $dir core cd core ansible-test sanity --requirements --python ${{ matrix.python-version }} ansible-test units --requirements --python ${{ matrix.python-version }} ================================================ FILE: .gitignore ================================================ # test output tests/output/ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # ansible-galaxy package *.tar.gz # vi *.swp ================================================ FILE: CHANGELOG.rst ================================================ ============================= pfSensible.Core Release Notes ============================= .. contents:: Topics v0.7.1 ====== Minor Changes ------------- - pfsense_ipsec_p2/proposal - Add missing new DH Groups 31, 32 support in ipsec vpn (https://github.com/pfsensible/core/issues/183) - pfsense_log_settings - add nologlinklocal4, nologsnort2c, and logconfigchanges parameters (https://github.com/pfsensible/core/pull/199). - pfsense_user - add disabled parameter (https://github.com/pfsensible/core/pull/208). Bugfixes -------- - pfsense_aggregate - fix argument_spec handling for aggregated modules that broke aggregated_nat_outbounds (https://github.com/pfsensible/core/issues/201). - pfsense_authserver_ldap - Call set_pam_auth() if needed to update system config. - pfsense_authserver_ldap - Fix disabling ldap_allow_unauthenticated (https://github.com/pfsensible/core/issues/139). - pfsense_ca - Better validation for name, lifetime, and dn_* parameters (https://github.com/pfsensible/core/pull/142). - pfsense_dhcp_server - Describe denyunknown options and allow disabling it via `disabled` (https://github.com/pfsensible/core/issues/203). - pfsense_dns_resolver - Add ability to specify Virtual IPs for interfaces (https://github.com/pfsensible/core/issues/136). - pfsense_dns_resolver - Fix configuration without domainoverrides set (https://github.com/pfsensible/core/issues/206). - pfsense_dns_resolver - Fix forward_tls_upstream handling in domainoverrides (https://github.com/pfsensible/core/issues/209). - pfsense_ipsec_p2 - Allow disabling hash algorithms (https://github.com/pfsensible/core/issues/172) - pfsense_setup - Fix PHP command to update system broken in 0.7.0 (https://github.com/pfsensible/core/pull/210). v0.7.0 ====== Release Summary --------------- This is a major refactoring of the ``pfsensible.core`` collection. The goal was to support easier creation of new modules via the ``pfsensible-generate-module`` script. PFSenseModuleBase was expanded to handle more common functions via configuration options and callback functions. Minor Changes ------------- - pfsense_alias - Add `url` parameter and deprecate using `address` for `urltable` and `urltable_ports` types. - pfsense_ca - Add ability to create internal CAs. (https://github.com/pfsensible/core/issues/135) - pfsense_rule - Change `after` to insert after the last match instead of the first. Breaking Changes / Porting Guide -------------------------------- - This release is only expected to work with pfSense 2.8.0+ / pfSense Plus 24.11+ due to changes in various lookup_*() functions in pfSense. Bugfixes -------- - Use config_get_path() to load configuration in php update commands. Fixes various update commands not working with pfSense 2.8.0 (https://github.com/pfsensible/core/issues/190) - pfsense_ca / pfsense_cert - Fix validation of base64 encoded keys and certs. (https://github.com/pfsensible/core/issues/174) - pfsense_ca/pfsense_cert - Restart services affected by updated certificates. (https://github.com/pfsensible/core/issues/191) - pfsense_cert - Write generated internal certificate into config. (https://github.com/pfsensible/core/issues/186) - pfsense_dns_resolver - do not always add an empty domainoverrides item. (https://github.com/pfsensible/core/issues/187) - pfsense_interface - fixes removal of an interface when interface group is empty. (https://github.com/pfsensible/core/issues/182) - pfsense_interface - fixes removal of an interface with `state: absent`. _remove_all_separators() works when no separator exists for that interface. (https://github.com/pfsensible/core/issues/170) New Modules ----------- - pfsensible.core.pfsense_dhcp_server - Manage pfSense DHCP servers - pfsensible.core.pfsense_phpshell - PHP Shell - pfsensible.core.pfsense_shellcmd - Manage pfSense shellcmds v0.6.2 ====== Minor Changes ------------- - added ``auto`` choice for ``myid_type`` and ``peerid_type`` (https://github.com/pfsensible/core/issues/145) - pfsense_ca - added ``key`` parameter to import CA private key (https://github.com/pfsensible/core/issues/57) - pfsense_dns_resolver - validate ``domainoverrides.ip`` field - pfsense_openvpn_client - added ``v4only`` and `v6only`` values for ``create_gw`` (https://github.com/pfsensible/core/issues/133) - pfsense_openvpn_override - support changed semantics of ``push_reset`` in pfSense Plus 24.11 - pfsense_openvpn_server - no longer sort authmode items - pfsense_setup - Update language list for pfSense 2.7.1 / pfSense Plus 23.09. - pfsensible_interface - implemented ``ipv6_type: slaac`` and added the ``slaacusev4iface`` parameter (https://github.com/pfsensible/core/issues/121). - pfsensible_openvpn_server - Allow ``Local Database`` for ``authmode`` parameter (https://github.com/pfsensible/core/issues/125). Bugfixes -------- - made pfsense_dns_resolver hosts idempotent (https://github.com/pfsensible/core/issues/151) - pfsense - handle "."s prefixing php() output triggered by the presense of /var/run/booting and issue a warning (https://github.com/pfsensible/core/issues/118) - pfsense_dns_resolver - allow for comma separated list of IP addresses in ``hosts.ip`` (https://github.com/pfsensible/core/discussions/150) - pfsense_openvpn_client - add ``tls_type`` parameter - pfsense_openvpn_client/server - apply ``tls`` setting to config (https://github.com/pfsensible/core/issues/132) - pfsense_user - fixed setting multiple groups for a user (https://github.com/pfsensible/core/issues/130) - set `global $config;` in phpshell() to find update commands in pfSense Plus 24.11 v0.6.1 ====== Minor Changes ------------- - Bump required ansible version to 2.12. - Have _get_ansible_param_bool set the value to value_false if the parameter is present and false. - Refactor pfsense_authserver_ldap and pfsense_authserver_radius. Should not have any visible impact. - Ship tests so other pfsensible collections can use them. - pfsense_ca - allow for disabling `randomserial` and `trust` parameters. - pfsense_dhcp_static - Add arp_table_static_entry argument (https://github.com/https://github.com/pfsensible/core/issues/109). Deprecated Features ------------------- - The pfsensible_haproxy* modules have moved to the `pfsensible.haproxy` collection and will be removed from `pfsensible.core` in version 0.8.0. v0.6.0 ====== Major Changes ------------- - pfsense_default_gateway - Add module for setting the default gateways - pfsense_dns_resolver - Add module for DNS resolver (unbound) settings Minor Changes ------------- - ipaddress support for pfSense 2.4.4 - pfsense_cert - Support EC certs (https://github.com/pfsensible/core/pull/98) - pfsense_interface - Always return `ifname` - even on interface creation - pfsense_interface - Prevent removal if interface is part of an interface group - pfsense_nat_outbound - Allow for NET:INTERFACE addresses - pfsense_nat_port_forward - 2.4.5 compatibility - pfsense_openvpn_server - Do not allow removal of an instance with an interface assignment - pfsense_rule - Add option to ignore an inexistent queue - pfsense_rule - Add support for floating 'any' interface rule (https://github.com/pfsensible/core/pull/90) - plugins/lookup/pfsense - Optimization and ignore queue setting - tests/plays - Add plays for testing with a live pfSense instance Bugfixes -------- - pfsense_aggregate - Fix where a rule with a duplicated name would not be deleted if required - pfsense_dhcp_static - Allow removing entry with just name (https://github.com/pfsensible/core/issues/69) - pfsense_dhcp_static - Allow use of display name for netif. Error in case a interface group name is specified (https://github.com/pfsensible/core/issues/79) - pfsense_interface - Properly shut dwon interface and kill dhclient process when removing interface (https://github.com/pfsensible/core/pull/67) - pfsense_interface_group - Check that members list is unique - pfsense_interface_group - Fix creation (https://github.com/pfsensible/core/issues/74) - pfsense_interface_group - `members` is only required for creation - pfsense_nat_outbound - Fix boolean values, invert (https://github.com/pfsensible/core/issues/92) - pfsense_openvpn_client - Fix strictuserdn -> strictusercn option (https://github.com/pfsensible/core/pull/93) - pfsense_openvpn_client/override/server - Allow network alias and non-strict network address for `tunnel_network`/`tunnel_network6` (https://github.com/pfsensible/core/issues/77) - pfsense_openvpn_server - Fix use of `generate` with `shared_key` and `tls` (https://github.com/pfsensible/core/issues/81) - pfsense_setup - No default values - leads to unexpected changes (https://github.com/pfsensible/core/issues/91) - pfsense_user - Fix setting system group membership (https://github.com/pfsensible/core/issues/70) New Modules ----------- - pfsensible.core.pfsense_default_gateway - Manage pfSense default gateway - pfsensible.core.pfsense_dns_resolver - Manage pfSense DNS resolver (unbound) settings ================================================ FILE: GENERATING_MODULES.md ================================================ # Generating Modules with pfsensible-generate-module 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. ## Modules that manage multiple items If this is a module that will allow you to create multiple items (e.g. aliases, rules): * Save a minimal item with a name (often Name or Description) of `item_min` (or something else if that does not work). Simply try immediately saving an item with just that name, then fill out fields one at a time and re-save until pfSense stops complaining about missing items. * Save a "fully" configured item with a name of `item_full` (or something else if that will not work). It may be helpful to change as many options away from the default as possible. Focus on settings that would be useful to you. * Run the script: misc/pfsensible-generate-module --url URL if you needed to use different names for the items than `item_min` and `item_full` you can set them with the `--item-min` and `--item-full` options. ## Modules that configure something If this is a module that will just configure something, it is best to start with the default configuration. Then add the --is-config` option: misc/pfsensible-generate-module --url URL --is-config ## Other options * Pass the `--author-name`, `--author-email`, and `--author-handle` options to give yourself credit! * You will need to add the `--user` and/or `--password` options if you have changed from the install defaults. * If the automatically determined module name does not seem correct, you can change it with the `--module-name` option. * It may make sense to create a module for different types of items if the parameters are wildly different (as is the case with the different types of authentication servers for example). If so, add the `--type-suffix` option to add the "type" of the item as a suffix to the module name. ## Final steps Review the items in the generated module flagged with `TODO` for possible changes needed. ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # ansible-pfsense / pfsensible.core This is a set of modules to allow you to configure pfSense firewalls with ansible. ### NOTE: Changes with pfsensible.core 0.4.0 With pfsensible.core 0.4.0 we have stopped stripping the pfsense_ prefix from the module names. This caused conflicts with other modules (like the ansible core 'setup' module). You can use the ['collections'](https://docs.ansible.com/ansible/latest/user_guide/collections_using.html#simplifying-module-names-with-the-collections-keyword) keyword in your playbooks and roles to simplify the module names instead. ## Installation using ansible galaxy Ansible Galaxy (as of version 2.9) now has an option for collections. A collection is a distribution format for delivering all type of Ansible content (not just roles as it was before). To install: ``` ansible-galaxy collection install pfsensible.core ``` Optionally, you can specify the path of the collection installation with the `-p` option. ``` ansible-galaxy collection install pfsensible.core -p ./collections ``` Additionally, you can set the `collections_paths` option in your `ansible.cfg` file to automatically designate install locations. ```ini # ansible.cfg [defaults] collections_paths=collections ``` ## Configuration Current versions of ansible should automatically detect the version of Python on the pfSense system. If Python discovery fails, you can set ansible_python_interpreter in your playbook or hosts vars, e.g. for pfSense 2.7.2: ``` ansible_python_interpreter: /usr/local/bin/python3.11 ``` Modules must run as root in order to make changes to the system. By default pfSense does not have sudo capability so `become` will not work. You can install it with: ``` - name: "Install packages" package: name: - pfSense-pkg-sudo state: present ``` and then configure sudo so that your user has permission to use sudo. ## Modules The following modules are currently available: * [pfsense_alias](https://github.com/pfsensible/core/wiki/pfsense_alias) for aliases * [pfsense_authserver_ldap](https://github.com/pfsensible/core/wiki/pfsense_authserver_ldap) for LDAP authentication servers * [pfsense_authserver_radius](https://github.com/pfsensible/core/wiki/pfsense_authserver_radius) for RADIUS authentication servers * [pfsense_ca](https://github.com/pfsensible/core/wiki/pfsense_ca) for Certificate Authorities * [pfsense_cert](https://github.com/pfsensible/core/wiki/pfsense_cert) for Certificates * [pfsense_default_gateway](https://github.com/pfsensible/core/wiki/pfsense_default_gateway) for setting the default gateways * [pfsense_dhcp_static](https://github.com/pfsensible/core/wiki/pfsense_dhcp_static) for static DHCP entries * [pfsense_dns_resolver](https://github.com/pfsensible/core/wiki/pfsense_dns_resolver) for DNS resolver (unbound) settings * [pfsense_gateway](https://github.com/pfsensible/core/wiki/pfsense_gateway) for routing gateways * [pfsense_group](https://github.com/pfsensible/core/wiki/pfsense_group) for user groups * [pfsense_interface](https://github.com/pfsensible/core/wiki/pfsense_interface) for interfaces * [pfsense_interface_group](https://github.com/pfsensible/core/wiki/pfsense_interface_group) for interface groups * [pfsense_ipsec](https://github.com/pfsensible/core/wiki/pfsense_ipsec) for IPsec tunnels and phase 1 options * [pfsense_ipsec_proposal](https://github.com/pfsensible/core/wiki/pfsense_ipsec_proposal) for IPsec proposals * [pfsense_ipsec_p2](https://github.com/pfsensible/core/wiki/pfsense_ipsec_p2) for IPsec tunnels phase 2 options * [pfsense_log_settings](https://github.com/pfsensible/core/wiki/pfsense_log_settings) for logging settings * [pfsense_openvpn_client](https://github.com/pfsensible/core/wiki/pfsense_openvpn_client) for OpenVPN client configuration * [pfsense_openvpn_override](https://github.com/pfsensible/core/wiki/pfsense_openvpn_override) for OpenVPN override configuration * [pfsense_openvpn_server](https://github.com/pfsensible/core/wiki/pfsense_openvpn_server) for OpenVPN server configuration * [pfsense_nat_outbound](https://github.com/pfsensible/core/wiki/pfsense_nat_outbound) for outbound NAT (SNAT) rules * [pfsense_nat_port_forward](https://github.com/pfsensible/core/wiki/pfsense_nat_port_forward) for port forwarding NAT (DNAT) rules * [pfsense_rewrite_config](https://github.com/pfsensible/core/wiki/pfsense_rewrite_config) to rewrite config.xml * [pfsense_route](https://github.com/pfsensible/core/wiki/pfsense_route) for routes * [pfsense_rule](https://github.com/pfsensible/core/wiki/pfsense_rule) for firewall rules * [pfsense_rule_separator](https://github.com/pfsensible/core/wiki/pfsense_rule_separator) for firewall rule separators * [pfsense_setup](https://github.com/pfsensible/core/wiki/pfsense_setup) for general setup * [pfsense_user](https://github.com/pfsensible/core/wiki/pfsense_user) for users * [pfsense_vlan](https://github.com/pfsensible/core/wiki/pfsense_vlan) for VLANs ## Bulk modules These modules allow you to make important changes at once and, using the purge parameters, to keep the targets configuration strictly synchronized with your playbooks: * [pfsense_aggregate](https://github.com/pfsensible/core/wiki/pfsense_aggregate) for firewall aliases, rules, and rule separators, plus interfaces and VLANs * [pfsense_ipsec_aggregate](https://github.com/pfsensible/core/wiki/pfsense_ipsec_aggregate) for IPsec tunnels, phases 1, phases 2 and proposals ## Third party modules These modules allow you to manage installed packages: * [pfsense_haproxy_backend](https://github.com/pfsensible/core/wiki/pfsense_haproxy_backend) for HAProxy backends * [pfsense_haproxy_backend_server](https://github.com/pfsensible/core/wiki/pfsense_haproxy_backend_server) for HAProxy backends servers ## [Change Log](https://github.com/pfsensible/core/blob/master/CHANGELOG.rst) ## High-Availability Configuration Syncing pfsensible modules do not trigger an XMLRPC configuration sync to a secondary system. But this can be done with the use of a handler as shown: ``` tasks: - name: Make a chage pfsensible.core.alias: name: an_alias state: absent become: true notify: sync config handlers: - name: sync config pfsensible.core.pfsense_rewrite_config: become: true ``` ## Writing new modules See [GENERATING_MODULES](https://github.com/pfsensible/core/blob/master/GENERATING_MODULES.md) for instructions on how to use the pfensible-generate-module script to automate the task writing basic pfsensible modules. ## Operation Modules in the collection work by editing `/cf/conf/config.xml` using xml.etree.ElementTree, then calling the appropriate PHP update function via the pfSense PHP developer shell. Some formatting is lost, and CDATA items are converted to normal entries, but so far no problems with that have been noted. ## License GPLv3.0 or later ================================================ FILE: changelogs/.plugin-cache.yaml ================================================ objects: {} plugins: become: {} cache: {} callback: {} cliconf: {} connection: {} httpapi: {} inventory: {} lookup: pfsense: description: Generate pfSense aliases, rules and rule_separators name: pfsense version_added: 0.1.0 module: pfsense_aggregate: description: Manage multiple pfSense firewall aliases, rules, and rule separators, plus interfaces and VLANs name: pfsense_aggregate namespace: '' version_added: 0.1.0 pfsense_alias: description: Manage pfSense aliases name: pfsense_alias namespace: '' version_added: 0.1.0 pfsense_authserver_ldap: description: Manage pfSense LDAP authentication servers name: pfsense_authserver_ldap namespace: '' version_added: 0.1.0 pfsense_authserver_radius: description: Manage pfSense RADIUS authentication servers name: pfsense_authserver_radius namespace: '' version_added: 0.5.0 pfsense_ca: description: Manage pfSense Certificate Authorities name: pfsense_ca namespace: '' version_added: 0.1.0 pfsense_cert: description: Manage pfSense certificates name: pfsense_cert namespace: '' version_added: 0.5.0 pfsense_default_gateway: description: Manage pfSense default gateway name: pfsense_default_gateway namespace: '' version_added: 0.6.0 pfsense_dhcp_server: description: Manage pfSense DHCP servers name: pfsense_dhcp_server namespace: '' version_added: 0.7.0 pfsense_dhcp_static: description: Manage pfSense DHCP static mapping name: pfsense_dhcp_static namespace: '' version_added: 0.5.0 pfsense_dns_resolver: description: Manage pfSense DNS resolver (unbound) settings name: pfsense_dns_resolver namespace: '' version_added: 0.6.0 pfsense_gateway: description: Manage pfSense gateways name: pfsense_gateway namespace: '' version_added: 0.1.0 pfsense_group: description: Manage pfSense user groups name: pfsense_group namespace: '' version_added: 0.1.0 pfsense_haproxy_backend: description: Manage pfSense HAProxy backends name: pfsense_haproxy_backend namespace: '' version_added: 0.1.0 pfsense_haproxy_backend_server: description: Manage pfSense haproxy backend servers name: pfsense_haproxy_backend_server namespace: '' version_added: 0.1.0 pfsense_interface: description: Manage pfSense interfaces name: pfsense_interface namespace: '' version_added: 0.1.0 pfsense_interface_group: description: Manage pfSense interface groups name: pfsense_interface_group namespace: '' version_added: 0.5.0 pfsense_ipsec: description: Manage pfSense IPsec tunnels and phase 1 options name: pfsense_ipsec namespace: '' version_added: 0.1.0 pfsense_ipsec_aggregate: description: Manage multiple pfSense IPsec tunnels, phases 1, phases 2 and proposals name: pfsense_ipsec_aggregate namespace: '' version_added: 0.1.0 pfsense_ipsec_p2: description: Manage pfSense IPsec tunnels phase 2 options name: pfsense_ipsec_p2 namespace: '' version_added: 0.1.0 pfsense_ipsec_proposal: description: Manage pfSense IPsec proposals name: pfsense_ipsec_proposal namespace: '' version_added: 0.1.0 pfsense_log_settings: description: Manage pfSense syslog settings name: pfsense_log_settings namespace: '' version_added: 0.4.2 pfsense_nat_outbound: description: Manage pfSense Outbound NAT (SNAT) rules name: pfsense_nat_outbound namespace: '' version_added: 0.1.0 pfsense_nat_port_forward: description: Manage pfSense port forwarding NAT (DNAT) rules name: pfsense_nat_port_forward namespace: '' version_added: 0.1.0 pfsense_openvpn_client: description: Manage pfSense OpenVPN configuration name: pfsense_openvpn_client namespace: '' version_added: 0.5.0 pfsense_openvpn_override: description: Manage pfSense OpenVPN Client Specific Overrides name: pfsense_openvpn_override namespace: '' version_added: 0.5.0 pfsense_openvpn_server: description: Manage pfSense OpenVPN server configuration name: pfsense_openvpn_server namespace: '' version_added: 0.5.0 pfsense_phpshell: description: PHP Shell name: pfsense_phpshell namespace: '' version_added: 0.7.0 pfsense_rewrite_config: description: Rewrite pfSense config.xml name: pfsense_rewrite_config namespace: '' version_added: 0.5.3 pfsense_route: description: Manage pfSense routes name: pfsense_route namespace: '' version_added: 0.1.0 pfsense_rule: description: Manage pfSense firewall rules name: pfsense_rule namespace: '' version_added: 0.1.0 pfsense_rule_separator: description: Manage pfSense firewall rule separators name: pfsense_rule_separator namespace: '' version_added: 0.1.0 pfsense_setup: description: Manage pfSense general setup name: pfsense_setup namespace: '' version_added: 0.1.0 pfsense_shellcmd: description: Manage pfSense shellcmds name: pfsense_shellcmd namespace: '' version_added: 0.7.0 pfsense_user: description: Manage pfSense users name: pfsense_user namespace: '' version_added: 0.1.0 pfsense_vlan: description: Manage pfSense VLANs name: pfsense_vlan namespace: '' version_added: 0.1.0 netconf: {} shell: {} strategy: {} vars: {} version: 0.7.1 ================================================ FILE: changelogs/134_openvpn_digest.yml ================================================ bugfixes: - pfsense_openvpn_client/server - Support additional digest values (https://github.com/pfsensible/core/issues/134). ================================================ FILE: changelogs/changelog.yaml ================================================ ancestor: null releases: 0.6.0: changes: bugfixes: - pfsense_aggregate - Fix where a rule with a duplicated name would not be deleted if required - pfsense_dhcp_static - Allow removing entry with just name (https://github.com/pfsensible/core/issues/69) - pfsense_dhcp_static - Allow use of display name for netif. Error in case a interface group name is specified (https://github.com/pfsensible/core/issues/79) - pfsense_interface - Properly shut dwon interface and kill dhclient process when removing interface (https://github.com/pfsensible/core/pull/67) - pfsense_interface_group - Check that members list is unique - pfsense_interface_group - Fix creation (https://github.com/pfsensible/core/issues/74) - pfsense_interface_group - `members` is only required for creation - pfsense_nat_outbound - Fix boolean values, invert (https://github.com/pfsensible/core/issues/92) - pfsense_openvpn_client - Fix strictuserdn -> strictusercn option (https://github.com/pfsensible/core/pull/93) - pfsense_openvpn_client/override/server - Allow network alias and non-strict network address for `tunnel_network`/`tunnel_network6` (https://github.com/pfsensible/core/issues/77) - pfsense_openvpn_server - Fix use of `generate` with `shared_key` and `tls` (https://github.com/pfsensible/core/issues/81) - pfsense_setup - No default values - leads to unexpected changes (https://github.com/pfsensible/core/issues/91) - pfsense_user - Fix setting system group membership (https://github.com/pfsensible/core/issues/70) major_changes: - pfsense_default_gateway - Add module for setting the default gateways - pfsense_dns_resolver - Add module for DNS resolver (unbound) settings minor_changes: - ipaddress support for pfSense 2.4.4 - pfsense_cert - Support EC certs (https://github.com/pfsensible/core/pull/98) - pfsense_interface - Always return `ifname` - even on interface creation - pfsense_interface - Prevent removal if interface is part of an interface group - pfsense_nat_outbound - Allow for NET:INTERFACE addresses - pfsense_nat_port_forward - 2.4.5 compatibility - pfsense_openvpn_server - Do not allow removal of an instance with an interface assignment - pfsense_rule - Add option to ignore an inexistent queue - pfsense_rule - Add support for floating 'any' interface rule (https://github.com/pfsensible/core/pull/90) - plugins/lookup/pfsense - Optimization and ignore queue setting - tests/plays - Add plays for testing with a live pfSense instance fragments: - 0.6.0-changes.yaml modules: - description: Manage pfSense default gateway name: pfsense_default_gateway namespace: '' - description: Manage pfSense DNS resolver (unbound) settings name: pfsense_dns_resolver namespace: '' release_date: '2024-01-06' 0.6.1: changes: deprecated_features: - The pfsensible_haproxy* modules have moved to the `pfsensible.haproxy` collection and will be removed from `pfsensible.core` in version 0.8.0. minor_changes: - Bump required ansible version to 2.12. - Have _get_ansible_param_bool set the value to value_false if the parameter is present and false. - Refactor pfsense_authserver_ldap and pfsense_authserver_radius. Should not have any visible impact. - Ship tests so other pfsensible collections can use them. - pfsense_ca - allow for disabling `randomserial` and `trust` parameters. - pfsense_dhcp_static - Add arp_table_static_entry argument (https://github.com/https://github.com/pfsensible/core/issues/109). fragments: - 111-Add-arp_table-static_entry.yml - ansible-requires.yml - authserver-refactor.yml - deprecate_haproxy.yml - module-base-bool.yml - pfsense_ca-allow-disabling.yml - ship-tests.yml release_date: '2024-01-20' 0.6.2: changes: bugfixes: - made pfsense_dns_resolver hosts idempotent (https://github.com/pfsensible/core/issues/151) - pfsense - handle "."s prefixing php() output triggered by the presense of /var/run/booting and issue a warning (https://github.com/pfsensible/core/issues/118) - pfsense_dns_resolver - allow for comma separated list of IP addresses in ``hosts.ip`` (https://github.com/pfsensible/core/discussions/150) - pfsense_openvpn_client - add ``tls_type`` parameter - pfsense_openvpn_client/server - apply ``tls`` setting to config (https://github.com/pfsensible/core/issues/132) - pfsense_user - fixed setting multiple groups for a user (https://github.com/pfsensible/core/issues/130) - set `global $config;` in phpshell() to find update commands in pfSense Plus 24.11 minor_changes: - added ``auto`` choice for ``myid_type`` and ``peerid_type`` (https://github.com/pfsensible/core/issues/145) - pfsense_ca - added ``key`` parameter to import CA private key (https://github.com/pfsensible/core/issues/57) - pfsense_dns_resolver - validate ``domainoverrides.ip`` field - pfsense_openvpn_client - added ``v4only`` and `v6only`` values for ``create_gw`` (https://github.com/pfsensible/core/issues/133) - pfsense_openvpn_override - support changed semantics of ``push_reset`` in pfSense Plus 24.11 - pfsense_openvpn_server - no longer sort authmode items - pfsense_setup - Update language list for pfSense 2.7.1 / pfSense Plus 23.09. - 'pfsensible_interface - implemented ``ipv6_type: slaac`` and added the ``slaacusev4iface`` parameter (https://github.com/pfsensible/core/issues/121).' - pfsensible_openvpn_server - Allow ``Local Database`` for ``authmode`` parameter (https://github.com/pfsensible/core/issues/125). fragments: - booting.yml - ca_key.yml - dnf_resolver_aliases.yml - dns_resolver_ip.yml - interface-slaac.yml - ipsec_auto.yml - langauages.yml - openvpn_client_gw.yml - openvpn_localdb.yml - openvpn_override.yml - openvpn_server_unsorted_authmode.yml - openvpn_tls.yml - phpshell_config.yml - user_groups.yml release_date: '2025-01-30' 0.7.0: changes: breaking_changes: - This release is only expected to work with pfSense 2.8.0+ / pfSense Plus 24.11+ due to changes in various lookup_*() functions in pfSense. bugfixes: - Use config_get_path() to load configuration in php update commands. Fixes various update commands not working with pfSense 2.8.0 (https://github.com/pfsensible/core/issues/190) - pfsense_ca / pfsense_cert - Fix validation of base64 encoded keys and certs. (https://github.com/pfsensible/core/issues/174) - pfsense_ca/pfsense_cert - Restart services affected by updated certificates. (https://github.com/pfsensible/core/issues/191) - pfsense_cert - Write generated internal certificate into config. (https://github.com/pfsensible/core/issues/186) - pfsense_dns_resolver - do not always add an empty domainoverrides item. (https://github.com/pfsensible/core/issues/187) - pfsense_interface - fixes removal of an interface when interface group is empty. (https://github.com/pfsensible/core/issues/182) - 'pfsense_interface - fixes removal of an interface with `state: absent`. _remove_all_separators() works when no separator exists for that interface. (https://github.com/pfsensible/core/issues/170)' minor_changes: - pfsense_alias - Add `url` parameter and deprecate using `address` for `urltable` and `urltable_ports` types. - pfsense_ca - Add ability to create internal CAs. (https://github.com/pfsensible/core/issues/135) - pfsense_rule - Change `after` to insert after the last match instead of the first. release_summary: 'This is a major refactoring of the ``pfsensible.core`` collection. The goal was to support easier creation of new modules via the ``pfsensible-generate-module`` script. PFSenseModuleBase was expanded to handle more common functions via configuration options and callback functions.' fragments: - 0.7.0.yml - 135_pfsense_ca_create_internal.yml - 170_pfsense_interface_fix_remove_all_separators.yml - 174_pfsense_cert_validate_base64.yml - 182_interface_group_null_check.yml - 186_fix_pfsense_cert_internal.yml - 187_dns_resolver_domainoverrides.yml - 190_config_get_path.yml - 191_cert_restart_services.yml - pfsense_alias-add-url.yml - pfsense_rule-after.yml modules: - description: Manage pfSense DHCP servers name: pfsense_dhcp_server namespace: '' - description: PHP Shell name: pfsense_phpshell namespace: '' - description: Manage pfSense shellcmds name: pfsense_shellcmd namespace: '' release_date: '2025-09-22' 0.7.1: changes: bugfixes: - pfsense_aggregate - fix argument_spec handling for aggregated modules that broke aggregated_nat_outbounds (https://github.com/pfsensible/core/issues/201). - pfsense_authserver_ldap - Call set_pam_auth() if needed to update system config. - pfsense_authserver_ldap - Fix disabling ldap_allow_unauthenticated (https://github.com/pfsensible/core/issues/139). - pfsense_ca - Better validation for name, lifetime, and dn_* parameters (https://github.com/pfsensible/core/pull/142). - pfsense_dhcp_server - Describe denyunknown options and allow disabling it via `disabled` (https://github.com/pfsensible/core/issues/203). - pfsense_dns_resolver - Add ability to specify Virtual IPs for interfaces (https://github.com/pfsensible/core/issues/136). - pfsense_dns_resolver - Fix configuration without domainoverrides set (https://github.com/pfsensible/core/issues/206). - pfsense_dns_resolver - Fix forward_tls_upstream handling in domainoverrides (https://github.com/pfsensible/core/issues/209). - pfsense_ipsec_p2 - Allow disabling hash algorithms (https://github.com/pfsensible/core/issues/172) - pfsense_setup - Fix PHP command to update system broken in 0.7.0 (https://github.com/pfsensible/core/pull/210). minor_changes: - pfsense_ipsec_p2/proposal - Add missing new DH Groups 31, 32 support in ipsec vpn (https://github.com/pfsensible/core/issues/183) - pfsense_log_settings - add nologlinklocal4, nologsnort2c, and logconfigchanges parameters (https://github.com/pfsensible/core/pull/199). - pfsense_user - add disabled parameter (https://github.com/pfsensible/core/pull/208). fragments: - 136_dns_resolver_domainoverrides.yml - 139_ldap_allow_unauthenticated.yml - 142_ca_validate.yml - 172_ipsec_hash.yml - 183_ipsec_dh.yml - 199_pfsense_log_settings_parameters.yml - 201_pfsense_aggregate_nat.yml - 203_dhcp_server_denyunknown.yml - 206_dns_resolver_domainoverrides.yml - 208_pfsense_user_disabled.yml - 209_dns_resolver_domainoverrides.yml - 210_setup.yml - pfsense_authserver_ldap_pam.yml release_date: '2025-11-09' ================================================ FILE: changelogs/config.yaml ================================================ changelog_filename_template: ../CHANGELOG.rst changelog_filename_version_depth: 0 changes_file: changelog.yaml changes_format: combined ignore_other_fragment_extensions: true keep_fragments: false mention_ancestor: true new_plugins_after_name: removed_features notesdir: fragments prelude_section_name: release_summary prelude_section_title: Release Summary sanitize_changelog: true sections: - - major_changes - Major Changes - - minor_changes - Minor Changes - - breaking_changes - Breaking Changes / Porting Guide - - deprecated_features - Deprecated Features - - removed_features - Removed Features (previously deprecated) - - security_fixes - Security Fixes - - bugfixes - Bugfixes - - known_issues - Known Issues title: pfSensible.Core trivial_section_name: trivial use_fqcn: true ================================================ FILE: changelogs/fragments/129_sshguard_whitelist.yaml ================================================ minor_changes: - pfsense_setup - added sshguard_whitelist option (https://github.com/pfsensible/core/issues/129). ================================================ FILE: changelogs/fragments/217_pfsense_setup_webguicert.yml ================================================ minor_changes: - pfsense_setup - add ``webguicert`` parameter (https://github.com/pfsensible/core/pull/217). ================================================ FILE: changelogs/fragments/219_parse_address_ipv6.yml ================================================ bugfixes: - pfsense_rule - Allow IPv6 addresses in source and destination (https://github.com/pfsensible/core/issues/219). ================================================ FILE: changelogs/fragments/223_fix_openvpn_alias_expansion.yml ================================================ minor_changes: - pfsense_openvpn_server - add call to ``alias_make_table()`` to allow alias expansion (https://github.com/pfsensible/core/pull/223). ================================================ FILE: changelogs/fragments/224_add_dco_for_plus_versions.yml ================================================ minor_changes: - pfsense_openvpn_server - add ``dco`` parameter (https://github.com/pfsensible/core/pull/224). - improve pfsense.is_ce_version to better support CE and Plus comparison ================================================ FILE: changelogs/fragments/226_dns_resolver.yaml ================================================ bugfixes: - pfsense_dns_resolver - Allow IPv6 addresses for hosts and domainoverrides (https://github.com/pfsensible/core/pull/245). ================================================ FILE: changelogs/fragments/228_interface_diff.yml ================================================ minor_changes: - pfsense_interface - support ``--diff`` (https://github.com/pfsensible/core/pull/228). ================================================ FILE: changelogs/fragments/238_pfsense_openvpn_server.yml ================================================ bugfixes: - pfsense_openvpn_server - Normalize `tls` text to CRLF line endings to match web interface (https://github.com/pfsensible/core/issues/163). minor_changes: - pfsense_openvpn_server - Drop `ncp_enable` parameter no longer used (https://github.com/pfsensible/core/pull/238). - pfsense_openvpn_server - No longer remove `strictusercn` option if not specified to match web interface (https://github.com/pfsensible/core/pull/238). ================================================ FILE: changelogs/fragments/239_sync_config.yml ================================================ bugfixes: - pfsense_rewrite_config - Drop obsolete and unneeded call to parse_config() (https://github.com/pfsensible/core/issues/239). minor_changes: - Add note to README about using pfsense_write_config to trigger XMLRPC configuration syncs (https://github.com/pfsensible/core/issues/239). ================================================ FILE: changelogs/fragments/242_gateway_loss.yml ================================================ minor_changes: - pfsense_gateway - Add losshigh/losslow parameters (https://github.com/pfsensible/core/pull/242). ================================================ FILE: changelogs/fragments/243_openvpn_client.yml ================================================ bugfixes: - pfsense_openvpn_client - Fix index calculation so that it actually updates the running client configuration (https://github.com/pfsensible/core/pull/243). minor_changes: - pfsense_openvpn_client - Return the vpnid (https://github.com/pfsensible/core/pull/243). ================================================ FILE: changelogs/fragments/245_arg_route.yaml ================================================ bugfixes: - Fix initialization of arg_route (https://github.com/pfsensible/core/pull/245). ================================================ FILE: changelogs/fragments/248_class_level_imports.yaml ================================================ minor_changes: - Remove class level imports in PFSenseModule to support the use of Mitogen (https://github.com/pfsensible/core/pull/248). ================================================ FILE: changelogs/fragments/251_setup_hardware.yaml ================================================ minor_changes: - pfsense_setup - add crypto_hardware and thermal_hardware parameters (https://github.com/pfsensible/core/pull/251). ================================================ FILE: changelogs/fragments/rule_pass_before_deny_ordering.yml ================================================ bugfixes: - pfsense_rule - New pass/match rules without explicit ``after`` or ``before`` are now inserted before the first block/reject rule on the same interface, preserving correct allow-before-deny ordering. ================================================ FILE: changelogs/fragments/rule_protocol_any_with_ports.yml ================================================ bugfixes: - pfsense_rule - Allow protocol ``any`` with destination/source ports, matching pfSense UI behaviour. ================================================ FILE: examples/ipsec/README.md ================================================ # Managing ipsec tunnels with ansible-pfsense This example will demonstrate how to manage your ipsec configuration. It is designed for people who have multiple pfSense firewalls to setup. ## Description We want to configure 3 firewalls and setup a fully connected VPN network between them. We assume a standardized configuration (like each firewall uses it's wan interface), done with ansible-pfsense indeed. To easily acheive this goal, I have wrote an ansible filter. It takes a yaml file for input, describing the desired VPNs properties, and generates output parameters for the module [pfsense_ipsec_aggregate](https://github.com/opoplawski/ansible-pfsense/wiki/pfsense_ipsec_aggregate). If you want to add new firewalls and networks to your topology, it only requires a few more lines in the yaml definition file. As far as possible, I tried to use the same parameters as for the ansible-pfsense ipsec modules, in order to make writing the configuration yaml file more natural. ## Files * ipsecs.yaml: the VPN properties * hosts: the Ansible file for pfsense hosts * setup_ipsec.yml: the playbook used to setup all the pfsenses * filter_plugins/pfsense.py: the formatting plugin * more.ipsecs.yaml: more VPN properties ## Installation You don't need to copy any files. Just adapt your ansible hosts file like the one provided or adapt the yaml file with your hosts. To run the test in check mode for all the 3 firewalls, just go into your ansible-pfsense directory and run: ``` ansible-playbook -C -v examples/ipsec/setup_ipsec.yml ``` ## TODO The filter plugin needs to be improved to support all kind of configuration (especially regarding authentication parameters). ================================================ FILE: examples/ipsec/filter_plugins/pfsense.py ================================================ # -*- coding: utf-8 -*- # Copyright: (c) 2019, Frederic Bor # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleFilterError def format_ipsec_aggregate_ipsecs(all_tunnels, pfname): """ format ipsecs for format_ipsec_aggregate """ res = list() for name, ipsec in all_tunnels.items(): pfsenses = ipsec['pfsenses'] if pfname not in pfsenses: continue local = pfsenses[pfname] for remote_name, remote_options in pfsenses.items(): if remote_name == pfname: continue params = dict() res.append(params) params['descr'] = name + ' to ' + remote_name params['state'] = 'present' for option in ipsec: if option in ['pfsenses', 'phase1', 'phase2']: continue params[option] = ipsec[option] for option in remote_options: if option in ['sharing', 'myid_data']: continue params[option] = remote_options[option] if 'peerid_type' in params and params['peerid_type'] == 'keyid tag': params['peerid_data'] = remote_options['myid_data'] if 'myid_data' in local: params['myid_data'] = local['myid_data'] return res def format_ipsec_aggregate_proposals(all_tunnels, pfname): """ format proposals for format_ipsec_aggregate """ res = list() for name, ipsec in all_tunnels.items(): pfsenses = ipsec['pfsenses'] if pfname not in pfsenses: continue if 'phase1' not in ipsec: raise AnsibleFilterError("phase1 is missing in {0}".format(name)) phase1 = ipsec['phase1'] p1s = list() if 'encryptions' not in phase1: raise AnsibleFilterError("encryptions is missing in phase1 of {0}".format(name)) if 'hashes' not in phase1: raise AnsibleFilterError("hashes is missing in phase1 of {0}".format(name)) encryptions = phase1['encryptions'] hashes = phase1['hashes'].split(' ') for remote_name in pfsenses: if remote_name == pfname: continue for encryption in encryptions: for hash_option in hashes: params = dict() p1s.append(params) params['descr'] = name + ' to ' + remote_name params['state'] = 'present' params['hash'] = hash_option params['encryption'] = encryption if encryptions[encryption] is not None and encryptions[encryption] != 'None': params['key_length'] = encryptions[encryption] for p1_option in phase1: if p1_option in ['encryptions', 'hashes']: continue for p1 in p1s: p1[p1_option] = phase1[p1_option] res.extend(p1s) return res def format_ipsec_aggregate_p2s(all_tunnels, pfname): """ format p2s for format_ipsec_aggregate """ res = list() for name, ipsec in all_tunnels.items(): pfsenses = ipsec['pfsenses'] if pfname not in pfsenses: continue if 'phase2' not in ipsec: raise AnsibleFilterError("phase2 is missing in {0}".format(name)) phase2 = ipsec['phase2'] if 'mode' not in phase2: raise AnsibleFilterError("mode is missing in phase2 of {0}".format(name)) mode = phase2['mode'] local = pfsenses[pfname] if 'sharing' in local: local_sharing = local['sharing'].split(' ') elif mode != 'transport': raise AnsibleFilterError("sharing is missing for {0} in {1}".format(pfname, name)) p2s = list() for remote_name, remote in pfsenses.items(): if remote_name == pfname: continue if 'sharing' in remote: remote_sharing = remote['sharing'].split(' ') elif mode != 'transport': raise AnsibleFilterError("sharing is missing for {0} in {1}".format(remote_name, name)) if mode != 'transport': for local_network in local_sharing: for remote_network in remote_sharing: params = dict() p2s.append(params) params['p1_descr'] = name + ' to ' + remote_name params['descr'] = local_network + ' to ' + remote_network params['state'] = 'present' params['local'] = local_network params['remote'] = remote_network else: params = dict() p2s.append(params) params['descr'] = name + ' to ' + remote_name params['p1_descr'] = name + ' to ' + remote_name params['state'] = 'present' for p2_option, p2_value in phase2.items(): for p2 in p2s: if p2_option == 'encryptions': for encryption, keylength in p2_value.items(): p2[encryption] = True if keylength is not None and keylength != 'None': if isinstance(keylength, str): p2[encryption + '_len'] = keylength else: p2[encryption + '_len'] = str(keylength) elif p2_option == 'hashes': hashes = p2_value.split(' ') for hash_option in hashes: p2[hash_option] = True else: p2[p2_option] = p2_value res.extend(p2s) return res def format_ipsec_aggregate(*terms): """ format var for ipsec_aggregate """ if len(terms) != 2 or not isinstance(terms[0], dict): raise AnsibleFilterError("format_ipsec_aggregate expects one dictionnary of ipsec tunnels") all_tunnels = terms[0] pfname = terms[1] res = dict() res['aggregated_ipsecs'] = format_ipsec_aggregate_ipsecs(all_tunnels, pfname) res['aggregated_ipsec_proposals'] = format_ipsec_aggregate_proposals(all_tunnels, pfname) res['aggregated_ipsec_p2s'] = format_ipsec_aggregate_p2s(all_tunnels, pfname) return res class FilterModule(object): """ FilterModule """ @staticmethod def filters(): """ defined functions """ return { 'format_ipsec_aggregate': format_ipsec_aggregate, } ================================================ FILE: examples/ipsec/hosts ================================================ [pfsense] pf_1 ansible_ssh_host=10.0.1.1 ansible_ssh_port=22 ansible_ssh_user=root ansible_password=pfsense pf_2 ansible_ssh_host=10.0.2.1 ansible_ssh_port=22 ansible_ssh_user=root ansible_password=pfsense pf_3 ansible_ssh_host=10.0.3.1 ansible_ssh_port=22 ansible_ssh_user=root ansible_password=pfsense ================================================ FILE: examples/ipsec/ipsecs.yaml ================================================ ipsec_tunnels: fully_connected_vpn: iketype: ikev2 interface: wan myid_type: keyid tag peerid_type: keyid tag authentication_method: pre_shared_key preshared_key: HHmWGzbeAtyE8f2E lifetime: 43200 mode: main pfsenses: pf_1: sharing: 192.168.1.0/24 172.16.1.0/24 remote_gateway: pf1.acme.com myid_data: pf_1_id pf_2: sharing: 192.168.2.0/24 172.16.2.0/24 remote_gateway: pf2.acme.com myid_data: pf_2_id pf_3: sharing: 192.168.3.0/24 172.16.3.0/24 10.3.3.0/24 remote_gateway: pf3.acme.com myid_data: pf_3_id phase1: encryptions: aes128gcm: 128 hashes: sha256 dhgroup: 14 phase2: encryptions: aes128gcm: 128 hashes: sha256 # misc lifetime: 7200 pfsgroup: '14' mode: tunnel ================================================ FILE: examples/ipsec/more.ipsecs.yaml ================================================ ipsec_tunnels: fully_connected_vpn: iketype: ikev2 interface: wan myid_type: keyid tag peerid_type: keyid tag authentication_method: pre_shared_key preshared_key: HHmWGzbeAtyE8f2E lifetime: 43200 mode: main pfsenses: pf_1: sharing: 192.168.1.0/24 172.16.1.0/24 remote_gateway: pf1.acme.com myid_data: pf_1_id pf_2: sharing: 192.168.2.0/24 172.16.2.0/24 remote_gateway: pf2.acme.com myid_data: pf_2_id pf_3: sharing: 192.168.3.0/24 172.16.3.0/24 10.3.3.0/24 remote_gateway: pf3.acme.com myid_data: pf_3_id phase1: encryptions: { aes128gcm: 128, aes192gcm: 128, aes256gcm: 128, cast128: } hashes: sha256 aesxcbc dhgroup: 14 phase2: encryptions: { aes128gcm: 128, aes192gcm: 128, aes256gcm: 128, cast128: None } hashes: sha512 aesxcbc # misc lifetime: 7200 pfsgroup: '14' mode: tunnel ================================================ FILE: examples/ipsec/setup_ipsec.yml ================================================ --- - hosts: pfsense gather_facts: false connection: paramiko vars_files: ipsecs.yaml vars: params: "{{ ipsec_tunnels|format_ipsec_aggregate(inventory_hostname) }}" tasks: - name: "setup ipsec" pfsensible.core.pfsense_ipsec_aggregate: purge_ipsecs: true purge_ipsec_proposals: true purge_ipsec_p2s: true aggregated_ipsecs: "{{ params['aggregated_ipsecs'] }}" aggregated_ipsec_proposals: "{{ params['aggregated_ipsec_proposals'] }}" aggregated_ipsec_p2s: "{{ params['aggregated_ipsec_p2s'] }}" ================================================ FILE: examples/lookup/README.md ================================================ # Managing rules with lookup plugin This example will demonstrate how to easily manage your rules configuration. It is designed for people who have one to many pfSense firewalls to manage. ## General description We want to configure multiple firewalls using only one set of pfSense, rules, and aliases. Especially, we don't want to have to define several rules for each flow and firewall, when we have that kind of setup: ``` Host A <--> FW1 <--> ... <--> FW2 <--> Host B ``` If we want to allow Host A to connect to Host B, there should be only one definition of the flow for both firewalls. We will write a file describing our network topology. The lookup plugin will parse that file and accordingly, will generate the required parameters for pfsense_aggregate to implement what is specified with that topology. ## Setup description Let's say we have a network in Paris with: ``` - an internet router - a pfSense (FW1) providing IPsec VTI connectivity to another office, in Fargo - a laptop - a station - a DNS/proxy/ssh server ``` And in Fargo, there is: ``` - a pfSense (FW2), providing IPsec VTI connectivity to Paris - a station - some DNS servers - access to other privates networks ``` Here are the rules we want to be defined on both FW1 and FW2: ``` - all icmp but icmp-redirect are allowed - ospf is allowed on vti interfaces - the Paris server must be able to do DNS requests to Fargo private DNS servers - the Paris server can ssh into anything to Fargo office - the Paris laptop can connect to anything to Fargo office - the Fargo station must be able to connect to the Paris server on some ports (ssh, samba, squid, etc) - the Fargo station can ssh into the Paris internet router - the Fargo station can vnc into the Paris station - the Fargo station can setup the Paris pfSense ``` ## pfSenses definition First, we will define our pfsenses: ``` pfsenses: pf_fargo: { interfaces: { WAN: { remote_networks: internet }, LAN: { ip: 10.100.200.101/24 }, SERVERS: { ip: 192.168.1.101/24 }, IPsec: { ip: 10.9.8.2/30, remote_networks: paris_lan }, } } pf_paris: { interfaces: { LAN: { ip: 10.20.30.101/24, remote_networks: internet }, IPsec: { ip: 10.9.8.1/30, remote_networks: all_fargo_subnets }, } } ``` ### Fargo pfSense On the Fargo pfSense, we are defining all networks used to access internet, the station, the servers and for the remote ipsec. We need to specify an IP address for the IPsec interface, as we need rules for OSPF. We set the routed networks threw this interface to the Paris subnet The pfSense name must match the name used in playbook. ### Paris pfSense In this setup, as the pfSense is just an IPsec gateway there is no WAN interface. The LAN interface is used to connect to internet. We declare the Fargo subnets on the IPsec interface. ## Aliases definition Now, we will define all the aliases we need: ``` hosts_aliases: paris_lan: { ip: 10.20.30.0/24 } paris_router: { ip: 10.20.30.1 } paris_station: { ip: 10.20.30.2 } paris_server: { ip: 10.20.30.3 } paris_laptop: { ip: 10.20.30.4 } paris_ssh_hosts: { ip: paris_server paris_router } fargo_station: { ip: 10.100.200.10 } fargo_ads: { ip: 192.168.1.1 192.168.1.2 192.168.1.3 } all_fargo_subnets: { ip: 192.168.0.0/16 10.0.0.0/8 172.16.0.0/16 } internet: { ip: 0.0.0.0/0 } ipsec_vtis: { ip: 10.9.8.1 10.9.8.2 } ports_aliases: admin_ports: { port: 22 80 443 } dns_port: { port: 53 } ipsec_ports: { port: 500 4500 } squid_port: { port: 3128 } ssh_port: { port: 22 } smb_ports: { port: 135 137 139 445 } vnc_ports: { port: 5900-5901 } ``` ## Rules definition Finally, here are the rules: ``` rules: options: { log: yes } CONFIG: config_from_lan: { src: paris_lan, dst: 10.20.30.101, protocol: tcp, dst_port: admin_ports } ICMP: block_redirects: { src: any, dst: any, protocol: icmp, icmptype: redir, action: block, log: yes } allow_icmp: { src: any, dst: any, protocol: icmp, icmptype: any, log: no } OSPF: ospf_vtis: { src: ipsec_vtis, dst: ipsec_vtis, protocol: ospf, log: no } FROM_FARGO: config_from_fargo: { src: fargo_station, dst: 10.20.30.101, protocol: tcp, dst_port: admin_ports } ssh_from_fargo: { src: fargo_station, dst: paris_ssh_hosts, protocol: tcp, dst_port: ssh_port } proxy_from_fargo: { src: fargo_station, dst: paris_server, protocol: tcp, dst_port: squid_port } smb_from_fargo: { src: fargo_station, dst: paris_server, protocol: tcp, dst_port: smb_ports } vnc_from_fargo: { src: fargo_station, dst: paris_station, protocol: tcp, dst_port: vnc_ports } TO_FARGO: ssh_from_server: { src: paris_server, dst: all_fargo_subnets, protocol: tcp, dst_port: ssh_port } dns_from_server: { src: paris_server, dst: fargo_ads, protocol: tcp/udp, dst_port: dns_port } laptop_to_fargo: { src: paris_laptop, dst: all_fargo_subnets, protocol: any } ``` All the rules are logged, unless specified otherwise. ## Result: All the required aliases and rules on each firewall are defined where they need to be. ### Fargo ![fargo_aliases](https://github.com/opoplawski/ansible-pfsense/blob/master/examples/lookup/images/fargo_aliases.png) ![fargo_lan](https://github.com/opoplawski/ansible-pfsense/blob/master/examples/lookup/images/fargo_lan.png) ![fargo_ipsec](https://github.com/opoplawski/ansible-pfsense/blob/master/examples/lookup/images/fargo_ipsec.png) ### Paris ![paris_aliases](https://github.com/opoplawski/ansible-pfsense/blob/master/examples/lookup/images/paris_aliases.png) ![paris_lan](https://github.com/opoplawski/ansible-pfsense/blob/master/examples/lookup/images/paris_lan.png) ![paris_ipsec](https://github.com/opoplawski/ansible-pfsense/blob/master/examples/lookup/images/paris_ipsec.png) ## Files * hosts: the Ansible file for pfsense hosts * pfsense_definitions.yaml: our rules & network topology * setup_all_rules.yml: the playbook used to setup all the pfsenses ## Installation You don't need to copy any files. Just adapt your ansible hosts file like the one provided or adapt the yaml file with your hosts. To run the test in check mode for all the 2 firewalls, just go into your ansible-pfsense directory and run: ``` ansible-playbook -C -v examples/lookup/setup_all_rules.yml ``` You can run the plugin alone to see what is generated for the pfsense_aggregate module: ``` python ./lookup_plugins/pfsense.py examples/lookup/pfsense_definitions.yaml pf_paris ``` You can also add a rule name to just see what is generated for that rule: ``` python ./lookup_plugins/pfsense.py examples/lookup/pfsense_definitions.yaml pf_paris ssh_from_fargo ``` ## TODO The lookup plugin is still a work-in-progress. The code is quite ugly on some parts and it has a lot of limitations. ================================================ FILE: examples/lookup/hosts ================================================ [pfsense] pf_paris ansible_ssh_host=10.20.30.101 ansible_ssh_port=22 ansible_ssh_user=root ansible_password=pfsense pf_fargo ansible_ssh_host=10.100.200.101 ansible_ssh_port=22 ansible_ssh_user=root ansible_password=pfsense ================================================ FILE: examples/lookup/pfsense_definitions.yaml ================================================ --- ######################################################################################################################################### # P F S E N S E S # ######################################################################################################################################### pfsenses: pf_fargo: { interfaces: { WAN: { remote_networks: internet }, LAN: { ip: 10.100.200.101/24 }, SERVERS: { ip: 192.168.1.101/24 }, IPsec: { ip: 10.9.8.2/30, remote_networks: paris_lan }, } } pf_paris: { interfaces: { LAN: { ip: 10.20.30.101/24, remote_networks: internet }, IPsec: { ip: 10.9.8.1/30, remote_networks: all_fargo_subnets }, } } ######################################################################################################################################### # R U L E S # ######################################################################################################################################### rules: options: { log: yes } CONFIG: config_from_lan: { src: paris_lan, dst: 10.20.30.101, protocol: tcp, dst_port: admin_ports } ICMP: block_redirects: { src: any, dst: any, protocol: icmp, icmptype: redir, action: block, log: yes } allow_icmp: { src: any, dst: any, protocol: icmp, icmptype: any, log: no } OSPF: ospf_vtis: { src: ipsec_vtis, dst: ipsec_vtis, protocol: ospf, log: no } FROM_FARGO: config_from_fargo: { src: fargo_station, dst: 10.20.30.101, protocol: tcp, dst_port: admin_ports } ssh_from_fargo: { src: fargo_station, dst: paris_ssh_hosts, protocol: tcp, dst_port: ssh_port } proxy_from_fargo: { src: fargo_station, dst: paris_server, protocol: tcp, dst_port: squid_port } smb_from_fargo: { src: fargo_station, dst: paris_server, protocol: tcp, dst_port: smb_ports } vnc_from_fargo: { src: fargo_station, dst: paris_station, protocol: tcp, dst_port: vnc_ports } TO_FARGO: ssh_from_server: { src: paris_server, dst: all_fargo_subnets, protocol: tcp, dst_port: ssh_port } dns_from_server: { src: paris_server, dst: fargo_ads, protocol: tcp/udp, dst_port: dns_port } laptop_to_fargo: { src: paris_laptop, dst: all_fargo_subnets, protocol: any } ######################################################################################################################################### # A L I A S E S # ######################################################################################################################################### hosts_aliases: paris_lan: { ip: 10.20.30.0/24 } paris_router: { ip: 10.20.30.1 } paris_station: { ip: 10.20.30.2 } paris_server: { ip: 10.20.30.3 } paris_laptop: { ip: 10.20.30.4 } paris_ssh_hosts: { ip: paris_server paris_router } fargo_station: { ip: 10.100.200.10 } fargo_ads: { ip: 192.168.1.1 192.168.1.2 192.168.1.3 } all_fargo_subnets: { ip: 192.168.0.0/16 10.0.0.0/8 172.16.0.0/16 } internet: { ip: 0.0.0.0/0 } ipsec_vtis: { ip: 10.9.8.1 10.9.8.2 } ports_aliases: admin_ports: { port: 22 80 443 } dns_port: { port: 53 } ipsec_ports: { port: 500 4500 } squid_port: { port: 3128 } ssh_port: { port: 22 } smb_ports: { port: 135 137 139 445 } vnc_ports: { port: 5900-5901 } ================================================ FILE: examples/lookup/setup_all_rules.yml ================================================ --- - hosts: pfsense gather_facts: true connection: paramiko vars: params: "{{ lookup('pfsense', 'examples/lookup/pfsense_definitions.yaml', 'all_definitions') }}" tasks: - name: "setup aliases, rules & seperators" pfsensible.core.pfsense_aggregate: purge_rule_separators: true purge_aliases: true purge_rules: true aggregated_aliases: "{{ params['aggregated_aliases'] }}" aggregated_rules: "{{ params['aggregated_rules'] }}" aggregated_rule_separators: "{{ params['aggregated_rule_separators'] }}" ================================================ FILE: examples/pfsense.yml ================================================ --- - hosts: pfsense roles: - pfsense ================================================ FILE: examples/pfsense_setup.yml ================================================ --- - hosts: pfsense # For initial password connection use paramiko to handle BSD prompts connection: paramiko roles: - pfsense_setup ================================================ FILE: examples/roles/pfsense/tasks/fail2ban.yml ================================================ --- - block: - name: "Add fail2ban alias" pfsensible.core.pfsense_alias: name: fail2ban type: urltable address: http://127.0.0.1/aliastables/fail2ban updatefreq: 128 descr: "For fail2ban" detail: "updated by fail2ban" state: present - name: "Add fail2ban floating rules" pfsensible.core.pfsense_rule: name: "fail2ban dynamic block {{ item.name }}" action: reject interface: wan floating: yes ipprotocol: inet protocol: any direction: "{{ item.direction }}" source: "{{ item.source }}" destination: "{{ item.destination }}" after: 'top' state: present loop: - { name: incoming, direction: "in", source: fail2ban, destination: any } - { name: outgoing, direction: "out", source: any, destination: fail2ban } tags: pfsense-fail2ban ================================================ FILE: examples/roles/pfsense/tasks/main.yml ================================================ --- - block: - name: "Add aliases" pfsensible.core.pfsense_alias: name: "{{ item.name }}" type: "{{ item.type }}" address: "{{ item.address }}" descr: "{{ item.descr }}" detail: "{{ item.detail }}" state: present loop: - name: adservers type: host address: "172.16.10.10 172.16.10.11" descr: "Active Directory Servers" detail: "ad1||ad2" - "{{ pfsense_aliases }}" - name: "Set local network" set_fact: localnet: "{{ (ansible_igb0.ipv4[0].network ~ '/' ~ ansible_igb0.ipv4[0].netmask) | ipaddr('net') }}" - name: "Add Internal traffic rules" pfsensible.core.pfsense_rule: name: "Allow Internal traffic to {{ item }}" action: pass interface: lan ipprotocol: inet protocol: any source: "{{ localnet }}" destination: "{{ item }}" after: 'top' state: present loop: - 10.0.0.0/8 - 192.168.0.0/16 - name: "Add Allow proxies out rule" pfsensible.core.pfsense_rule: name: 'Allow proxies out' action: pass interface: lan ipprotocol: inet protocol: tcp source: webfilters destination: any after: 'Allow Internal traffic to 192.168.0.0/16' state: present - name: "Add Internal DNS out rule" pfsensible.core.pfsense_rule: name: 'Allow Internal DNS traffic out' action: pass interface: lan ipprotocol: inet protocol: udp source: dns_int destination: any:53 after: 'Allow proxies out' state: present - import_tasks: fail2ban.yml tags: pfsense ================================================ FILE: examples/roles/pfsense_setup/tasks/main.yml ================================================ --- - block: - name: "Load private data" include_vars: keys.yml # Different releases of pfSense work with different nss-pam-ldapd packages - name: "Set facts" set_fact: nss_pam_ldap_pkg: http://pkg.freebsd.org/FreeBSD:11:amd64/release_2/All/nss-pam-ldapd-0.9.9.txz when: ansible_distribution_version == "11.1" - name: "Set facts" set_fact: nss_pam_ldap_pkg: http://pkg.freebsd.org/FreeBSD:11:amd64/latest/All/nss-pam-ldapd-0.9.10_1.txz when: ansible_distribution_version == "11.2" - name: "Install nss-pam-ldap" # package: # name: {{ nss_pam_ldap_pkg }} # state: present command: /usr/sbin/pkg add {{ nss_pam_ldap_pkg }} register: pkg_command changed_when: not pkg_command.stdout is search("is already installed") - name: "Install packages" package: name: "{{ item }}" state: present loop: - pfSense-pkg-sudo # For pfsense ansible tasks - py27-ipaddress - name: "Configure nslcd" template: src: nslcd.conf.j2 dest: /usr/local/etc/nslcd.conf mode: 0600 - name: "Install AD cert" copy: src: ad.example.com.crt dest: /root/ad.example.com.crt - name: "Configure /etc/nsswitch.conf" lineinfile: path: /etc/nsswitch.conf regexp: "^({{ item }}):" backrefs: yes line: '\1: files ldap' loop: - group - passwd # Work around https://github.com/ansible/ansible/issues/41970 - name: "Enable nslcd in /etc/rc.conf.local" lineinfile: path: /etc/rc.conf.local regexp: "^nslcd_enable=.*" line: 'nslcd_enable="YES"' create: yes - name: "Enable and start nslcd" service: name: nslcd enabled: true state: started - name: "Enable savehist" lineinfile: path: "/etc/skel/dot.tcshrc" regexp: '^set savehist.*' line: "set savehist='1024 merge'" - name: "Setup admin users" include_tasks: setup_user.yml vars: user: "{{ adminuser }}" loop_control: loop_var: adminuser loop: - "{{ admin_users }}" tags: users # Need to include sudoers.d in the GUI - name: "Give Domain Admins sudo rights" copy: dest: /usr/local/etc/sudoers.d/admin owner: root group: wheel mode: 0440 content: | %Domain\ Admins ALL=(ALL) NOPASSWD: ALL tags: pfsense_setup ================================================ FILE: examples/roles/pfsense_setup/tasks/setup_user.yml ================================================ --- - block: - name: "Create home directory for {{ user }}" file: path: "/home/{{ user }}" owner: "{{ user }}" group: "{{ user }}" mode: 0750 state: directory - name: "Create .ssh directory" file: path: "/home/{{ user }}/.ssh" owner: "{{ user }}" group: "{{ user }}" mode: 0700 state: directory - name: "Install {{ item }}" copy: dest: "/home/{{ user }}/{{ item }}" src: /etc/skel/dot{{ item }} remote_src: yes owner: "{{ user }}" group: "{{ user }}" loop: - .hushlogin - .tcshrc - name: "Install authorized_keys for {{ user }}" copy: dest: "/home/{{ user }}/.ssh/authorized_keys" owner: "{{ user }}" group: "{{ user }}" mode: 0600 content: "{% for pub_key in ssh_pub_key[user] %}{{ pub_key }}\n{% endfor %}" tags: users ================================================ FILE: examples/roles/pfsense_setup/templates/nslcd.conf.j2 ================================================ # This is the configuration file for the LDAP nameservice # switch library's nslcd daemon. It configures the mapping # between NSS names (see /etc/nsswitch.conf) and LDAP # information in the directory. # See the manual page nslcd.conf(5) for more information. # The user and group nslcd should run as. uid nslcd gid nslcd # The uri pointing to the LDAP server to use for name lookups. # Multiple entries may be specified. The address that is used # here should be resolvable without using LDAP (obviously). #uri ldap://127.0.0.1/ #uri ldaps://127.0.0.1/ #uri ldapi://%2fvar%2frun%2fldapi_sock/ # Note: %2f encodes the '/' used as directory separator {% for server in adservers %} uri ldaps://{{ server }}/ {% endfor %} # The LDAP version to use (defaults to 3 # if supported by client library) #ldap_version 3 # The distinguished name of the search base. base dc=example,dc=com # The distinguished name to bind to the server with. # Optional: default is to bind anonymously. binddn {{ ad_bind_user }} # The credentials to bind with. # Optional: default is no credentials. # Note that if you set a bindpw you should check the permissions of this file. bindpw {{ ad_bind_password }} # The distinguished name to perform password modifications by root by. #rootpwmoddn cn=admin,dc=example,dc=com # The default search scope. scope sub #scope one #scope base # Customize certain database lookups. #base group ou=Groups,dc=example,dc=com #base passwd ou=People,dc=example,dc=com #base shadow ou=People,dc=example,dc=com #scope group onelevel #scope hosts sub # Bind/connect timelimit. #bind_timelimit 30 # Search timelimit. #timelimit 30 # Idle timelimit. nslcd will close connections if the # server has not been contacted for the number of seconds. #idle_timelimit 3600 # Use StartTLS without verifying the server certificate. #ssl start_tls #tls_reqcert never # CA certificates for server certificate verification #tls_cacertdir /etc/ssl/certs tls_cacertfile /root/ad.crt # Seed the PRNG if /dev/urandom is not provided #tls_randfile /var/run/egd-pool # SSL cipher suite # See man ciphers for syntax #tls_ciphers TLSv1 # Client certificate and key # Use these, if your server requires client authentication. #tls_cert #tls_key # Mappings for Services for UNIX 3.5 #filter passwd (objectClass=User) #map passwd uid msSFU30Name #map passwd userPassword msSFU30Password #map passwd homeDirectory msSFU30HomeDirectory #map passwd homeDirectory msSFUHomeDirectory #filter shadow (objectClass=User) #map shadow uid msSFU30Name #map shadow userPassword msSFU30Password #filter group (objectClass=Group) #map group member msSFU30PosixMember # Mappings for Services for UNIX 2.0 #filter passwd (objectClass=User) #map passwd uid msSFUName #map passwd userPassword msSFUPassword #map passwd homeDirectory msSFUHomeDirectory #map passwd gecos msSFUName #filter shadow (objectClass=User) #map shadow uid msSFUName #map shadow userPassword msSFUPassword #map shadow shadowLastChange pwdLastSet #filter group (objectClass=Group) #map group member posixMember # Mappings for Active Directory #pagesize 1000 #referrals off #idle_timelimit 800 #filter passwd (&(objectClass=user)(!(objectClass=computer))(uidNumber=*)(unixHomeDirectory=*)) #map passwd uid sAMAccountName #map passwd homeDirectory unixHomeDirectory #map passwd gecos displayName #filter shadow (&(objectClass=user)(!(objectClass=computer))(uidNumber=*)(unixHomeDirectory=*)) #map shadow uid sAMAccountName #map shadow shadowLastChange pwdLastSet #filter group (objectClass=group) # Alternative mappings for Active Directory # (replace the SIDs in the objectSid mappings with the value for your domain) pagesize 1000 referrals off idle_timelimit 800 filter passwd (&(objectClass=user)(objectClass=person)(!(objectClass=computer))) map passwd uid sAMAccountName map passwd uidNumber objectSid:S-1-5-21-89655523-1570529619-2103694531 map passwd gidNumber objectSid:S-1-5-21-89655523-1570529619-2103694531 map passwd homeDirectory "/home/$sAMAccountName" map passwd gecos displayName map passwd loginShell "/bin/sh" filter group (|(objectClass=group)(objectClass=person)) map group cn sAMAccountName map group gidNumber objectSid:S-1-5-21-89655523-1570529619-2103694531 # Mappings for AIX SecureWay #filter passwd (objectClass=aixAccount) #map passwd uid userName #map passwd userPassword passwordChar #map passwd uidNumber uid #map passwd gidNumber gid #filter group (objectClass=aixAccessGroup) #map group cn groupName #map group gidNumber gid ================================================ FILE: galaxy.yml ================================================ ### REQUIRED # The namespace of the collection. This can be a company/brand/organization or product namespace under which all # content lives. May only contain alphanumeric characters and underscores. Additionally namespaces cannot start with # underscores or numbers and cannot contain consecutive underscores namespace: pfsensible # The name of the collection. Has the same character restrictions as 'namespace' name: core # The version of the collection. Must be compatible with semantic versioning version: 0.7.2 # The path to the Markdown (.md) readme file. This path is relative to the root of the collection readme: README.md # A list of the collection's content authors. Can be just the name or in the format 'Full Name (url) # @nicks:irc/im.site#channel' authors: - Orion Poplawski - Frederic Bor - taylor vories - Jan Wenzel ### OPTIONAL but strongly recommended # A short summary description of the collection description: Core modules for managing pfSense # Either a single license or a list of licenses for content inside of a collection. Ansible Galaxy currently only # accepts L(SPDX,https://spdx.org/licenses/) licenses. This key is mutually exclusive with 'license_file' license: - GPL-3.0-or-later # A list of tags you want to associate with the collection for indexing/searching. A tag name has the same character # requirements as 'namespace' and 'name' tags: - networking - pfsense # Collections that this collection requires to be installed for it to be usable. The key of the dict is the # collection label 'namespace.name'. The value is a version range # L(specifiers,https://python-semanticversion.readthedocs.io/en/latest/#requirement-specification). Multiple version # range specifiers can be set and are separated by ',' dependencies: {} # The URL of the originating SCM repository repository: https://github.com/pfsensible/core # The URL to any online docs documentation: https://github.com/pfsensible/core/wiki # The URL to the homepage of the collection/project homepage: https://github.com/pfsensible/core # The URL to the collection issue tracker issues: https://github.com/pfsensible/core/issues build_ignore: - .github - .gitignore - .travis.yml - '*.tar.gz' - changelogs - examples - misc - setup.cfg ================================================ FILE: meta/runtime.yml ================================================ plugin_routing: modules: pfsense_haproxy_backend: deprecation: removal_version: 0.8.0 warning_text: Use pfsensible.haproxy.pfsense_haproxy_backend instead. pfsense_haproxy_backend_server: deprecation: removal_version: 0.8.0 warning_text: Use pfsensible.haproxy.pfsense_haproxy_backend_server instead. requires_ansible: ">=2.12" ================================================ FILE: misc/.coveragerc ================================================ [run] include = *pfsense* ================================================ FILE: misc/ansible2local ================================================ #!/bin/sh if [ -z "${ANSIBLE_HOME}" ] then echo "ANSIBLE_HOME is undefined. Go into ansible directory and run 'source hacking/env-setup'" exit 1 fi cp ${ANSIBLE_HOME}/test/units/modules/network/pfsense/*.py test/units/modules/network/pfsense/ cp ${ANSIBLE_HOME}/test/units/modules/network/pfsense/fixtures/*.xml test/units/modules/network/pfsense/fixtures/ cp ${ANSIBLE_HOME}/lib/ansible/module_utils/network/pfsense/*.py module_utils/network/pfsense/ cp ${ANSIBLE_HOME}/lib/ansible/modules/network/pfsense/*.py library/ cp ${ANSIBLE_HOME}/lib/ansible/plugins/lookup/pfsense.py lookup_plugins/pfsense.py ================================================ FILE: misc/local2ansible ================================================ #!/bin/sh if [ -z "${ANSIBLE_HOME}" ] then ANSIBLE_INSTALL=`ansible --version 2> /dev/null | grep 'module location' | cut -d '=' -f 2 | sed -e s/^[[:space:]]*//` if [ -z "$ANSIBLE_INSTALL" ] then echo "ANSIBLE_HOME is undefined and ansible is not found. Install ansible or go into ansible source directory and run 'source hacking/env-setup'" exit 1 fi echo Installing into program dir: ${ANSIBLE_INSTALL} else ANSIBLE_INSTALL=${ANSIBLE_HOME}/lib/ansible echo Installing into source dir: ${ANSIBLE_INSTALL} # tests are installed in source dir only mkdir -p ${ANSIBLE_HOME}/test/units/modules/network/pfsense/fixtures cp test/units/modules/network/pfsense/*.py ${ANSIBLE_HOME}/test/units/modules/network/pfsense/ cp -rp test/units/modules/network/pfsense/fixtures/* ${ANSIBLE_HOME}/test/units/modules/network/pfsense/fixtures/ cp test/units/plugins/lookup/*.py ${ANSIBLE_HOME}/test/units/plugins/lookup/ # cp test/units/plugins/lookup/fixtures/*.yaml ${ANSIBLE_HOME}/test/units/plugins/lookup/fixtures/ fi mkdir -p ${ANSIBLE_INSTALL}/module_utils/network/pfsense mkdir -p ${ANSIBLE_INSTALL}/modules/network/pfsense # remove old modules imports rm -rf ${ANSIBLE_INSTALL}/module_utils/network/pfsense/pfense_* cp module_utils/network/pfsense/*.py ${ANSIBLE_INSTALL}/module_utils/network/pfsense/ cp library/*.py ${ANSIBLE_INSTALL}/modules/network/pfsense/ cp lookup_plugins/pfsense.py ${ANSIBLE_INSTALL}/plugins/lookup/pfsense.py touch ${ANSIBLE_INSTALL}/module_utils/network/__init__.py touch ${ANSIBLE_INSTALL}/modules/network/__init__.py touch ${ANSIBLE_INSTALL}/modules/network/pfsense/__init__.py ================================================ FILE: misc/mkpfcollection ================================================ #!/bin/bash -eux mkdir -p {examples,misc,plugins,tests/unit} git mv library/* plugins/modules/ rmdir library git mv module_utils/network/pfsense plugins/module_utils git rm -r module_utils rm -rf module_utils git mv {pfsense.yml,pfsense_setup.yml,roles} examples/ git mv lookup_plugins plugins/lookup/ git mv test/units/plugins tests/unit/ mkdir tests/unit/plugins/modules git mv test/units/modules/network/pfsense/* tests/unit/plugins/modules/ git rm -r test rm -r test sed -i -e 's/pfsense_\([a-z]\)/pfsensible.core.pfsense_\1/g' -e s,opoplawski/ansible-pfsense,pfsensible/core, README.md sed -i -e 's/\(pfsense_.*:\)/pfsensible.core.\1/g' $(find examples -name \*.yml) sed -i -e s/ansible.modules.network.pfsense/ansible_collections.pfsensible.core.plugins.modules/ \ -e s/ansible.plugins.lookup.pfsense/ansible_collections.pfsensible.core.plugins.lookup.pfsense/ \ -e "s/lookup_loader.get('pfsense')/lookup_loader.get('pfsensible.core.pfsense')/" \ -e s/ansible.module_utils.network.pfsense/ansible_collections.pfsensible.core.plugins.module_utils/ \ -e s/ansible.module_utils.compat/ansible_collections.ansible.netcommon.plugins.module_utils.compat/ \ -e s/units.compat.mock/ansible_collections.community.internal_test_tools.tests.unit.compat.mock/ \ -e s/ansible.module_utils.compat.ipaddress/ansible_collections.pfsensible.core.plugins.module_utils.compat.ipaddress/ \ -e s/units.modules.utils/ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils/ \ -e '/version_added/s/"2.10"/0.1.0/' \ $(find -name \*.py) rm -f pfsensible-core-*.tar.gz ansible-galaxy collection build ================================================ FILE: misc/mkpfsensible ================================================ #!/bin/bash -eu [ ! -d ansible-pfsense ] && echo "No such directory ansible-pfsense" && exit 1 [ ! -d pfsensible/core ] && echo "No such directory pfsensible/core" && exit 1 rm -rf pfsensible/core/{examples,misc,plugins,tests/units/modules,*.tar.gz} mkdir -p pfsensible/core/{examples,misc,plugins/modules,tests/units/modules} cp -a ansible-pfsense/{.gitignore,examples,LICENSE} pfsensible/core/ cp -a ansible-pfsense/{pfsense.yml,pfsense_setup.yml,roles} pfsensible/core/examples/ cp -a ansible-pfsense/lookup_plugins pfsensible/core/plugins/lookup cp -a ansible-pfsense/module_utils/network/pfsense pfsensible/core/plugins/module_utils cp -a ansible-pfsense/test/units/modules/network/pfsense/* pfsensible/core/tests/units/modules/ for path in ansible-pfsense/library/*.py do filename=${path##*/} cp -a $path pfsensible/core/plugins/modules/${filename/pfsense_/} done sed -i -e 's/\(pfsense_.*:\)/pfsensible.core.\1/g' $(find pfsensible/core/examples -name \*.yml) sed -i -e '/import\|module:\|^ *pfsense_[a-z_0-9]*:$\|descr *= *.ansible pfsense_/s/pfsense_/pfsensible.core.pfsense_/' $(find pfsensible/core/plugins/modules -name \*.py) sed -i -e '/self.name = /s/pfsense_/pfsensible.core.pfsense_/' $(find pfsensible/core -name \*.py) sed -i -e s/ansible.module_utils.network.pfsense/ansible_collections.pfsensible.core.plugins.module_utils/ $(find pfsensible -name \*.py) sed -i -e 's/ansible.modules.network.pfsense import pfsense_/ansible_collections.pfsensible.core import /' $(find pfsensible/core/tests -name \*.py) cd pfsensible/core ansible-galaxy collection build ================================================ FILE: misc/pfsense_module.py.j2 ================================================ #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) {{ year }}, {{ author_name }} <{{ author_email }}> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' --- module: pfsense_{{ module_name }} short_description: Manage pfSense {{ module_name }}{{ ' configuration' if is_config else 's' }} version_added: "0.7.0" description: - Manage pfSense {{ module_name }}{{ ' configuration' if is_config else 's' }}.{{ ' This requires the pfSense ' ~ package ~ ' package to be installed.' if package != 'core' else '' }} options: {% if not is_config %} {{ name_param }}: description: The {{ name_param }} of the {{ module_name }}. required: true type: str state: description: State in which to leave the {{ module_name }}. default: present choices: ['present', 'absent'] type: str {% endif %} {% for name, param in params.items() %} {{ name }}: description: {{ "'" if ':' in param['description'] else '' }}{{ param['description'] | default('') }}{{ "'" if ':' in param['description'] else '' }} {% if 'default' in param and not is_config %} default: {{ param['default'] }} {% endif %} {% if 'choices' in param %} choices: {{ param['choices'] }} {% endif %} type: {{ param['type'] | default('') }} {% if param['type'] == 'list' %} elements: {{ param['elements'] | default('str') }} {% endif %} {% endfor %} author: {{ author_name }} (@{{ author_handle }}) ''' EXAMPLES = r''' - name: {{ 'Configure' if is_config else 'Add myitem' }} {{ module_name }} pfsensible.{{ package | lower() }}.pfsense_{{ module_name }}: {% if not is_config %} {{ name_param }}: myitem {% endif %} {% for name, param in params.items() %} {% if param['example'] is defined %} {% if param['type'] == 'list' %} {{ name }}: - {{ param['example'] }} - {{ param['example2'] | default('another item') }} {% else %} {{ name }}: {{ param['example'] }} {% endif %} {% else %} {{ name }}: {% if param['type'] == 'bool' %}false{% elif param['type'] == 'list' %}{% if 'choices' in param %}['{{ param['choices'][0:1] | join("', '") }}']{% else %}['item']{% endif %}{% elif param['type'] == 'str' %}{{ param['choices'][0] if 'choices' in param else '' }}{% endif %} {% endif %} {% endfor %} {% if not is_config %} state: present - name: Remove myitem {{ module_name }} pfsensible.{{ package | lower() }}.pfsense_{{ module_name }}: {{ name_param }}: myitem state: absent {% endif %} ''' RETURN = r''' commands: description: the set of commands that would be pushed to the remote device (if pfSense had a CLI). returned: always type: list {% if is_config %} sample: ["update {{ module_name }} set ..."] {% else %} sample: ["create {{ module_name }} 'myitem'", "update {{ module_name }} 'myitem' set ...", "delete {{ module_name }} 'myitem'"] {% endif %} ''' from ansible.module_utils.basic import AnsibleModule {% if is_config %} from ansible_collections.pfsensible.core.plugins.module_utils.module_config_base import PFSenseModuleConfigBase {% else %} from ansible_collections.pfsensible.core.plugins.module_utils.module_base import PFSenseModuleBase {% endif %} {% if args_imports %} from ansible_collections.pfsensible.core.plugins.module_utils.arg_route import {{ args_imports | sort | join(', ') }} {% endif %} # TODO - Keep either this or the next compact version of {{ module_name | upper() }}_ARGUMENT_SPEC {{ module_name | upper() }}_ARGUMENT_SPEC = { {% if not is_config %} # Only {{ name_param }} should be required here - othewise you cannot remove an item with just '{{ name_param }}' # Required arguments for creation should be noted in {{ module_name | upper() }}_REQUIRED_IF = ['state', 'present', ...] below '{{ name_param }}': {'required': True, 'type': 'str'}, 'state': { 'type': 'str', 'default': 'present', 'choices': ['present', 'absent'] }, {% endif %} {% for param in params %} '{{ param }}': { {% if 'choices' in params[param] %} 'choices': {{ params[param]['choices'] }}, {% endif %} {% if 'default' in params[param] %} 'default': '{{ params[param]['default'] }}', {% endif %} 'type': '{{ params[param]['type'] | default('') }}', }, {% endfor %} } # Compact style {{ module_name | upper() }}_ARGUMENT_SPEC = dict( {% if not is_config %} # Only {{ name_param }} should be required here - othewise you cannot remove an item with just '{{ name_param }}' # Required arguments for creation should be noted in {{ module_name | upper() }}_REQUIRED_IF = ['state', 'present', ...] below {{ name_param }}=dict(required=True, type='str'), state=dict(type='str', default='present', choices=['present', 'absent']), {% endif %} {% for param in params %} {{ param }}=dict(type='{{ params[param]['type'] | default('') }}'{% if 'choices' in params[param] %}, choices={{ params[param]['choices'] }}{% endif %}{% if 'default' in params[param] and not is_config %}, default='{{ params[param]['default'] }}'{% endif %}), {% endfor %} ) # TODO - Check for validity - what parameters are actually required when creating a new {{ module_name }}? {{ module_name | upper() }}_REQUIRED_IF = [ {% if not is_config %} {% if module_type %} ['state', 'present', ['type']], ['type', '{{ params['type']['example'] }}', ['{{ params | dict2items | rejectattr('key', 'equalto', 'type') | selectattr('value.required', 'defined') | rejectattr('value.default', 'defined') | map(attribute='key') | join("', '") }}']], {% else %} ['state', 'present', ['{{ params | dict2items | selectattr('value.required', 'defined') | rejectattr('value.default', 'defined') | map(attribute='key') | join("', '") }}']], {% endif %} {% endif %} ] {% if params_xml_only %} # TODO - Check this for validity and matching module argument {{ module_name | upper() }}_MAP_PARAM = [ {% for param in params_xml_only %} ('ARG', '{{ param }}'), {% endfor %} ] {% endif %} # TODO - Review this for clues for input validation. Search for functions in the below require_once files in /etc and /usr/local/pfSense/include PHP_VALIDATION = r''' {{ php_requires }} {{ php_save }} ''' # TODO - Add validation and parsing methods for parameters that require it {{ module_name | upper() }}_ARG_ROUTE = dict( {% set param_items = ((params | dict2items | selectattr('value.parse', 'defined') | list) + (params | dict2items | selectattr('value.validate', 'defined')) | list) | unique %} {% if param_items %} {% for param_item in param_items %} {{ param_item.key }}=dict({% if param_item.value.parse is defined %}parse={{ param_item.value.parse }},{% endif %}{% if param_item.value.validate is defined %}validate={{ param_item.value.validate }},{% endif %}), {% endfor %} {% else %} # TODO - These are just examples authorizedkeys=dict(parse=p2o_ssh_pub_key), password=dict(validate=validate_password), {% endif %} ) {% if bool_values == 'inconsistent' %} {{ module_name | upper() }}_BOOL_VALUES = dict( {% for k, v in bool_values.items() %} {{ k }}=(None, "{{ v }}"), {% endfor %} ) {% endif %} # TODO - Check for validity - what are default values when creating a new {{ module_name }} {{ module_name | upper() }}_CREATE_DEFAULT = dict( {% for item in params | dict2items | selectattr('value.default', 'defined') %} {{ item.key }}='{{ item.value.default | default('VALUE') }}', {% endfor %} {% for param in params_xml_only %} {{ param }}='{{ params[param]['example'] | default('VALUE') }}', {% endfor %} ) {% if package != 'core' %} {{ module_name | upper() }}_PHP_COMMAND_SET = r''' require_once("{{ package | lower() }}.inc"); {{ package | lower() }}_sync_package(); ''' {% elif 'filter.inc' in php_requires %} {{ module_name | upper() }}_PHP_COMMAND_SET = r''' require_once("filter.inc"); if (filter_configure() == 0) { clear_subsystem_dirty('{{ php_subsystem }}'); } ''' {% endif %} class {{ pfsense_module_name }}({{ module_base }}): """ module managing pfsense {{ module_name }}{{ ' configuration' if is_config else 's' }} """ ############################## # unit tests # # Must be class method for unit test usage @staticmethod def get_argument_spec(): """ return argument spec """ return {{ module_name | upper() }}_ARGUMENT_SPEC def __init__(self, module, pfsense=None): super({{ pfsense_module_name }}, self).__init__(module, pfsense, {{ 'package=\'' ~ package ~ '\', ' if package != 'core' else ''}}root='{{ module_root }}', node='{{ module_node }}', key='{{ module_key }}'{{ ', update_php=' ~ module_name | upper() ~ '_PHP_COMMAND_SET' if 'filter.inc' in php_requires else '' }}, arg_route={{ module_name | upper() }}_ARG_ROUTE{% if bool_style != 'inconsistent' %}, bool_style="{{ bool_style }}"{% else %}, bool_values={{ module_name | upper() }}_BOOL_VALUES{% endif %}{% if params_xml_only %}, map_param={{ module_name | upper() }}_MAP_PARAM{% endif %}, create_default={{ module_name | upper() }}_CREATE_DEFAULT) {% if package != 'core' %} ############################## # run # # TODO - find the correct sync function def _update(self): """ make the target pfsense reload """ return self.pfsense.phpshell({{ module_name | upper() }}_PHP_COMMAND_SET) {% endif %} {% if is_config %} ############################## # Logging # @staticmethod def _get_obj_name(): """ return obj's name """ return "{{ module_name }}" {% endif %} def main(): module = AnsibleModule( argument_spec={{ module_name | upper() }}_ARGUMENT_SPEC, required_if={{ module_name | upper() }}_REQUIRED_IF, supports_check_mode=True) pfmodule = {{ pfsense_module_name }}(module) # Pass params for testing framework pfmodule.run(module.params) pfmodule.commit_changes() if __name__ == '__main__': main() ================================================ FILE: misc/pfsensible-generate-module ================================================ #!/usr/bin/python3 # Copyright: (c) 2024, Orion Poplawski # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # TODO: # - validation for addresses # - bool type determination and parameter list # - generate version_added # - detect packages from ansible.plugins.filter.core import dict_to_list_of_dict_key_value_elements from ansible.plugins.filter.mathstuff import unique import argparse import datetime import getpass import git import jinja2 import lxml.etree as ET import lxml.html import os from paramiko import SSHClient import re import requests from scp import SCPClient, SCPException import shutil import sys import tempfile from urllib.parse import urlparse gitconfig = git.GitConfigParser() author_name = gitconfig.get_value('user', 'name') author_email = gitconfig.get_value('user', 'email') package = 'core' module_base = 'PFSenseModuleBase' module_key = None module_node = None name_param = None params_xml_only = [] is_simple_package = False is_full_package = False args_imports = [] php_requires = '' php_save = '' php_subsystem = '' parser = argparse.ArgumentParser(description='Generate a pfsensible module.') parser.add_argument('--url', help='The URL to scrape') parser.add_argument('--urlfile', help='A local file copy of the URL to scrape') parser.add_argument('--user', default='admin', help='The user to connect to the web interface as (defaults to "admin")') parser.add_argument('--password', default='pfsense', help='The password of user') parser.add_argument('--password-prompt', action='store_true', help='Prompt for the password of user') parser.add_argument('--ssh-no-agent', action='store_true', help='Do not use ssh agent for connection') parser.add_argument('--ssh-user', default='root', help='The user to connect via ssh as (defaults to "root")') parser.add_argument('--ssh-password', default='pfsense', help='The password of the ssh user') parser.add_argument('--ssh-password-prompt', action='store_true', help='Prompt for the password of the ssh user') parser.add_argument('--author-name', default=author_name, help='The full name of the module author') parser.add_argument('--author-email', default=author_email, help='The email address of the module author') parser.add_argument('--author-handle', default='', help='The github handle of the module author') parser.add_argument('--module-name', help='The name of the module to generate - defaults to being based on the url, required with --urlfile') parser.add_argument('--is-config', action='store_true', help='This is a configuration module', ) parser.add_argument('--name-param', help='The name of the primary module parameter - defaults to the key, but often "name" is used instead of "descr"') parser.add_argument('--type-param', default='type', help='The name of the parameter for selecting different types of elements', ) parser.add_argument('--type-suffix', const=True, default=False, nargs='?', help='Suffix the module name with the item type', ) parser.add_argument('--root-elt', default='root', help='The xml config element to find items under') parser.add_argument('--item-min', default='item_min', help='The name of the minimally configured item to search for in config.xml (defaults to "item_min")') parser.add_argument('--item-full', default='item_full', help='The name of the fully configured item to search for in config.xml, will be used for exmaples in the documentation (defaults to "item_max")') parser.add_argument('--host', help='The name of the pfsense host to connect to - only used with --urlfile') parser.add_argument('--force', action=argparse.BooleanOptionalAction, help='Force overwriting the output file if it exists') parser.add_argument('--keep-tmpdir', action=argparse.BooleanOptionalAction, help='Keep the downloaded files in the temporary directory') parser.add_argument('--keep-params', action=argparse.BooleanOptionalAction, help='Keep parameters from the web interface not found in the XML') parser.add_argument('--verbose', '-v', action='count', default=0) args = parser.parse_args() # TODO - require a --module-root arg or search for it if args.is_config: module_root = 'system' # Temporary directory for files tmpdir = tempfile.TemporaryDirectory(prefix='pfgenmod-') if args.url is not None: uri = urlparse(args.url) # Login using just the base URL login_url = f'{uri.scheme}://{uri.netloc}/' # Collect host for later use to scp config.xml host = f'{uri.netloc}' # Collect phpfile to scp later phpfile = re.sub(r'^.*/([^/]+\.php).*$', r'\1', uri.path) # Construct a likely module name from the URL if args.module_name is None: # See if this pkg_edit URL first if re.match(r'/pkg', uri.path): module_name = re.sub(r'^xml=.*?([^/]+)\.xml.*$', r'\1', uri.query) package = re.sub(r'([^_]+).*', r'\1', module_name) is_simple_package = True phpfile = None elif (match := re.match(r'/([^/]+)/([^_]+_.+)\.php', uri.path)) is not None: module_name = re.sub(r'(?:_edit|manager)$', '', match.group(2)) package = match.group(1) is_full_package = True else: module_name = re.sub(r'^/(?:firewall_|services_|system_)?(.*?)(?:_edit|manager)?\.php$', r'\1', uri.path) module_name_singular = re.sub(r'ses$', 's', module_name) if module_name_singular != module_name: module_name = module_name_singular else: module_name = re.sub(r's$', '', module_name) else: module_name = args.module_name # We likely don't have a valid certificate requests.packages.urllib3.disable_warnings() # Start our session (need cookies for login) client = requests.Session() # Retrieve the CSRF token first 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) # Prompt for web password if requested if args.password_prompt: args.password = getpass.getpass("Enter your web user password: ") # 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) if (args.verbose >= 4): print(f'Login URL returned {r} {r.text}') html = lxml.html.fromstring(r.text) #

Username or Password incorrect

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: # Use a cached copy of the web page - get rid of this? Need to specify host and module name html = lxml.html.parse(args.urlfile) host = args.host module_name = args.module_name else: sys.exit('You must specify one of --url or --urlfile') # Prompt for ssh password if requested if args.ssh_password_prompt: args.ssh_password = getpass.getpass("Enter your ssh user password: ") # Collect the /cf/conf/config.xml file with SSHClient() as ssh: ssh.load_system_host_keys() ssh.connect(host, username=args.ssh_user, allow_agent=not args.ssh_no_agent, password=args.ssh_password) files_to_sftp = ['/cf/conf/config.xml'] if is_simple_package: files_to_sftp.append(f'/usr/local/pkg/{package}.inc') files_to_sftp.append(f'/usr/local/pkg/inc/{package}.inc') files_to_sftp.append(f'/usr/local/pkg/{package}.xml') elif is_full_package: files_to_sftp.append(f'/usr/local/www/{package}/{phpfile}') files_to_sftp.append(f'/usr/local/pkg/{package}/{package}.inc') files_to_sftp.append(f'/usr/local/pkg/{package}.xml') elif phpfile is not None: files_to_sftp.append(f'/usr/local/www/{phpfile}') with ssh.open_sftp() as sftp: for file in files_to_sftp: try: if (args.verbose >= 1): print(f'Copying {file}') sftp.get(file, f'{tmpdir.name}/{os.path.basename(file)}') except FileNotFoundError as e: pass # Save the scraped web page if asked to keep files if args.keep_tmpdir: f = open(f'{tmpdir.name}/{module_name}.html', 'w') f.write(r.text) f.close() shutil.copytree(tmpdir.name, f'/tmp/{module_name}', dirs_exist_ok=True) print(f'Keeping /tmp/{module_name}') # Parse the config.xml file root = ET.parse(f'{tmpdir.name}/config.xml').getroot() params_full = dict() if not args.is_config: # Search for any element with our target text, make sure we found only one xpath = f'.//*[.="{args.item_min}"]' if args.root_elt != 'root': root = root.find(f'.//{args.root_elt}') key_elts = root.findall(xpath) if len(key_elts) > 1: sys.exit(f'Found {len(key_elts)} items with path "{xpath}"') elif len(key_elts) == 0: sys.exit(f'Cannot find minimally configured item with path "{xpath}"') else: key_elt = key_elts[0] # This element should be the key for the items module_key = key_elt.tag if args.name_param: name_param = args.name_param else: name_param = module_key # The full node configuration element will be the parent node_elt = key_elt.find('..') module_node = node_elt.tag # The "root" for this type of element is above that root_elt = node_elt.find('..') module_root = root_elt.tag # Debug if args.verbose >= 2: print('item_min:\t' + ET.tostring(node_elt).decode()) # Let's use our node and key as a check full_elt = root.find(f'.//{module_node}[{module_key}="{args.item_full}"]') if full_elt is None: sys.exit(f'Cannot find fully configured item with path ".//{module_node}[{module_key}="{args.item_full}"]"') # Debug if args.verbose >= 2: print('item_full:\t' + ET.tostring(full_elt).decode()) # Collect the items for comparison with web elements and example values for elt in full_elt: if elt.tag == '': continue param = dict() addr_elt = elt.find('address') if addr_elt is not None: param['example'] = addr_elt.text param['address'] = True elif elt.text is not None: if elt.tag in params_full: # Copy example and possibly other values from previous copy param = params_full[elt.tag] # If we have already need one of these, then it is a list param['type'] = 'list' # TODO - can we determine the type? param['elements'] = 'str' param['example2'] = elt.text.strip() else: param['type'] = 'str' param['example'] = elt.text.strip() # else: # Likely a bool? params_full[elt.tag] = param # Try to determine the "proper" package name if package != 'core': package_elt = root.xpath(f"//package[translate(name/text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = '{package}']") if package_elt: package = package_elt[0].find('name').text else: print(f"WARNING: Could not find proper package name for {package}!") # Parse the php file if phpfile is not None: found_save = False with open(f'{tmpdir.name}/{phpfile}', 'r') as f: for line in f: if re.match(r'require_once', line): php_requires += line continue if re.search(r'if \(\$_POST\[\'save\']', line): found_save = True continue if found_save: if re.match(r'}', line): found_save = False else: php_save += re.sub(r'\t', ' ', re.sub(r'^\t', '', line)) subsystem_search = re.search(r'subsystem_dirty\(\'(.*)\'\)', line) if subsystem_search: php_subsystem = subsystem_search.group(1) # See if this is not a proper form URL if len(html.forms) != 1 or len(html.forms[0].inputs) <= 1: action_buttons_urls = html.find('.//nav[@class="action-buttons"]/a') if action_buttons_urls is not None: action_href = re.sub(r'\?.*', '', action_buttons_urls.attrib["href"]) sys.exit(f'ERROR: This does not appear to be a proper form URL, you probably want {uri.scheme}://{uri.netloc}/{action_href}') else: sys.exit(f'ERROR: This does not appear to be a proper form URL, do you need a ? parameter?') # TODO - For packages we could parse /usr/local/pkg/{package}.xml instead # Make sure a string has a trailing period def enforce_period(s): if len(s) > 0 and s[-1] != '.': s += '.' return s # Collected parameters from the web form params = dict() # Collect the input elements for input in html.forms[0].inputs: # Skip internal items if input.name == '__csrf_magic': continue param = dict(description='') if args.verbose >= 2: print(f'attrib={input.attrib}') if isinstance(input, lxml.html.InputElement): if input.tail is not None: input.tail = input.tail.strip() if args.verbose >= 2: print(f'input name={input.name} id={input.get("id")} type={input.type} value={input.value} ' f'text={input.text} title={input.get("title")} tail={input.tail}') if input.type == 'checkbox': param['type'] = 'bool' param['value'] = input.attrib['value'].strip() param['example'] = 'true' elif input.type == 'number': param['type'] = 'int' if input.value is not None: param['default'] = input.value elif input.type == 'password': param['type'] = 'str' param['password'] = True # TODO - set nolog elif input.type == 'radio': # Radio buttons are a series of individual elements if input.name in params: param = params[input.name] param['choices'].append(input.attrib['value']) if input.checked: param['default'] = input.attrib['value'] else: param['type'] = 'str' param['choices'] = [ input.attrib['value'] ] if input.checked: param['default'] = input.attrib['value'] elif input.type == 'text': param['type'] = 'str' if input.value is not None: param['default'] = input.value # TODO - handle placeholder as 'default' value - description? create_default? example? for attr in ['min', 'placeholder', 'step']: if attr in input.attrib: param[attr] = input.attrib[attr] # Text sometimes is after the input element inside the enclosing