From 587ca23374cba584392dcdd3f73284bd19e76edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Z=C3=A1le=C5=A1=C3=A1k?= Date: Wed, 30 Oct 2024 01:50:38 +0100 Subject: [PATCH] Initial commit --- addNewAPs.yml | 101 +++ ansible.cfg | 7 + group_vars/accessPoints.yml | 88 +++ group_vars/openwrt.yml | 4 + host_vars/ap_0c806307e88a.yml | 33 + host_vars/ap_107c61992bd8.yml | 62 ++ host_vars/ap_b04e26bbc7e3.yml | 49 ++ host_vars/ap_c47154391634.yml | 45 ++ host_vars/ap_c47154393f26.yml | 49 ++ host_vars/ap_c87f54de81d8.yml | 33 + include/createHostVars.yml | 25 + inventory.yml | 18 + playbook.yml | 37 + roles/batman/README.md | 143 ++++ roles/batman/defaults/main.yml | 64 ++ roles/batman/files/luci-proto-batman-adv.ipk | Bin 0 -> 3281 bytes roles/batman/handlers/main.yml | 8 + roles/batman/meta/main.yml | 12 + roles/batman/tasks/ath10k.yml | 64 ++ roles/batman/tasks/interface.yml | 56 ++ roles/batman/tasks/main.yml | 32 + roles/batman/tasks/prepare.yml | 48 ++ roles/dhcp/README.md | 108 +++ roles/dhcp/defaults/main.yml | 51 ++ roles/dhcp/handlers/main.yml | 7 + roles/dhcp/meta/main.yml | 12 + roles/dhcp/tasks/dhcp.yml | 45 ++ roles/dhcp/tasks/dnsmasq.yml | 34 + roles/dhcp/tasks/host.yml | 40 ++ roles/dhcp/tasks/main.yml | 20 + roles/dropbear/README.md | 53 ++ roles/dropbear/defaults/main.yml | 18 + roles/dropbear/files/authorized_keys | 0 roles/dropbear/handlers/main.yml | 6 + roles/dropbear/meta/main.yml | 12 + roles/dropbear/tasks/dropbear.yml | 24 + roles/dropbear/tasks/main.yml | 20 + roles/extroot/README.md | 47 ++ roles/extroot/defaults/main.yml | 19 + roles/extroot/files/90-extroot-restore | 19 + roles/extroot/handlers/main.yml | 13 + roles/extroot/meta/main.yml | 12 + roles/extroot/tasks/check.yml | 24 + roles/extroot/tasks/fstab.yml | 68 ++ roles/extroot/tasks/main.yml | 39 + roles/extroot/tasks/prepare.yml | 13 + roles/extroot/tasks/system.yml | 55 ++ roles/extroot/tasks/usb.yml | 10 + roles/firewall/README.md | 192 +++++ roles/firewall/defaults/main.yml | 109 +++ roles/firewall/handlers/main.yml | 6 + roles/firewall/meta/main.yml | 12 + roles/firewall/tasks/defaults.yml | 18 + roles/firewall/tasks/forwarding.yml | 41 ++ roles/firewall/tasks/ipset.yml | 43 ++ roles/firewall/tasks/main.yml | 40 ++ roles/firewall/tasks/nat.yml | 48 ++ roles/firewall/tasks/redirect.yml | 51 ++ roles/firewall/tasks/rule.yml | 50 ++ roles/firewall/tasks/zone.yml | 44 ++ roles/gekmihesg.openwrt/.ansible-lint | 4 + .../.github/workflows/galaxy.yml | 16 + roles/gekmihesg.openwrt/.gitignore | 3 + roles/gekmihesg.openwrt/.yamllint | 9 + roles/gekmihesg.openwrt/LICENSE | 674 ++++++++++++++++++ roles/gekmihesg.openwrt/README.md | 178 +++++ roles/gekmihesg.openwrt/defaults/main.yml | 17 + roles/gekmihesg.openwrt/files/wrapper.sh | 356 +++++++++ roles/gekmihesg.openwrt/handlers/main.yml | 30 + roles/gekmihesg.openwrt/library/nohup.py | 36 + .../library/openwrt_command.sh | 63 ++ .../gekmihesg.openwrt/library/openwrt_copy.sh | 83 +++ .../gekmihesg.openwrt/library/openwrt_file.sh | 172 +++++ .../library/openwrt_lineinfile.sh | 122 ++++ .../library/openwrt_nohup.sh | 12 + .../gekmihesg.openwrt/library/openwrt_opkg.sh | 70 ++ .../gekmihesg.openwrt/library/openwrt_ping.sh | 25 + .../library/openwrt_service.sh | 63 ++ .../library/openwrt_setup.sh | 67 ++ .../library/openwrt_slurp.sh | 21 + .../gekmihesg.openwrt/library/openwrt_stat.sh | 137 ++++ .../library/openwrt_sysctl.sh | 90 +++ .../gekmihesg.openwrt/library/openwrt_uci.sh | 384 ++++++++++ roles/gekmihesg.openwrt/library/uci.py | 190 +++++ .../meta/.galaxy_install_info | 2 + roles/gekmihesg.openwrt/meta/main.yml | 27 + .../molecule/default/collections.yml | 3 + .../molecule/default/converge.yml | 11 + .../molecule/default/molecule.yml | 45 ++ .../molecule/default/verify.yml | 49 ++ roles/gekmihesg.openwrt/requirements.txt | 4 + roles/gekmihesg.openwrt/tasks/main.yml | 20 + roles/gekmihesg.openwrt/tasks/package.yml | 12 + roles/gekmihesg.openwrt/tasks/packages.yml | 40 ++ .../vars_plugins/monkeypatch.py | 51 ++ roles/mesh11sd/README.md | 80 +++ roles/mesh11sd/defaults/main.yml | 41 ++ roles/mesh11sd/handlers/main.yml | 8 + roles/mesh11sd/meta/main.yml | 12 + roles/mesh11sd/tasks/ath10k.yml | 50 ++ roles/mesh11sd/tasks/configure.yml | 14 + roles/mesh11sd/tasks/main.yml | 31 + roles/mesh11sd/tasks/prepare.yml | 20 + roles/network/README.md | 123 ++++ roles/network/defaults/main.yml | 74 ++ roles/network/handlers/main.yml | 5 + roles/network/meta/main.yml | 12 + roles/network/tasks/device.yml | 42 ++ roles/network/tasks/globals.yml | 11 + roles/network/tasks/interface.yml | 50 ++ roles/network/tasks/main.yml | 43 ++ roles/network/tasks/route.yml | 44 ++ roles/network/tasks/rule.yml | 46 ++ roles/network/tasks/switch_dsa.yml | 40 ++ roles/network/tasks/switch_swconfig.yml | 40 ++ roles/pbr/README.md | 91 +++ roles/pbr/defaults/main.yml | 39 + roles/pbr/handlers/main.yml | 7 + roles/pbr/meta/main.yml | 12 + roles/pbr/tasks/main.yml | 19 + roles/pbr/tasks/policy.yml | 44 ++ roles/pbr/tasks/prepare.yml | 88 +++ roles/pbr/tasks/service.yml | 25 + roles/pbr/tasks/snapshot.yml | 32 + roles/system/README.md | 58 ++ roles/system/defaults/main.yml | 15 + roles/system/handlers/main.yml | 6 + roles/system/meta/main.yml | 12 + roles/system/tasks/main.yml | 17 + roles/system/tasks/system.yml | 22 + roles/wireguard/README.md | 95 +++ roles/wireguard/defaults/main.yml | 28 + roles/wireguard/handlers/main.yml | 6 + roles/wireguard/meta/main.yml | 12 + roles/wireguard/tasks/main.yml | 23 + roles/wireguard/tasks/peer.yml | 128 ++++ roles/wireguard/tasks/prepare.yml | 13 + roles/wireguard/tasks/server.yml | 111 +++ roles/wireless/README.md | 83 +++ roles/wireless/defaults/main.yml | 32 + roles/wireless/handlers/main.yml | 8 + roles/wireless/meta/main.yml | 12 + roles/wireless/tasks/device.yml | 31 + roles/wireless/tasks/interface.yml | 93 +++ roles/wireless/tasks/main.yml | 19 + setupAllAPs.yml | 34 + templates/host_vars.j2 | 33 + 147 files changed, 7521 insertions(+) create mode 100644 addNewAPs.yml create mode 100644 ansible.cfg create mode 100644 group_vars/accessPoints.yml create mode 100644 group_vars/openwrt.yml create mode 100644 host_vars/ap_0c806307e88a.yml create mode 100644 host_vars/ap_107c61992bd8.yml create mode 100644 host_vars/ap_b04e26bbc7e3.yml create mode 100644 host_vars/ap_c47154391634.yml create mode 100644 host_vars/ap_c47154393f26.yml create mode 100644 host_vars/ap_c87f54de81d8.yml create mode 100644 include/createHostVars.yml create mode 100644 inventory.yml create mode 100644 playbook.yml create mode 100644 roles/batman/README.md create mode 100644 roles/batman/defaults/main.yml create mode 100644 roles/batman/files/luci-proto-batman-adv.ipk create mode 100644 roles/batman/handlers/main.yml create mode 100644 roles/batman/meta/main.yml create mode 100644 roles/batman/tasks/ath10k.yml create mode 100644 roles/batman/tasks/interface.yml create mode 100644 roles/batman/tasks/main.yml create mode 100644 roles/batman/tasks/prepare.yml create mode 100644 roles/dhcp/README.md create mode 100644 roles/dhcp/defaults/main.yml create mode 100644 roles/dhcp/handlers/main.yml create mode 100644 roles/dhcp/meta/main.yml create mode 100644 roles/dhcp/tasks/dhcp.yml create mode 100644 roles/dhcp/tasks/dnsmasq.yml create mode 100644 roles/dhcp/tasks/host.yml create mode 100644 roles/dhcp/tasks/main.yml create mode 100644 roles/dropbear/README.md create mode 100644 roles/dropbear/defaults/main.yml create mode 100644 roles/dropbear/files/authorized_keys create mode 100644 roles/dropbear/handlers/main.yml create mode 100644 roles/dropbear/meta/main.yml create mode 100644 roles/dropbear/tasks/dropbear.yml create mode 100644 roles/dropbear/tasks/main.yml create mode 100644 roles/extroot/README.md create mode 100644 roles/extroot/defaults/main.yml create mode 100644 roles/extroot/files/90-extroot-restore create mode 100644 roles/extroot/handlers/main.yml create mode 100644 roles/extroot/meta/main.yml create mode 100644 roles/extroot/tasks/check.yml create mode 100644 roles/extroot/tasks/fstab.yml create mode 100644 roles/extroot/tasks/main.yml create mode 100644 roles/extroot/tasks/prepare.yml create mode 100644 roles/extroot/tasks/system.yml create mode 100644 roles/extroot/tasks/usb.yml create mode 100644 roles/firewall/README.md create mode 100644 roles/firewall/defaults/main.yml create mode 100644 roles/firewall/handlers/main.yml create mode 100644 roles/firewall/meta/main.yml create mode 100644 roles/firewall/tasks/defaults.yml create mode 100644 roles/firewall/tasks/forwarding.yml create mode 100644 roles/firewall/tasks/ipset.yml create mode 100644 roles/firewall/tasks/main.yml create mode 100644 roles/firewall/tasks/nat.yml create mode 100644 roles/firewall/tasks/redirect.yml create mode 100644 roles/firewall/tasks/rule.yml create mode 100644 roles/firewall/tasks/zone.yml create mode 100644 roles/gekmihesg.openwrt/.ansible-lint create mode 100644 roles/gekmihesg.openwrt/.github/workflows/galaxy.yml create mode 100644 roles/gekmihesg.openwrt/.gitignore create mode 100644 roles/gekmihesg.openwrt/.yamllint create mode 100644 roles/gekmihesg.openwrt/LICENSE create mode 100644 roles/gekmihesg.openwrt/README.md create mode 100644 roles/gekmihesg.openwrt/defaults/main.yml create mode 100644 roles/gekmihesg.openwrt/files/wrapper.sh create mode 100644 roles/gekmihesg.openwrt/handlers/main.yml create mode 100644 roles/gekmihesg.openwrt/library/nohup.py create mode 100644 roles/gekmihesg.openwrt/library/openwrt_command.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_copy.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_file.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_lineinfile.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_nohup.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_opkg.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_ping.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_service.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_setup.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_slurp.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_stat.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_sysctl.sh create mode 100644 roles/gekmihesg.openwrt/library/openwrt_uci.sh create mode 100644 roles/gekmihesg.openwrt/library/uci.py create mode 100644 roles/gekmihesg.openwrt/meta/.galaxy_install_info create mode 100644 roles/gekmihesg.openwrt/meta/main.yml create mode 100644 roles/gekmihesg.openwrt/molecule/default/collections.yml create mode 100644 roles/gekmihesg.openwrt/molecule/default/converge.yml create mode 100644 roles/gekmihesg.openwrt/molecule/default/molecule.yml create mode 100644 roles/gekmihesg.openwrt/molecule/default/verify.yml create mode 100644 roles/gekmihesg.openwrt/requirements.txt create mode 100644 roles/gekmihesg.openwrt/tasks/main.yml create mode 100644 roles/gekmihesg.openwrt/tasks/package.yml create mode 100644 roles/gekmihesg.openwrt/tasks/packages.yml create mode 100644 roles/gekmihesg.openwrt/vars_plugins/monkeypatch.py create mode 100644 roles/mesh11sd/README.md create mode 100644 roles/mesh11sd/defaults/main.yml create mode 100644 roles/mesh11sd/handlers/main.yml create mode 100644 roles/mesh11sd/meta/main.yml create mode 100644 roles/mesh11sd/tasks/ath10k.yml create mode 100644 roles/mesh11sd/tasks/configure.yml create mode 100644 roles/mesh11sd/tasks/main.yml create mode 100644 roles/mesh11sd/tasks/prepare.yml create mode 100644 roles/network/README.md create mode 100644 roles/network/defaults/main.yml create mode 100644 roles/network/handlers/main.yml create mode 100644 roles/network/meta/main.yml create mode 100644 roles/network/tasks/device.yml create mode 100644 roles/network/tasks/globals.yml create mode 100644 roles/network/tasks/interface.yml create mode 100644 roles/network/tasks/main.yml create mode 100644 roles/network/tasks/route.yml create mode 100644 roles/network/tasks/rule.yml create mode 100644 roles/network/tasks/switch_dsa.yml create mode 100644 roles/network/tasks/switch_swconfig.yml create mode 100644 roles/pbr/README.md create mode 100644 roles/pbr/defaults/main.yml create mode 100644 roles/pbr/handlers/main.yml create mode 100644 roles/pbr/meta/main.yml create mode 100644 roles/pbr/tasks/main.yml create mode 100644 roles/pbr/tasks/policy.yml create mode 100644 roles/pbr/tasks/prepare.yml create mode 100644 roles/pbr/tasks/service.yml create mode 100644 roles/pbr/tasks/snapshot.yml create mode 100644 roles/system/README.md create mode 100644 roles/system/defaults/main.yml create mode 100644 roles/system/handlers/main.yml create mode 100644 roles/system/meta/main.yml create mode 100644 roles/system/tasks/main.yml create mode 100644 roles/system/tasks/system.yml create mode 100644 roles/wireguard/README.md create mode 100644 roles/wireguard/defaults/main.yml create mode 100644 roles/wireguard/handlers/main.yml create mode 100644 roles/wireguard/meta/main.yml create mode 100644 roles/wireguard/tasks/main.yml create mode 100644 roles/wireguard/tasks/peer.yml create mode 100644 roles/wireguard/tasks/prepare.yml create mode 100644 roles/wireguard/tasks/server.yml create mode 100644 roles/wireless/README.md create mode 100644 roles/wireless/defaults/main.yml create mode 100644 roles/wireless/handlers/main.yml create mode 100644 roles/wireless/meta/main.yml create mode 100644 roles/wireless/tasks/device.yml create mode 100644 roles/wireless/tasks/interface.yml create mode 100644 roles/wireless/tasks/main.yml create mode 100644 setupAllAPs.yml create mode 100644 templates/host_vars.j2 diff --git a/addNewAPs.yml b/addNewAPs.yml new file mode 100644 index 0000000..80698bb --- /dev/null +++ b/addNewAPs.yml @@ -0,0 +1,101 @@ +- name: Detekce zařízení v síti + hosts: localhost + vars: + subnets: ["10.11.99", "10.22.99"] + gather_facts: no + tasks: + - name: Získání seznamu zařízení v rozsahu DHCP serveru + ansible.builtin.shell: | + for i in $(seq 100 254); do + ping -W .1 -c 1 {{ item }}.$i > /dev/null 2>&1 && echo {{ item }}.$i; + done || true + register: new_ips + loop: "{{ subnets }}" + - name: Přidat aktivní IP do dynamického inventáře + ansible.builtin.add_host: + name: "{{ item }}" + groups: found_devices + loop: "{{ new_ips.results | map(attribute='stdout_lines') | flatten }}" + - name: Přidat skupinu found_devices do metaskupiny openwrt + ansible.builtin.add_host: + groups: openwrt + name: "{{ item }}" + loop: "{{ groups['found_devices'] }}" + + - name: Získání seznamu volných adres mimo DHCP server + ansible.builtin.shell: | + for i in $(seq 1 99); do + ping -W .1 -c 1 {{ item }}.$i > /dev/null 2>&1 || echo {{ item }}.$i; + done + register: free_ips + loop: "{{ subnets }}" + - name: Vytvoření seznamu volných IP adres podle subnetu + set_fact: + free_subnet_ips: "{{ free_subnet_ips | default({}) | combine({item.item: item.stdout_lines}) }}" + loop: "{{ free_ips.results }}" + +- name: Získání hostů a generování hostnamů + hosts: found_devices + roles: + - gekmihesg.openwrt + gather_facts: yes + vars: + ansible_scp_extra_args: "-O" + openwrt_install_recommended_packages: false + tasks: + - name: Získání unikátního názvu zařízení podle MAC adresy + set_fact: + hostname: "ap_{{ ansible_facts.openwrt_devices[ansible_facts.openwrt_interfaces.mgmnt.l3_device].macaddr.replace(':', '') }}" + + - name: Uložení ip adresy hosta a hosnamu do seznamu hostů + set_fact: + host_info: { "ip": "{{ ansible_host }}", "hostname": "{{ hostname }}" } + + - name: Shromáždění informací o všech hostech a předání na localhost + delegate_to: localhost + delegate_facts: true + run_once: true + set_fact: + found_hosts_info: "{{ ansible_play_hosts | map('extract', hostvars, 'host_info') | list }}" + +- name: Přidání nového access poitu do správy + hosts: localhost + gather_facts: no + tasks: + - name: Přidělení statické IP adresy a vytvoření souboru v host_vars + include_tasks: include/createHostVars.yml + loop: "{{ found_hosts_info }}" + - meta: refresh_inventory + - name: Přidat nalezených hostů do dynamického inventáře + ansible.builtin.add_host: + name: '{{ item.hostname }}' + ansible_host: '{{ item.ip }}' + groups: new_devices + loop: "{{ found_hosts_info }}" + - name: Přidat skupinu new_devices do metaskupiny openwrt + ansible.builtin.add_host: + groups: openwrt + name: "{{ item }}" + loop: "{{ groups['new_devices'] }}" + +- name: Nastavení statické ip na mgmnt interface + hosts: new_devices + roles: + - gekmihesg.openwrt + - network + gather_facts: yes + vars: + ansible_scp_extra_args: "-O" + device_bridge_port: "{{ ansible_facts.openwrt_interfaces.mgmnt.device | regex_search('eth[0-9]+|wan') }}" + network_interfaces: + - id: "mgmnt" + proto: "static" + device: "{{ device_bridge_port }}.99" + ipaddr: "{{ device_ip_address }}/24" + gateway: "{{ device_ip_address | regex_replace('\\.[0-9]+$', '.1') }}" + dns: ["{{ device_ip_address | regex_replace('\\.[0-9]+$', '.1') }}"] + pre_tasks: + - name: update time + command: + cmd: ntpd -dnq -p pool.ntp.org + changed_when: false \ No newline at end of file diff --git a/ansible.cfg b/ansible.cfg new file mode 100644 index 0000000..b1dab48 --- /dev/null +++ b/ansible.cfg @@ -0,0 +1,7 @@ +[defaults] +# inventory = inventory.yml +roles_path = ../roles +remote_user = root +ansible_ssh_private_key_file = ~/.ssh/id_rsa +host_key_checking = false +display_skipped_hosts = false \ No newline at end of file diff --git a/group_vars/accessPoints.yml b/group_vars/accessPoints.yml new file mode 100644 index 0000000..344a539 --- /dev/null +++ b/group_vars/accessPoints.yml @@ -0,0 +1,88 @@ +device_bridge_port: "{{ ansible_facts.openwrt_interfaces.mgmnt.device | regex_search('eth[0-9]+|wan') }}" + +device_2g_radio: "{{ (ansible_facts.openwrt_wireless | dict2items | selectattr('value.config.band', 'equalto', '2g') | map(attribute='key') | first) | default('none') }}" +device_5g_radio: "{{ (ansible_facts.openwrt_wireless | dict2items | selectattr('value.config.band', 'equalto', '5g') | map(attribute='key') | first) | default('none') }}" + +network_devices: + - id: "@device[1]" + name: "br-vlan129" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.129"] + - id: "@device[2]" + name: "br-vlan137" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.137"] + - id: "@device[3]" + name: "br-vlan145" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.145"] + - id: "@device[4]" + name: "br-free" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.152"] + - id: "@device[5]" + name: "br-oldaurora" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.128"] + +network_interfaces: + - id: "hoste_wifi" + proto: "none" + device: "br-vlan129" + - id: "studenti_wifi" + proto: "none" + device: "br-vlan137" + - id: "ucitele_wifi" + proto: "none" + device: "br-vlan145" + - id: "free_wifi" + proto: "none" + device: "br-free" + - id: "oldaurora" + proto: "none" + device: "br-oldaurora" + +wireless_devices_default: + disabled: 0 + country: CZ + +wireless_interfaces: + - ssid: "aurora" + mode: "ap" + ifname: "aurora" + network: ["hoste_wifi"] + encryption: "wpa2+ccmp" + auth_server: "10.11.99.99" + auth_secret: "Jednokolka123" + dynamic_vlan: "2" + vlan_tagged_interface: "{{ ansible_facts.openwrt_interfaces.mgmnt.device | regex_search('eth[0-9]+|wan') }}" + vlan_bridge: "br-vlan" + vlan_naming: "1" + isolate: "1" + ieee80211r: "1" + ft_over_ds: "0" + device: "{{ ansible_facts.openwrt_wireless | list }}" + # - ssid: "aurora" + # state: "absent" + - ssid: "aurora - free" + mode: "ap" + ifname: "auroraFree" + network: ["free_wifi"] + encryption: "none" + isolate: "1" + device: "{{ ansible_facts.openwrt_wireless | list }}" + - ssid: "Aurora" + mode: "ap" + ifname: "oldAurora" + network: ["oldaurora"] + encryption: "psk2+ccmp" + key: "Kunjedlbaterku" + isolate: "0" + ieee80211r: "1" + ft_over_ds: "0" + device: "{{ ansible_facts.openwrt_wireless | list }}" diff --git a/group_vars/openwrt.yml b/group_vars/openwrt.yml new file mode 100644 index 0000000..d942718 --- /dev/null +++ b/group_vars/openwrt.yml @@ -0,0 +1,4 @@ +system: + hostname: "{{ device_hostname | default(inventory_hostname_short) }}" + timezone: "CET-1CEST,M3.5.0,M10.5.0/3" + zonename: "Europe/Prague" diff --git a/host_vars/ap_0c806307e88a.yml b/host_vars/ap_0c806307e88a.yml new file mode 100644 index 0000000..8e5f29a --- /dev/null +++ b/host_vars/ap_0c806307e88a.yml @@ -0,0 +1,33 @@ +device_ip_address: "10.11.99.4" +device_hostname: "ap-outdoor" + +# network_switch_vlans: +# - id: "@switch_vlan[1]" +# vlan: "128" +# ports: "0t 1t 2 3t 4 5" +# description: "hoste" +# - id: "@switch_vlan[2]" +# vlan: "136" +# ports: "0t 1t" +# description: "studenti" +# - id: "@switch_vlan[3]" +# vlan: "144" +# ports: "0t 1t 3t" +# description: "ucitele" +# - id: "@switch_vlan[4]" +# vlan: "152" +# ports: "0t 1t" +# description: "free" + +# wireless_devices: +# - id: "" +# channel: "6" +# txpower: "5" + +# wireless_interfaces_override: + # - ssid: "aurora" + # device: "" + # - ssid: "aurora - free" + # device: "" + # - ssid: "Aurora" + # device: "" \ No newline at end of file diff --git a/host_vars/ap_107c61992bd8.yml b/host_vars/ap_107c61992bd8.yml new file mode 100644 index 0000000..3b6bd05 --- /dev/null +++ b/host_vars/ap_107c61992bd8.yml @@ -0,0 +1,62 @@ +device_ip_address: "10.11.99.2" +device_hostname: "" + +network_dsa_switch_vlans: + - id: "@switch_vlan[1]" + vlan: "128" + ports: "0t 6t 1 2 3 4" + description: "hoste" + - id: "@switch_vlan[2]" + vlan: "129" + ports: "0t 6t" + description: "hoste_wifi" + - id: "@switch_vlan[3]" + vlan: "136" + ports: "0t 6t" + description: "studenti_lan" + - id: "@switch_vlan[4]" + vlan: "137" + ports: "0t 6t" + description: "studenti_wifi" + - id: "@switch_vlan[5]" + vlan: "144" + ports: "0t 6t" + description: "ucitele_lan" + - id: "@switch_vlan[6]" + vlan: "145" + ports: "0t 6t" + description: "ucitele_wifi" + - id: "@switch_vlan[7]" + vlan: "152" + ports: "0t 6t" + description: "free_wifi" +# network_switch_vlans: +# - id: "@switch_vlan[1]" +# vlan: "128" +# ports: "0t 1t 2 3t 4 5" +# description: "hoste" +# - id: "@switch_vlan[2]" +# vlan: "136" +# ports: "0t 1t" +# description: "studenti" +# - id: "@switch_vlan[3]" +# vlan: "144" +# ports: "0t 1t 3t" +# description: "ucitele" +# - id: "@switch_vlan[4]" +# vlan: "152" +# ports: "0t 1t" +# description: "free" + +# wireless_devices: +# - id: "" +# channel: "6" +# txpower: "5" + +# wireless_interfaces_override: + # - ssid: "aurora" + # device: "" + # - ssid: "aurora - free" + # device: "" + # - ssid: "Aurora" + # device: "" \ No newline at end of file diff --git a/host_vars/ap_b04e26bbc7e3.yml b/host_vars/ap_b04e26bbc7e3.yml new file mode 100644 index 0000000..91a46f3 --- /dev/null +++ b/host_vars/ap_b04e26bbc7e3.yml @@ -0,0 +1,49 @@ +device_ip_address: "10.11.99.3" +device_hostname: "ap-predsin" + +network_swconfig_switch_vlans: + - id: "@switch_vlan[1]" + vlan: "128" + ports: "0t 1t 2" + description: "hoste_lan" + - id: "@switch_vlan[2]" + vlan: "129" + ports: "0t 1t" + description: "hoste_wifi" + - id: "@switch_vlan[3]" + vlan: "136" + ports: "0t 1t" + description: "studenti_lan" + - id: "@switch_vlan[4]" + vlan: "137" + ports: "0t 1t" + description: "studenti_wifi" + - id: "@switch_vlan[5]" + vlan: "144" + ports: "0t 1t" + description: "ucitele_lan" + - id: "@switch_vlan[6]" + vlan: "145" + ports: "0t 1t" + description: "ucitele_wifi" + - id: "@switch_vlan[7]" + vlan: "152" + ports: "0t 1t" + description: "free_wifi" + - id: "@switch_vlan[8]" + vlan: "199" + ports: "0t 1t" + description: "oldAurora" + +wireless_devices: + - id: "{{ device_2g_radio }}" + channel: "6" + txpower: "5" + +wireless_interfaces_override: + # - ssid: "aurora" + # device: "{{ [device_2g_radio] }}" + # - ssid: "aurora - free" + # device: "{{ [device_2g_radio] }}" + # - ssid: "Aurora" + # device: "{{ [device_2g_radio] }}" \ No newline at end of file diff --git a/host_vars/ap_c47154391634.yml b/host_vars/ap_c47154391634.yml new file mode 100644 index 0000000..a92084c --- /dev/null +++ b/host_vars/ap_c47154391634.yml @@ -0,0 +1,45 @@ +device_ip_address: "10.11.99.6" +device_hostname: "ap-vila-dole" + +network_swconfig_switch_vlans: + - id: "@switch_vlan[1]" + vlan: "128" + ports: "0t 6t 1 2 3 4" + description: "hoste" + - id: "@switch_vlan[2]" + vlan: "129" + ports: "0t 6t" + description: "hoste_wifi" + - id: "@switch_vlan[3]" + vlan: "136" + ports: "0t 6t" + description: "studenti_lan" + - id: "@switch_vlan[4]" + vlan: "137" + ports: "0t 6t" + description: "studenti_wifi" + - id: "@switch_vlan[5]" + vlan: "144" + ports: "0t 6t" + description: "ucitele_lan" + - id: "@switch_vlan[6]" + vlan: "145" + ports: "0t 6t" + description: "ucitele_wifi" + - id: "@switch_vlan[7]" + vlan: "152" + ports: "0t 6t" + description: "free_wifi" + +wireless_devices: + - id: "{{ device_2g_radio }}" + channel: "13" + txpower: "4" + +# wireless_interfaces_override: + # - ssid: "aurora" + # device: "{{ [device_2g_radio] }}" + # - ssid: "aurora - free" + # device: "{{ [device_2g_radio] }}" + # - ssid: "Aurora" + # device: "{{ [device_2g_radio] }}" \ No newline at end of file diff --git a/host_vars/ap_c47154393f26.yml b/host_vars/ap_c47154393f26.yml new file mode 100644 index 0000000..04a41eb --- /dev/null +++ b/host_vars/ap_c47154393f26.yml @@ -0,0 +1,49 @@ +device_ip_address: "10.11.99.5" +device_hostname: "ap-vila-nahore" + +network_swconfig_switch_vlans: + - id: "@switch_vlan[0]" + vlan: "99" + ports: "0t 6t 2t" + description: "mgmnt" + - id: "@switch_vlan[1]" + vlan: "128" + ports: "0t 6t 1 2t 3 4" + description: "hoste" + - id: "@switch_vlan[2]" + vlan: "129" + ports: "0t 6t 2t" + description: "hoste_wifi" + - id: "@switch_vlan[3]" + vlan: "136" + ports: "0t 6t 2t" + description: "studenti_lan" + - id: "@switch_vlan[4]" + vlan: "137" + ports: "0t 6t 2t" + description: "studenti_wifi" + - id: "@switch_vlan[5]" + vlan: "144" + ports: "0t 6t 2t" + description: "ucitele_lan" + - id: "@switch_vlan[6]" + vlan: "145" + ports: "0t 6t 2t" + description: "ucitele_wifi" + - id: "@switch_vlan[7]" + vlan: "152" + ports: "0t 6t 2t" + description: "free_wifi" + +wireless_devices: + - id: "{{ device_2g_radio }}" + channel: "8" + txpower: "4" + +# wireless_interfaces_override: + # - ssid: "aurora" + # device: "{{ [device_2g_radio] }}" + # - ssid: "aurora - free" + # device: "{{ [device_2g_radio] }}" + # - ssid: "Aurora" + # device: "{{ [device_2g_radio] }}" \ No newline at end of file diff --git a/host_vars/ap_c87f54de81d8.yml b/host_vars/ap_c87f54de81d8.yml new file mode 100644 index 0000000..98f388d --- /dev/null +++ b/host_vars/ap_c87f54de81d8.yml @@ -0,0 +1,33 @@ +device_ip_address: "10.22.99.2" +device_hostname: "ap-frystak" + +wireless_devices: + - id: "{{ device_2g_radio }}" + channel: "1" + +network_devices: + - id: "@device[0]" + name: "br-vlan128" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}"] + - id: "@device[1]" + name: "br-vlan136" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.136"] + - id: "@device[2]" + name: "br-vlan144" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.144"] + - id: "@device[3]" + name: "br-free" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}.152"] + - id: "@device[4]" + name: "br-oldaurora" + state: "present" + type: "bridge" + ports: ["{{ device_bridge_port }}"] \ No newline at end of file diff --git a/include/createHostVars.yml b/include/createHostVars.yml new file mode 100644 index 0000000..801d9e8 --- /dev/null +++ b/include/createHostVars.yml @@ -0,0 +1,25 @@ +- name: Zjistit subnet + set_fact: + ip_subnet: "{{ item.ip | regex_search('^(\\d+\\.\\d+\\.\\d+)') }}" +- name: Přidělit IP adresu + set_fact: + ip_address: "{{ free_subnet_ips[ip_subnet] | first }}" + +- name: existuje config v host_vars? + stat: + path: host_vars/{{item.hostname}}.yml + register: st +- name: Vytvoření souboru v host_vars + template: + src: templates/host_vars.j2 + dest: host_vars/{{item.hostname}}.yml + when: not st.stat.exists +- name: Aktualizovat seznam volných IP adres po přidělení + set_fact: + free_subnet_ips: "{{ free_subnet_ips | combine({ip_subnet: free_subnet_ips[ip_subnet][1:]}) }}" +- name: Přidat blok s novým přístupovým bodem na konec souboru + lineinfile: + path: inventory.yml # Cesta k souboru + line: |2 + {{ item.hostname }}: + ansible_host: "{{ ip_address }}" \ No newline at end of file diff --git a/inventory.yml b/inventory.yml new file mode 100644 index 0000000..3e2e2b5 --- /dev/null +++ b/inventory.yml @@ -0,0 +1,18 @@ +openwrt: + children: + accessPoints: + +accessPoints: + vars: + ansible_scp_extra_args: "-O" + hosts: + # ap_c47154394838: + # ansible_host: "10.11.99.2" + ap_b04e26bbc7e3: + ansible_host: "10.11.99.3" + ap_0c806307e88a: + ansible_host: "10.11.99.4" + ap_c47154393f26: + ansible_host: "10.11.99.5" + ap_c47154391634: + ansible_host: "10.11.99.6" \ No newline at end of file diff --git a/playbook.yml b/playbook.yml new file mode 100644 index 0000000..8681bef --- /dev/null +++ b/playbook.yml @@ -0,0 +1,37 @@ +- hosts: openwrt + roles: + - system + - gekmihesg.openwrt + gather_facts: yes + tasks: + - name: get interfaces + uci: + command: get + key: network.mgmnt.device + register: br_interface + - name: print interface + debug: + msg: "{{ br_interface.result | regex_search('eth[0-9]+|wan') }}" + + - name: Show all ansible_facts + debug: + msg: "{{ ansible_facts }}" + - name: Get list of radios + debug: + msg: "Get: {{ item }}" + loop: "{{ wireless_interfaces.0.device }}" + register: radios + + # tasks: + # - name: Override wifi devices + # debug: + # msg: "{{ item | combine({'device': new_device}) }}" + # vars: + # new_device: "{{ (wireless_interfaces_override | default() | selectattr('ssid', 'equalto', item.ssid) | map(attribute='device') | list | first) | default(item.device) }}" + # loop: "{{ wireless_interfaces }}" + # - name: List children + # debug: + # msg: "Family={{ item.0.ssid }} Child={{ item.1 }}" + # with_subelements: + # - "{{ wireless_interfaces }}" + # - device \ No newline at end of file diff --git a/roles/batman/README.md b/roles/batman/README.md new file mode 100644 index 0000000..d00323a --- /dev/null +++ b/roles/batman/README.md @@ -0,0 +1,143 @@ +# `flyoverhead.openwrt.batman` + +OpenWRT `B.A.T.M.A.N.` configuration +- create and configure B.A.T.M.A.N. network + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `batman_enabled` | Enable B.A.T.M.A.N. configuration | `required` | `boolean` | `false` | +| `ath10k_ct_fix` | Enable [ath10k-ct drivers fix](https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#wireless_hardware_support) | `optional` | `boolean` | `false` | +| `non_mesh_pkgs` | List of non-mesh wpad packages installed by default | `required` | `list` | `["wpad-mini", "wpad-basic", "wpad-basic-wolfssl", "wpad-basic-openssl", "wpad-basic-mbedtls"]` | +| `batman_pkgs` | List of B.A.T.M.A.N. packages to be installed | `required` | `list` | `["wpad-mesh-wolfssl", "kmod-batman-adv", "batctl-default"]` | +| `batman_network_interfaces` | List of [B.A.T.M.A.N. network interfaces](https://openwrt.org/docs/guide-user/network/wifi/mesh/batman#batman-adv_options_for_bat0_the_main_mesh_interface) to be configured | | `list of dictionaries` | | +| | B.A.T.M.A.N. control interface configuration | | | | +|  `id` | Unique B.A.T.M.A.N. control interface ID | `mandatory` | `string` | `bat0` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `proto` | Interface protocol | `mandatory` | `string` | `batadv` | +|  `aggregated_ogms` | Enable originator messages used to determine the qualities needed to direct neighbors and spreading this message throughout the whole mesh | `required` | `boolean` | `1` | +|  `routing_algo` | Routing algorithm (`BATMAN_IV` or `BATMAN_V`) | `mandatory` | `string` | `BATMAN_IV` | +|  `bonding` | Distribute frames through interfaces (similar in quality and speed) using Round Robin to increase throughput | `optional` | `boolean` | `0` | +|  `fragmentation` | Enable packet fragmentation | `required` | `boolean` | `1` | +|  `gw_mode` | Gateway mode (`off`, `client` or `server`) | `required` | `string` | `off` | +|  `gw_bandwidth` | Gateway bandwidth (for `client` nodes to know about the gateway's quality stated by `download/upload`, and can be suffixed with `mbit` or `kbit`) | `optional` | `string` | `100mbit/20mbit` | +|  `gw_sel_class` | Criteria by which client shoul select a gateway indicated by TQ (`1`, `2`, `3` or `XX`) | `optional` | `integer` | `20` | +|  `log_level` | Standard warning/error messages are sent to the kernel log (`0-255` 8 bit Bitmask) | `optional` | `integer` | `0` | +|  `orig_interval` | Interval (in milliseconds) in which batman-adv floods the network with its protocol information | `optional` | `integer` | `1000` | +|  `bridge_loop_avoidance` | Enable avoidance of broadcast loops (for bridged LAN setups) | `required` | `boolean` | `1` | +|  `distributed_arp_table` | Enable mesh-wide ARP table cache | `required` | `boolean` | `1` | +|  `multicast_mode` | Enable group aware multicast forwarding infrastructure, aiming to reduce unnecessary packet transmissions | `required` | `boolean` | `1` | +|  `multicast_fanout` | Batman-adv detects potential multicast listeners who are interested in traffic to a given multicast destination address (requires `multicast_mode`) | `optional` | `integer` | `16` | +|  `network_coding` | Enable to combine two packets into a single transmission | `optional` | `boolean` | `0` | +|  `hop_penalty` | Modify batman_adv's preference for multihop routes vs short routes | `optional` | `integer` | `30` | +|  `ap_isolation` | Enable standard WiFi APs support AP Isolation to prevent clients communicating with each other | `optional` | `boolean` | `0` | +|  `isolation_mark` | Firewall mark which allows to classify clients as isolated via firewall rules (defined as a `value/mask`) | `optional` | `string` | `0x00000000/0x00000000` | +| | B.A.T.M.A.N. link interface configuration | | | | +|  `name` | Unique B.A.T.M.A.N. link interface name | `mandatory` | `string` | `batmesh` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `proto` | Interface protocol | `mandatory` | `string` | `batadv_hardif` | +|  `master` | B.A.T.M.A.N. control interface name | `mandatory` | `string` | `bat0` | +|  `mtu` | MTU value | `optional` | `integer` | `2304` | +|  `delegate` | Enable prefix delegation | `optional` | `boolean` | `0` | +| `batman_wireless_interfaces` | List of [B.A.T.M.A.N. network interfaces](https://openwrt.org/docs/guide-user/network/wifi/mesh/batman#s_encrypted_authenticated_mesh) | | `list of dictionaries` | | +|  `id` | Unique wireless interface ID | `mandatory` | `string` | `mesh0` | +|  `name` | Unique wireless interface name | `mandatory` | `string` | `mesh0` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `device` | Radio device associated with the interface | `mandatory` | `string` | `radio0` | +|  `network` | B.A.T.M.A.N. network associated with the interface (match `B.A.T.M.A.N. link interface name`) | `required` | `list` | `batmesh` | +|  `mode` | Wireless interface operation mode | `required` | `string` | `mesh` | +|  `disabled` | Disable wireless network | `required` | `boolean` | `0` | +|  `mesh_id` | ID of the mesh network to join wireless interface to | `optional` | `string` | `example_mesh_id` | +|  `mesh_fwding` | Switch off 802.11s forwarding/routing cause it's handled by batman-adv at each node | `required` | `boolean` | `0` | +|  `encryption` | Wireless encryption method | `required` | `string` | `psk2+ccmp` | +|  `key` | Passphrase for pre-shared key | `required` | `string` | `password` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.batman +``` + +## Example Vars + +### Server Node + +```yaml +batman_enabled: true +ath10k_ct_fix: true +batman_network_interfaces: + - id: "bat0" + state: "present" + proto: "batadv" + routing_algo: "BATMAN_IV" + gw_mode: "server" + gw_bandwidth: "100mbit/20mbit" + - id: "batmesh0" + state: "present" + proto: "batadv_hardif" + master: "bat0" + mtu: "2304" +batman_wireless_interfaces: + - id: "mesh0" + name: "mesh0" + state: "present" + device: "radio0" + network: ["batmesh0"] + mode: "mesh" + mesh_id: "openwrt_mesh" + mesh_fwding: "0" + encryption: "psk2+ccmp" + key: "passphrase" +``` + +### Client Node + +```yaml +batman_enabled: true +ath10k_ct_fix: true +batman_network_interfaces: + - id: "bat0" + state: "present" + proto: "batadv" + routing_algo: "BATMAN_IV" + gw_mode: "client" + gw_sel_class: "20" + - id: "batmesh0" + state: "present" + proto: "batadv_hardif" + master: "bat0" + mtu: "2304" +batman_wireless_interfaces: + - id: "mesh0" + name: "mesh0" + state: "present" + device: "radio0" + network: ["batmesh0"] + mode: "mesh" + mesh_id: "openwrt_mesh" + mesh_fwding: "0" + encryption: "psk2+ccmp" + key: "passphrase" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/network/wifi/mesh/batman +- https://downloads.open-mesh.org/batman/manpages/batctl.8.html diff --git a/roles/batman/defaults/main.yml b/roles/batman/defaults/main.yml new file mode 100644 index 0000000..41b9bc9 --- /dev/null +++ b/roles/batman/defaults/main.yml @@ -0,0 +1,64 @@ +--- +# Deafult B.A.T.M.A.N. status +batman_enabled: false + +# Enable ath10k-ct drivers fix +# https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#wireless_hardware_support +ath10k_ct_fix: false + +# Non-mesh wpad packages +non_mesh_pkgs: + [ + "wpad-mini", + "wpad-basic", + "wpad-basic-wolfssl", + "wpad-basic-openssl", + "wpad-basic-mbedtls", + ] + +# B.A.T.M.A.N. packages +batman_pkgs: ["wpad-mesh-wolfssl", "kmod-batman-adv", "batctl-default"] + +# B.A.T.M.A.N. network interfaces +batman_network_interfaces: + - id: "" + state: "" + proto: "" + aggregated_ogms: "" + routing_algo: "" + bonding: "" + fragmentation: "" + gw_mode: "" + gw_bandwidth: "" + gw_sel_class: "" + log_level: "" + orig_interval: "" + bridge_loop_avoidance: "" + distributed_arp_table: "" + multicast_mode: "" + multicast_fanout: "" + network_coding: "" + hop_penalty: "" + ap_isolation: "" + isolation_mark: "" + delegate: "" + - id: "" + state: "" + proto: "" + master: "" + mtu: "" + delegate: "" + +# B.A.T.M.A.N. wireless interfaces +batman_wireless_interfaces: + - id: "" + name: "" + state: "" + device: "" + network: [] + mode: "" + disabled: "" + mesh_id: "" + mesh_fwding: "" + encryption: "" + key: "" diff --git a/roles/batman/files/luci-proto-batman-adv.ipk b/roles/batman/files/luci-proto-batman-adv.ipk new file mode 100644 index 0000000000000000000000000000000000000000..50b637ea8d843c777860e96a6452d3550602cdfb GIT binary patch literal 3281 zcmV;?3@-B@iwFP!000001MSyWG#uK$2XI03-a|wey)#OV5+s7?EfGXFdKttZS`s08 z62k<8gdBDBHu{hW(MB)P!zdA*(PsYV-urUzdHLU$bIx7s&S&kletYeg{d?HIwZ2|8x%o{~Rf47e|nz)E_e-5^dTl1jR*rVG4E%Nr^AAEP>1t&BG z^$HA#C9dgP-Nc_hC+8LN6mpoXZ_H-FbQvrM`b#Y~6Wvk=@AU#n!4ZKgxL99&@Z#z! z5;=y(9_{UOtbSfaFO!5Etm%gD~l7FCt3<{)~#yFb&{ zft8Fm#pXgiEU6odtGf}9B@g)Pnc903VJV8$R+$E_m)(P^n;>87)5nO)ihX_`h@r62 z+_53t*sbh^zRoer^GH)BWC}$w-Yte9x_(j(#(j1eUa>P-czR9}>Gmpf7;MTnaEG(g z0D^t0u>qA}Ii3=DB2<3xv7AYzk>7C^c1ug-w}6OCy>H2BfC#ek)*oS#WTv%I{fCB# zTB!513Yi!X^HO6EEXCm$PekgQtw6J6lrBU5RA8 ziuS$wf{Im0z4YcK$`2JBcSYH&EXV$9GcPCC@;B0g$lyHuhU{62_akQ(~~*=(0iBdzwkaag=j1Q`uXPQYGQe z5g4M9+WQ1U@!^5Oy@J3keyVRI_s2bE z3)cFcGi50ea_sjKuQMT@?czkW@!q_BM6N))6~Dxe;%dPh=SkEvv$^4z&!ZFDHO{-vep3kH>iVCK@k=4i3SeOJMi z^34k;i9)Yb;EC8N@KyI+5Kk>Mg9_eXQsgsavgqqJeMWEnb9T@>e|0BKdGoEU7dQLV zm(FK&Hsl7B(<4s?oQcV@pGpPVXaj?nsxTyj$~nA>qfQ{C&=zaH^|+q+%U8(^nM{|~ zQfm$SYsJhK%@dVvC)-V~@O#qrNqpu_s3f;+832lx)3ijZe@=aSY0KGw|GjRrZ zh&dv)_Qdj->AT^!rPrRC8}M9RH0jq51`V0SVieZ zHhDgWUx-OK4HgDdFW(&%(ww#_E=#eFO8ni9sif1AKcsmA0(4qc^K8(hfU4XWrZX?PsDwyvi8}y#i1!$fz?=M+d_THc6Le;SEGk*)XBjn%+*22{XP^vKN-!8R8V5->b?nahGNj&{A34y_ zNbAo%7Qy(gY}IgY=}d-7=_O1577M*WJQ(d-C0nZgQ+OI`>Ggp95miBIw>c`hW}8ZB z==($F#!qLTR>te5#%$no?U;wCt7M+piUl8oU#H~;F{v_BI7Qvxb<9A3JSSnhZ%w{T z1#ZhyfcAj>DK3DXNhxg*;4_nu5$L&BD2fr;W7W9eiQLUe{IH*>v77|p84@V`GZY5!K*D^rtd=5W@*>3ra<237O^9)V*-X^ z;?DC!zhWxe_5p<_F}p%Pxgfy?NLBjG@U|z$B&AHV z*q6&Sa_nI0#QK2ueXO`@6DyxQ9 z3ZysBxs^qhIjp^r(4tImZJRdS^YVaxaD-PN(7YMBU&#W&b>>F*+z*CrFXEd`vU6d5 z@$?rCZRtQiuao;{ha;9%eV?v|$;$by;I|vuaU8UwyoIo-WUSYVFLUq(Y7AR{!%3t% zkqMfMM5+oQ{aUlz0gR1bxlSz-QMliS29D!r@$TA7c1O8 z@BFYSi@I>%mAmj`7(UNRVB1x-T54s zUymzZdSklcJ*Z=9Ge#PU|Hc98m7`cpOM)@Z*ci;WsB>1DEE^|IbgZ{{E231d$RD(B z;kA-*9gM#&q7d!si*6oU6tTSjW7SaNh}7f(VnibU>~kj|ARr(hARr(hARr(hARr(h P_ + batman_luci_package_status.stdout is undefined or + batman_luci_package_status.stdout | length == 0 + block: + # Copy local package file + - name: Copy luci-proto-batman-adv package file + ansible.builtin.copy: + src: "luci-proto-batman-adv.ipk" + dest: "/tmp/luci-proto-batman-adv.ipk" + owner: "root" + group: "root" + mode: "0755" + + # Install B.A.T.M.A.N. LuCI package + - name: Install luci-proto-batman-adv package file + ansible.builtin.command: + cmd: "opkg install /tmp/luci-proto-batman-adv.ipk" diff --git a/roles/dhcp/README.md b/roles/dhcp/README.md new file mode 100644 index 0000000..349896f --- /dev/null +++ b/roles/dhcp/README.md @@ -0,0 +1,108 @@ +# `flyoverhead.openwrt.dhcp` + +OpenWRT `dhcp` configuration +- configure dnsmasq settings +- create/delete/configure dhcp pools +- create/delete/configure static leases +- create/delete/configure ipsets + +## Role Variables + +| Variable | Descritpion | Status | Type | Example | +| :--- | :--- | :--- | :--- | :--- | +| `dhcp_common` | DHCP and DNS [common options](https://openwrt.org/docs/guide-user/base-system/dhcp#common_options) | | `dictionary` | | +|  `authoritative` | Force dnsmasq into authoritative mode (used if this is the only server on the network) | `required` | `boolean` | `1` | +|  `boguspriv` | Reject reverse lookups to private IP ranges where no corresponding entry exists in `/etc/hosts` | `optional` | `boolean` | `1` | +|  `cachesize` | Size of dnsmasq query cache | `optional` | `integer` | `150` | +|  `domain` | Local domain suffix appended to DHCP names and hosts file entries | `optional` | `string` | `lan` | +|  `domainneeded` | Never forward queries for plain names, without dots or domain parts, to upstream nameservers | `optional` | `boolean` | `1` | +|  `dnssec` | Validate DNS replies and cache DNSSEC data | `optional` | `boolean` | `0` | +|  `dnsseccheckunsigned` | Check the zones of unsigned replies to ensure that unsigned replies are allowed in those zones | `optional` | `boolean` | `0` | +|  `expandhosts` | Add the local domain part to names found in /etc/hosts | `optional` | `boolean` | `1` | +|  `filterwin2k` | Do not forward requests that cannot be answered by public name servers | `optional` | `boolean` | `0` | +|  `fqdn` | Do not resolve unqualifed local hostnames (needs `domain` to be set) | `optional` | `boolean` | `0` | +|  `leasefile` | Path to file to store DHCP leases in | `optional` | `string` | `/tmp/dhcp.leases` | +|  `local` | Never forward matching domains and subdomains, resolve from DHCP or hosts files only. | `optional` | `string` | `/lan/` | +|  `localise_queries` | Return answers to DNS queries matching the subnet from which the query was received if multiple IPs are available | `optional` | `boolean` | `1` | +|  `localservice` | Accept DNS queries only from hosts whose address is on a local subnet | `optional` | `boolean` | `0` | +|  `nonegcache` | Do not cache negative replies, e.g. for non-existent domains | `optional` | `boolean` | `1` | +|  `nonwildcard` | Bind dynamically to interfaces rather than wildcard address | `optional` | `boolean` | `1` | +|  `readethers` | Read static lease entries from /etc/ethers | `optional` | `boolean` | `1` | +|  `rebind_protection` | Enables DNS rebind attack protection by discarding upstream RFC1918 responses | `optional` | `boolean` | `1` | +|  `rebind_localhost` | Allows upstream 127.0.0.0/8 responses, required for DNS based blacklist services (needs `rebind_protection` to be enabled) | `optional` | `boolean` | `1` | +|  `rebind_domain` | List of domains to allow RFC1918 responses for (needs `rebind_protection` to be enabled) | `optional` | `list` | `["/example.com/", "/maydomain.com/"]` | +|  `resolvfile` | Path to file with upstream resolvers | `optional` | `string` | `"/tmp/resolv.conf.d/resolv.conf.auto` | +|  `server` | List of DNS upstream servers to forward requests to | `optional` | `list` | `["192.168.1.1", "192.168.1.2"]` | +|  `serverlist` | Path to file with DNS upstream servers list content | `optional` | `string` | `/etc/dnsmasq.servers` | +|  `address` | List of IP addresses for queried domains | `optional` | `list` | `/site.example.com/192.168.1.1` | +|  `allservers` | Force dnsmasq to send all queries to all available upstream DNS servers | `optional` | `boolean` | `0` | +| `dhcp_pools` | List of per interface [lease pools and settings](https://openwrt.org/docs/guide-user/base-system/dhcp#dhcp_pools) | | `list of dictionaries` | | +|  `id` | Unique dhcp pool ID | `mandatory` | `string` | `lan` | +|  `interface` | Interface associated with DHCP pool (must be one of the interfaces defined in `/etc/config/network`) | `mandatory` | `string` | `lan` | +|  `state` | DHCP pool status (`present` or `absent`) | `required` | `string` | `present` | +|  `dhcp_option` | List of DHCP options | `optional` | `list` | `["3,192.168.1.1", "6,192.168.1.1"]` | +|  `force` | Force DHCP serving on the specified interface even if another DHCP server is detected on the same network segment | `optional` | `boolean` | `0` | +|  `dhcpv4` | Enable or disable DHCPv4 server (`server` or `disabled`) | `mandatory` | `string` | `server` | +|  `leasetime` | Lease time of addresses handed out to client | `required` | `string` | `12h` | +|  `limit` | Size of the address pool | `required` | `integer` | `150` | +|  `start` | Offset from the network address of the underlying interface (for calculating the minimum address that may be leased to clients) | `required` | `integer` | `100` | +|  `ra` | Operation mode of the Router Advertisements service (`server`, `relay`, `hybrid` or `disabled`) | `optional` | `string` | `disabled` | +|  `dhcpv6` | Operation mode of the DHCPv6 service (`server`, `relay`, `hybrid` or `disabled`) | `optional` | `string` | `disabled` | +|  `dns_service` | Enable local IPv6 DNS server | `optional` | `boolean` | `0` | +| `dhcp_leases` | List of hosts' [static leases](https://openwrt.org/docs/guide-user/base-system/dhcp#static_leases) | | `list of dictionaries` | | +|  `id` | Unique dhcp lease ID | `optional` | `string` | `host01` | +|  `name` | Optional hostname to assign to the host | `optional` | `string` | `host01` | +|  `state` | Static lease status (`present` or `absent`) | `required` | `string` | `present` | +|  `ip` | IP address to assign to the host (`IP address` or `ignore`) | `mandatory` | `string` | `192.168.1.11` | +|  `mac` | Hardware address of the host | `mandatory` | `string` | `00:11:22:33:44:55` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.dhcp +``` + +## Example Vars + +```yaml +dhcp_common: + authoritative: "1" + boguspriv: "1" + cachesize: "1000" + domainneeded: "1" + rebind_protection: "1" + rebind_localhost: "1" +dhcp_pools: + - id: "lan" + interface: "lan" + state: "state" + dhcpv4: "server" + limit: "50" + start: "50" +dhcp_leases: + - id: "host01" + name: "host01" + state: "present" + ip: "192.168.1.51" + mac: "00:11:22:33:44:55" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/base-system/dhcp diff --git a/roles/dhcp/defaults/main.yml b/roles/dhcp/defaults/main.yml new file mode 100644 index 0000000..e79e8b8 --- /dev/null +++ b/roles/dhcp/defaults/main.yml @@ -0,0 +1,51 @@ +--- +# dnsmasq section +dhcp_common: + authoritative: "" + boguspriv: "" + cachesize: "" + domain: "" + domainneeded: "" + dnssec: "" + dnsseccheckunsigned: "" + expandhosts: "" + filterwin2k: "" + fqdn: "" + leasefile: "" + local: "" + localise_queries: "" + localservice: "" + nonegcache: "" + nonwildcard: "" + readethers: "" + rebind_protection: "" + rebind_localhost: "" + rebind_domain: [] + resolvfile: "" + server: [] + serverlist: "" + address: [] + allservers: "" + +# dhcp section +dhcp_pools: + - id: "" + interface: "" + state: "" + dhcp_option: [] + force: "" + dhcpv4: "" + leasetime: "" + limit: "" + start: "" + ra: "" + dhcpv6: "" + dns_service: "" + +# host section +dhcp_leases: + - id: "" + name: "" + state: "" + ip: "" + mac: "" diff --git a/roles/dhcp/handlers/main.yml b/roles/dhcp/handlers/main.yml new file mode 100644 index 0000000..c651c66 --- /dev/null +++ b/roles/dhcp/handlers/main.yml @@ -0,0 +1,7 @@ +--- +# Reload dhcp service +- name: Reload dhcp + ansible.builtin.service: + name: "{{ item }}" + state: restarted + loop: ["dnsmasq", "odhcpd"] diff --git a/roles/dhcp/meta/main.yml b/roles/dhcp/meta/main.yml new file mode 100644 index 0000000..359803b --- /dev/null +++ b/roles/dhcp/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure dhcp settings + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "dhcp"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/dhcp/tasks/dhcp.yml b/roles/dhcp/tasks/dhcp.yml new file mode 100644 index 0000000..b5de251 --- /dev/null +++ b/roles/dhcp/tasks/dhcp.yml @@ -0,0 +1,45 @@ +--- +# Set state status for dhcp pool +- name: Set state status for dhcp pool {{ item.id | default(item.interface) }} + ansible.builtin.set_fact: + dhcp_state: "{{ item.state | default('present') }}" + +# Delete dhcp pool for interface +- name: Delete dhcp pool for interface {{ item.id | default(item.interface) }} + when: "'absent' in dhcp_state" + uci: + command: "absent" + config: "dhcp" + section: "{{ item.id | default(item.interface) }}" + type: "dhcp" + +# Create and configure dhcp pool for interface +- name: Create and configure dhcp pool for interface + when: "'present' in dhcp_state" + block: + # Create dhcp pool for interface + - name: Create dhcp pool for interface {{ item.id | default(item.interface) }} + uci: + command: "add" + config: "dhcp" + section: "{{ item.id | default(item.interface) }}" + type: "dhcp" + + # Configure dhcp pool + - name: Configure dhcp pool for {{ item.id | default(item.interface) }} + uci: + command: "set" + config: "dhcp" + section: "{{ item.id | default(item.interface) }}" + type: "dhcp" + value: + interface: "{{ item.interface | default(omit) }}" + dhcp_option: "{{ item.dhcp_option | default([]) | join(' ') }}" + force: "{{ item.force | default(omit) }}" + dhcpv4: "{{ item.dhcpv4 | default(omit) }}" + leasetime: "{{ item.leasetime | default(omit) }}" + limit: "{{ item.limit | default(omit) }}" + start: "{{ item.start | default(omit) }}" + ra: "{{ item.ra | default(omit) }}" + dhcpv6: "{{ item.dhcpv6 | default(omit) }}" + dns_service: "{{ item.dns_service | default(omit) }}" diff --git a/roles/dhcp/tasks/dnsmasq.yml b/roles/dhcp/tasks/dnsmasq.yml new file mode 100644 index 0000000..527097f --- /dev/null +++ b/roles/dhcp/tasks/dnsmasq.yml @@ -0,0 +1,34 @@ +--- +# Configure common options +- name: Configure common options + uci: + command: "set" + config: "dhcp" + section: "@dnsmasq[0]" + type: "dnsmasq" + value: + authoritative: "{{ dhcp_common.authoritative | default(omit) }}" + boguspriv: "{{ dhcp_common.boguspriv | default(omit) }}" + cachesize: "{{ dhcp_common.cachesize | default(omit) }}" + domain: "{{ dhcp_common.domain | default(omit) }}" + domainneeded: "{{ dhcp_common.domainneeded | default(omit) }}" + dnssec: "{{ dhcp_common.dnssec | default(omit) }}" + dnsseccheckunsigned: "{{ dhcp_common.dnsseccheckunsigned | default(omit) }}" + expandhosts: "{{ dhcp_common.expandhosts | default(omit) }}" + filterwin2k: "{{ dhcp_common.filterwin2k | default(omit) }}" + fqdn: "{{ dhcp_common.fqdn | default(omit) }}" + leasefile: "{{ dhcp_common.leasefile | default(omit) }}" + local: "{{ dhcp_common.local | default(omit) }}" + localise_queries: "{{ dhcp_common.localise_queries | default(omit) }}" + localservice: "{{ dhcp_common.localservice | default(omit) }}" + nonegcache: "{{ dhcp_common.nonegcache | default(omit) }}" + nonwildcard: "{{ dhcp_common.nonwildcard | default(omit) }}" + readethers: "{{ dhcp_common.readethers | default(omit) }}" + rebind_protection: "{{ dhcp_common.rebind_protection | default(omit) }}" + rebind_localhost: "{{ dhcp_common.rebind_localhost | default(omit) }}" + rebind_domain: "{{ dhcp_common.rebind_domain | default([]) | join(' ') }}" + resolvfile: "{{ dhcp_common.resolvfile | default([]) | join(' ') }}" + server: "{{ dhcp_common.server | default([]) | join(' ') }}" + serverlist: "{{ dhcp_common.serverlist | default(omit) }}" + address: "{{ dhcp_common.address | default([]) | join(' ') }}" + allservers: "{{ dhcp_common.allservers | default(omit) }}" diff --git a/roles/dhcp/tasks/host.yml b/roles/dhcp/tasks/host.yml new file mode 100644 index 0000000..c787d57 --- /dev/null +++ b/roles/dhcp/tasks/host.yml @@ -0,0 +1,40 @@ +--- +# Set static lease state status for host +- name: Set static lease state status for host {{ item.id }} + ansible.builtin.set_fact: + static_lease_state: "{{ item.state | default('present') }}" + +# Delete static lease for host +- name: Delete static lease for host {{ item.id }} + when: "'absent' in static_lease_state" + uci: + command: "absent" + config: "dhcp" + section: "{{ item.id }}" + type: "host" + +# Create and configure static lease for host +- name: Create and configure static lease for host + when: "'present' in static_lease_state" + block: + # Create static lease for host + - name: Create static lease for host {{ item.id }} + uci: + command: "add" + config: "dhcp" + section: "{{ item.id | default('@host[-1]') }}" + type: "host" + + # Configure static lease for host + - name: Configure static lease for host {{ item.id }} + uci: + command: "set" + config: "dhcp" + section: "{{ item.id | default('@host[-1]') }}" + type: "host" + value: + name: "{{ item.name | default(omit) }}" + ip: "{{ item.ip | default(omit) }}" + mac: "{{ item.mac | default(omit) }}" + tag: "{{ item.tag | default(omit) }}" + dns: "{{ item.dns | default(omit) }}" diff --git a/roles/dhcp/tasks/main.yml b/roles/dhcp/tasks/main.yml new file mode 100644 index 0000000..0040fe2 --- /dev/null +++ b/roles/dhcp/tasks/main.yml @@ -0,0 +1,20 @@ +--- +# Configure dnsmasq section +- name: Configure dnsmasq section + ansible.builtin.include_tasks: dnsmasq.yml + +# Configure dhcp section +- name: Configure dhcp section + ansible.builtin.include_tasks: dhcp.yml + loop: "{{ dhcp_pools | default([]) }}" + +# Configure host section +- name: Configure host section + ansible.builtin.include_tasks: host.yml + loop: "{{ dhcp_leases | default([]) }}" + +# Apply changes and reload DHCP service +- name: Apply changes and reload dhcp + uci: + command: commit + notify: Reload dhcp diff --git a/roles/dropbear/README.md b/roles/dropbear/README.md new file mode 100644 index 0000000..c41dc72 --- /dev/null +++ b/roles/dropbear/README.md @@ -0,0 +1,53 @@ +# `flyoverhead.openwrt.dropbear` + +OpenWRT `dropbear` configuration +- configure dropbear settings + +## Role Variables + +| Variable | Descritpion | Status | Type | Example | +| :--- | :--- | :--- | :--- | :--- | +| `dropbear` | Dropbear settings configuration | | `dictionary` | | +|  `enable` | Enable starting dropbear at system boot | `required` | `boolean` | `1` | +|  `verbose` | Enable verbose output by the start scrip | `optional` | `boolean` | `0` | +|  `BannerFile` | Name of a file to be printed before the user has authenticated successfully | `optional` | `string` | `7` | +|  `PasswordAuth` | Allow authenticating with passwords | `optional` | `boolean` | `1` | +|  `Port` | SSH service listening port | `required` | `integer` | `22` | +|  `RootPasswordAuth` | Allow authenticating as root with passwords | `optional` | `boolean` | `1` | +|  `RootLogin` | Allow SSH logins as root | `optional` | `boolean` | `1` | +|  `GatewayPorts` | Allow remote hosts to connect to forwarded port | `optional` | `boolean` | `0` | +|  `Interface` | Limit connections to specified network interface | `optional` | `string` | `lan` | +|  `keyfile` | Path to host key file | `optional` | `string` | `/etc/dropbear/authorized_keys` | +|  `SSHKeepAlive` | Keep alive | `optional` | `integer` | `300` | +|  `IdleTimeout` | Idle timeout | `optional` | `integer` | `0` | +|  `mdns` | Enable announcing the service via mDNS | `optional` | `boolean` | `1` | +|  `MaxAuthTries` | Amount of password entering retries before SSH server closes the connection | `optional` | `integer` | `3` | +|  `RecvWindowSize` | Per-channel receive window buffer size | `optional` | `integer` | `24576` | + +> Note: multiple public keys can be added to `authorized_keys` file in `files` directory + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.dropbear +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/base-system/dropbear diff --git a/roles/dropbear/defaults/main.yml b/roles/dropbear/defaults/main.yml new file mode 100644 index 0000000..d6c3815 --- /dev/null +++ b/roles/dropbear/defaults/main.yml @@ -0,0 +1,18 @@ +--- +# system section +dropbear: + enable: "" + verbose: "" + BannerFile: "" + PasswordAuth: "" + Port: "" + RootPasswordAuth: "" + RootLogin: "" + GatewayPorts: "" + Interface: "" + keyfile: "" + SSHKeepAlive: "" + IdleTimeout: "" + mdns: "" + MaxAuthTries: "" + RecvWindowSize: "" diff --git a/roles/dropbear/files/authorized_keys b/roles/dropbear/files/authorized_keys new file mode 100644 index 0000000..e69de29 diff --git a/roles/dropbear/handlers/main.yml b/roles/dropbear/handlers/main.yml new file mode 100644 index 0000000..fa645a0 --- /dev/null +++ b/roles/dropbear/handlers/main.yml @@ -0,0 +1,6 @@ +--- +# Reload dropbear service +- name: Reload dropbear + ansible.builtin.service: + name: dropbear + state: reloaded diff --git a/roles/dropbear/meta/main.yml b/roles/dropbear/meta/main.yml new file mode 100644 index 0000000..16b51eb --- /dev/null +++ b/roles/dropbear/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure dropbear settings + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "dropbear"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/dropbear/tasks/dropbear.yml b/roles/dropbear/tasks/dropbear.yml new file mode 100644 index 0000000..5e356bb --- /dev/null +++ b/roles/dropbear/tasks/dropbear.yml @@ -0,0 +1,24 @@ +--- +# Configure dropbear settings +- name: Configure dropbear settings + uci: + command: "set" + config: "dropbear" + section: "@dropbear[0]" + type: "dropbear" + value: + enable: "{{ dropbear.enable | default(omit) }}" + verbose: "{{ dropbear.verbose | default(omit) }}" + BannerFile: "{{ dropbear.BannerFile | default(omit) }}" + PasswordAuth: "{{ dropbear.PasswordAuth | default(omit) }}" + Port: "{{ dropbear.Port | default(omit) }}" + RootPasswordAuth: "{{ dropbear.RootPasswordAuth | default(omit) }}" + RootLogin: "{{ dropbear.RootLogin | default(omit) }}" + GatewayPorts: "{{ dropbear.GatewayPorts | default(omit) }}" + Interface: "{{ dropbear.Interface | default(omit) }}" + keyfile: "{{ dropbear.keyfile | default(omit) }}" + SSHKeepAlive: "{{ dropbear.SSHKeepAlive | default(omit) }}" + IdleTimeout: "{{ dropbear.IdleTimeout | default(omit) }}" + mdns: "{{ dropbear.mdns | default(omit) }}" + MaxAuthTries: "{{ dropbear.MaxAuthTries | default(omit) }}" + RecvWindowSize: "{{ dropbear.RecvWindowSize | default(omit) }}" diff --git a/roles/dropbear/tasks/main.yml b/roles/dropbear/tasks/main.yml new file mode 100644 index 0000000..f8872e6 --- /dev/null +++ b/roles/dropbear/tasks/main.yml @@ -0,0 +1,20 @@ +--- +# Configure dropbear section +- name: Configure dropbear section + ansible.builtin.include_tasks: dropbear.yml + +# Copy SSH authorized keys +- name: Copy ssh authorized keys + ansible.builtin.copy: + src: "authorized_keys" + dest: "/etc/dropbear/authorized_keys" + owner: "root" + group: "root" + mode: "0600" + force: true + +# Apply changes and reload dropbear service +- name: Apply changes and reload dropbear + uci: + command: commit + notify: Reload dropbear diff --git a/roles/extroot/README.md b/roles/extroot/README.md new file mode 100644 index 0000000..07d11cd --- /dev/null +++ b/roles/extroot/README.md @@ -0,0 +1,47 @@ +# `flyoverhead.openwrt.extroot` + +OpenWRT `extroot` configuration +- configure extroot + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `extroot_enabled` | Enable extroot configuration | `required` | `boolean` | `false` | +| `extroot_pkgs` | List of packages required for extroot configuration | `required` | `list` | `["kmod-usb-core", "kmod-usb-storage", "kmod-usb2", "kmod-usb3", "block-mount", "kmod-fs-ext4", "e2fsprogs", "parted"]` | +| `extroot_device` | External USB device name | `required` | `string` | `sda` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.extroot +``` + +## Example Vars + +```yaml +extroot_enabled: true +extroot_device: "sda" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/additional-software/extroot_configuration +- https://openwrt.org/docs/guide-user/advanced/hotplug_extras +- https://openwrt.org/docs/guide-user/advanced/opkg_extras diff --git a/roles/extroot/defaults/main.yml b/roles/extroot/defaults/main.yml new file mode 100644 index 0000000..284f71c --- /dev/null +++ b/roles/extroot/defaults/main.yml @@ -0,0 +1,19 @@ +--- +# Deafult extroot status +extroot_enabled: false + +# extroot required packages +extroot_pkgs: + [ + "kmod-usb-core", + "kmod-usb-storage", + "kmod-usb2", + "kmod-usb3", + "block-mount", + "kmod-fs-ext4", + "e2fsprogs", + "parted", + ] + +# extroot device +extroot_device: "sda" diff --git a/roles/extroot/files/90-extroot-restore b/roles/extroot/files/90-extroot-restore new file mode 100644 index 0000000..72378fd --- /dev/null +++ b/roles/extroot/files/90-extroot-restore @@ -0,0 +1,19 @@ +if uci -q get fstab.overlay > /dev/null \ +&& [ ! -e /etc/extroot-restore ] \ +&& lock -n /var/lock/extroot-restore \ +&& [ -e /etc/opkg-restore-init ] +then +UUID="$(uci -q get fstab.overlay.uuid)" +OVRL="$(block info | sed -n -e "/${UUID}/s/:.*$//p")" +mount "${OVRL}" /mnt +BAK="$(mktemp -d -p /mnt -t bak.XXXXXX)" +mv -f /mnt/etc /mnt/upper "${BAK}" +touch /etc/extroot-restore +if grep -q -e "\s/overlay\s" /etc/mtab +then cp -f -a /overlay/. /mnt +fi +umount "${OVRL}" +lock -u /var/lock/extroot-restore +reboot +fi +exit 1 diff --git a/roles/extroot/handlers/main.yml b/roles/extroot/handlers/main.yml new file mode 100644 index 0000000..812adf8 --- /dev/null +++ b/roles/extroot/handlers/main.yml @@ -0,0 +1,13 @@ +--- +# Reboot device +- name: Reboot device + ansible.builtin.command: + cmd: "reboot" + register: reboot_device_status + changed_when: reboot_device_status != 0 + +# Wait for device to boot up +- name: Wait for device to boot up + ansible.builtin.wait_for_connection: + delay: 30 + timeout: 300 diff --git a/roles/extroot/meta/main.yml b/roles/extroot/meta/main.yml new file mode 100644 index 0000000..a6ff093 --- /dev/null +++ b/roles/extroot/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure external root + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "extroot"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/extroot/tasks/check.yml b/roles/extroot/tasks/check.yml new file mode 100644 index 0000000..7eac336 --- /dev/null +++ b/roles/extroot/tasks/check.yml @@ -0,0 +1,24 @@ +--- +# Set extroot status to false +# to prevent permanent configuration +- name: Set default extroot status fact to false + ansible.builtin.set_fact: + extroot_configure: false + +# Check current extroot status +- name: Check current extroot status + uci: + command: "get" + config: "fstab" + section: "@mount[0].target" + type: "mount" + register: extroot_status + failed_when: > + extroot_status.result is undefined and + 'Entry not found' not in extroot_status.result + +# Set extroot status fact +- name: Set extroot status fact + ansible.builtin.set_fact: + extroot_configure: true + when: extroot_device not in extroot_status.result diff --git a/roles/extroot/tasks/fstab.yml b/roles/extroot/tasks/fstab.yml new file mode 100644 index 0000000..aaa6250 --- /dev/null +++ b/roles/extroot/tasks/fstab.yml @@ -0,0 +1,68 @@ +--- +# Get rootfs block device name +- name: Get rootfs block device name + ansible.builtin.command: + cmd: 'sed -n -e "/\s\/overlay\s.*$/s///p" /etc/mtab' + register: rootfs_block_device_name + changed_when: rootfs_block_device_name.rc != 0 + +# Set rootfs block device name fact +- name: Set rootfs block device name fact + ansible.builtin.set_fact: + block_device_name: "{{ rootfs_block_device_name.stdout }}" + +# Mount rootfs data to another directory +- name: Mount rootfs data to another directory + block: + # Add new mount point for root + - name: Add new mount point for root + uci: + command: "add" + config: "fstab" + section: "rwm" + type: "mount" + + # Configure new mount point for root + - name: Configure new mount point for root + uci: + command: "set" + config: "fstab" + section: "rwm" + type: "mount" + value: + device: "{{ block_device_name }}" + target: "/rwm" + +# Get external USB device UUID +- name: Get external usb device uuid + ansible.builtin.command: + cmd: 'block info /dev/{{ extroot_device }}1 | grep -o -e "UUID=\S*"' + register: external_usb_device_uuid + changed_when: external_usb_device_uuid.rc != 0 + +# Set external usb device uuid fact +- name: Set external usb device uuid fact + ansible.builtin.set_fact: + usb_device_uuid: '{{ external_usb_device_uuid.stdout | regex_search(''(?<=")(.*?)(?=")'') }}' + +# Mount external USB as overlayfs +- name: Mount external usb as overlayfs + block: + # Add overlay mount point + - name: Add overlay mount point + uci: + command: "add" + config: "fstab" + section: "overlay" + type: "mount" + + # Configure overlay mount point + - name: Configure overlay mount point + uci: + command: "set" + config: "fstab" + section: "overlay" + type: "mount" + value: + uuid: "{{ usb_device_uuid }}" + target: "/overlay" diff --git a/roles/extroot/tasks/main.yml b/roles/extroot/tasks/main.yml new file mode 100644 index 0000000..51a8427 --- /dev/null +++ b/roles/extroot/tasks/main.yml @@ -0,0 +1,39 @@ +--- +# Check extroot status +- name: Check extroot status + ansible.builtin.include_tasks: check.yml + when: extroot_enabled + +# Install required packages +- name: Install required packages + ansible.builtin.include_tasks: prepare.yml + when: extroot_configure + +# Configure exteral USB drive +- name: Configure external usb + ansible.builtin.include_tasks: usb.yml + when: extroot_configure + +# Configure fstab +- name: Configure fstab + ansible.builtin.include_tasks: fstab.yml + when: extroot_configure + +# Configure system +- name: Configure system + ansible.builtin.include_tasks: system.yml + when: extroot_configure + +# Apply changes and reboot device +- name: Apply changes and reboot device + when: extroot_configure + block: + # Commit changes + - name: Commit changes + uci: + command: commit + notify: ["Reboot device", "Wait for device to boot up"] + + # Reboot device + - name: Reboot device + ansible.builtin.meta: flush_handlers diff --git a/roles/extroot/tasks/prepare.yml b/roles/extroot/tasks/prepare.yml new file mode 100644 index 0000000..d72a314 --- /dev/null +++ b/roles/extroot/tasks/prepare.yml @@ -0,0 +1,13 @@ +--- +# Update opkg cache +- name: Update opkg cache + ansible.builtin.command: + cmd: "opkg update" + changed_when: false + +# Install required packages +- name: Install required packages + opkg: + name: "{{ item }}" + state: "present" + loop: "{{ extroot_pkgs }}" diff --git a/roles/extroot/tasks/system.yml b/roles/extroot/tasks/system.yml new file mode 100644 index 0000000..c0c58ea --- /dev/null +++ b/roles/extroot/tasks/system.yml @@ -0,0 +1,55 @@ +--- +# Copy overlay partition content to external USB device +- name: Copy overlay content to external usb device + ansible.builtin.command: + cmd: "{{ item }}" + uses_shell: true + loop: + [ + "mount /dev/{{ extroot_device }}1 /mnt", + "tar -C /overlay -cvf - . | tar -C /mnt -xf -", + "umount /mnt", + ] + loop_control: + label: "{{ item }}" + +# Configure hotplug extras +- name: Configure hotplug extras + ansible.builtin.command: + cmd: "{{ item }}" + chdir: "/tmp" + loop: + [ + 'uclient-fetch -O hotplug-extras.sh "https://openwrt.org/_export/code/docs/guide-user/advanced/hotplug_extras?codeblock=0"', + "chmod +x ./hotplug-extras.sh", + ./hotplug-extras.sh, + ] + +# Configure opkg extras +- name: Configure opkg extras + ansible.builtin.command: + cmd: "{{ item }}" + chdir: "/tmp" + loop: + [ + 'uclient-fetch -O opkg-extras.sh "https://openwrt.org/_export/code/docs/guide-user/advanced/opkg_extras?codeblock=0"', + "chmod +x ./opkg-extras.sh", + ./opkg-extras.sh, + ] + +# Configure extroot auto restore +- name: Configure extroot auto restore + ansible.builtin.copy: + src: "90-extroot-restore" + dest: "/etc/uci-defaults/90-extroot-restore" + owner: "root" + group: "root" + mode: "0644" + +# Add auto restore to sysupgrade configuration +- name: Add auto restore to sysupgrade.conf + ansible.builtin.lineinfile: + path: "/etc/sysupgrade.conf" + line: "/etc/uci-defaults" + insertafter: "EOF" + state: "present" diff --git a/roles/extroot/tasks/usb.yml b/roles/extroot/tasks/usb.yml new file mode 100644 index 0000000..e460ab1 --- /dev/null +++ b/roles/extroot/tasks/usb.yml @@ -0,0 +1,10 @@ +--- +# Create new partition in external USB disk +- name: Create partition in external usb device + ansible.builtin.command: + cmd: "parted -s /dev/{{ extroot_device }} -- mklabel gpt mkpart extroot 2048s -2048s" + +# Format partition to EXT4 file system +- name: Format partition to ext4 fs + ansible.builtin.command: + cmd: "mkfs.ext4 -FL extroot /dev/{{ extroot_device }}1" diff --git a/roles/firewall/README.md b/roles/firewall/README.md new file mode 100644 index 0000000..9a9f141 --- /dev/null +++ b/roles/firewall/README.md @@ -0,0 +1,192 @@ +# `flyoverhead.openwrt.firewall` + +OpenWRT `firewall` configuration +- configure defaults settings +- create/delete/configure firewall zones +- create/delete/configure firewall zone forwardings +- create/delete/configure firewall traffic rules +- create/delete/configure firewall port forwardings +- create/delete/configure firewall ip sets +- create/delete/configure firewall nat rules + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `firewall_defaults` | [Minimal firewall configuration](https://openwrt.org/docs/guide-user/firewall/firewall_configuration#defaults) | | `dictionary` | | +|  `input` | Set policy for the `INPUT` chain of the `filter` table (`ACCEPT`, `REJECT`, `DROP`) | `optional` | `string` | `REJECT` | +|  `forward` | Set policy for the `FORWARD` chain of the `filter` table (`ACCEPT`, `REJECT`, `DROP`) | `optional` | `string` | `REJECT` | +|  `output` | Set policy for the `OUTPUT` chain of the `filter` table (`ACCEPT`, `REJECT`, `DROP`) | `optional` | `string` | `REJECT` | +|  `drop_invalid` | Drop invalid packets | `optional` | `boolean` | `0` | +|  `synflood_protect` | Enable SYN flood protection | `optional` | `boolean` | `0` | +|  `synflood_rate` | Set rate limit (packets/second) for SYN packets which the traffic is considered a flood | `optional` | `string` | `25/s` | +|  `synflood_burst` | Set burst limit for SYN packets which the traffic is considered a flood if it exceeds the allowed rate | `optional` | `string` | `50` | +|  `flow_offloading` | Enable software flow offloading for connections | `optional` | `boolean` | `0` | +|  `flow_offloading_hw` | Enable hardware flow offloading for connections | `optional` | `boolean` | `0` | +| `firewall_zones` | List of [firewall zones](https://openwrt.org/docs/guide-user/firewall/firewall_configuration#zones) | | `list of dictionaries` | | +|  `id` | Unique zone ID | `mandatory` | `string` | `guest` | +|  `name` | Unique zone name | `mandatory` | `string` | `guest` | +|  `state` | Zone status (`present` or `absent`) | `required` | `string` | `present` | +|  `network` | List of interfaces attached to this zone (if omitted and neither extra* options, subnets nor devices are given, the value of `name` is used by default) | `required` | `list` | `["lan"]` | +|  `masq` | Masquerade outgoing zone IPv4 traffic | `optional` | `boolean` | `0` | +|  `mtu_fix` | Enable MSS clamping for outgoing zone traffic | `optional` | `boolean` | `0` | +|  `input` | Default policy for incoming zone traffic (`ACCEPT`, `REJECT`, `DROP`) | `optional` | `string` | `DROP` | +|  `forward` | Default policy for forwarded zone traffic (`ACCEPT`, `REJECT`, `DROP`) | `optional` | `string` | `DROP` | +|  `output` | Default policy for outgoing zone traffic (`ACCEPT`, `REJECT`, `DROP`) | `optional` | `string` | `DROP` | +|  `family` | Protocol family used by iptables rule (`ipv4`, `ipv6` or `any`) | `optional` | `string` | `any` | +|  `enabled` | Enable zone | `optional` | `boolean` | `1` | +| `firewall_forwardings` | List of [zone forwardings](https://openwrt.org/docs/guide-user/firewall/firewall_configuration#forwardings) | | (`list of dictionaries`) | | +|  `name` | Unique forwarding name | `mandatory` | `string` | `guest` | +|  `state` | Forwarding status (`present` or `absent`) | `required` | `string` | `present` | +|  `src` | Traffic source zone (one of the defined `zone names`) | `mandatory` | `string` | `lan` | +|  `dest` | Traffic destination zone (one of the defined `zone names`) | `mandatory` | `string` | `wan` | +|  `family` | Protocol family used by iptables rule (`ipv4`, `ipv6` or `any`) | `optional` | `string` | `any` | +|  `ipset` | Match traffic against the given ipset | `optional` | `string` | `ipset_example` | +|  `enabled` | Enable forwarding | `optional` | `boolean` | `1` | +| `firewall_rules` | List of [traffic rules](https://openwrt.org/docs/guide-user/firewall/firewall_configuration#rules) | | (`list of dictionaries`) | | +|  `id` | Unique rule ID | `mandatory` | `string` | `rule_example` | +|  `name` | Unique rule name | `mandatory` | `string` | `Example rule` | +|  `state` | Rule status (`present` or `absent`) | `required` | `string` | `present` | +|  `src` | Traffic source zone (one of the defined `zone names` or `*` for any zone) | `required` | `string` | `wan` | +|  `src_ip` | Match incoming traffic from the specified source IP address | `optional` | `string` | `192.168.1.1` | +|  `src_port` | Match incoming traffic from the specified source port or port range, if relevant `proto` is specified | `optional` | `list` | `["22", "80", "3000-3010"]` | +|  `src_mac` | Match incoming traffic from the specified MAC address | `optional` | `string` | `00:11:22:33:44:55` | +|  `dest` | Traffic destination zone (one of the defined `zone names` or `*` for any zone) | `required` | `string` | `lan` | +|  `dest_ip` | Match incoming traffic directed to the specified destination IP address | `optional` | `string` | `192.168.1.10` | +|  `dest_port` | Match incoming traffic directed at the given destination port or port range, if relevant `proto` is specified | `optional` | `list` | `["22", "80", "3000-3010"]` | +|  `target` | Firewall action (`ACCEPT`, `REJECT`, `DROP`, `MARK`, `NOTRACK`) for matched traffic | `mandatory` | `string` | `DROP` | +|  `proto` | Match incoming traffic using the given protocol (`tcp`, `udp`, `udplite`, `icmp`, `esp`, `ah`, `sctp`, or `all`) | `optional` | `list` | `["tcp", "udp"]` | +|  `family` | Protocol family used by iptables rule (`ipv4`, `ipv6` or `any`) | `optional` | `string` | `any` | +|  `ipset` | Match traffic against the given ipset | `optional` | `string` | `ipset_example` | +|  `mark` | Match traffic against the given firewall mark | `optional` | `string` | `prohibit` | +|  `set_mark` | Zeroes out the bits given by mask and ORs value into the packet mark | `optional` | `string` | `0xFFFFFFFF` | +|  `enabled` | Enable rule | `optional` | `boolean` | `0` | +| `firewall_redirects` | List of [port forwardings](https://openwrt.org/docs/guide-user/firewall/firewall_configuration#redirects) | | (`list of dictionaries`) | | +|  `id` | Unique redirect ID | `mandatory` | `string` | `redirect_example` | +|  `name` | Redirect description | `mandatory` | `string` | `Example redirection` | +|  `state` | Redirect status (`present` or `absent`) | `required` | `string` | `present` | +|  `src` | Traffic source zone (one of the defined `zone names`) | `required` | `string` | `wan` | +|  `src_ip` | Match incoming traffic from the specified source IP address | `optional` | `string` | `172.16.0.10` | +|  `src_port` | Match incoming traffic originating from the given source port or port range on the client host | `optional` | `string` | `22` | +|  `src_mac` | Match incoming traffic from the specified MAC address | `optional` | `string` | `00:11:22:33:44:55` | +|  `src_dip` | Match incoming traffic directed at the given destination IP address (for DNAT), or rewrite the source address to the given address (for SNAT) | `optional` | `string` | `172.16.0.10` | +|  `src_dport` | Match incoming traffic directed at the given destination port or port range (for DNAT), or rewrite the source ports to the given value (for SNAT) | `optional` | `string` | `22` | +|  `dest` | Traffic destination zone (one of the defined `zone names`) | `required` | `string` | `lan` | +|  `dest_ip` | Redirect matches incoming traffic to the specified internal host (for DNAT), or match traffic directed at the given address (for SNAT) | `optional` | `string` | `192.168.1.1` | +|  `dest_port` | Redirect matched incoming traffic to the given port or port range (for DNAT), or match traffic directed at the given port or port range (for SNAT) | `optional` | `string` | `22` | +|  `target` | NAT target for the rule (`DNAT` or `SNAT`) | `optional` | `string` | `DNAT` | +|  `proto` | Match incoming traffic using the given protocol (`tcp`, `udp`, `udplite`, `icmp`, `esp`, `ah`, `sctp`, or `all`) | `optional` | `list` | `["tcp", "udp"]` | +|  `family` | Protocol family used by iptables rule (`ipv4`, `ipv6` or `any`) | `optional` | `string` | `any` | +|  `ipset` | Match traffic against the given ipset | `optional` | `string` | `ipset_example` | +|  `mark` | Match traffic against the given firewall mark | `optional` | `string` | `0xFFFFFFFF` | +|  `enabled` | Enable redirect | `optional` | `boolean` | `1` | +| `firewall_ipsets` | List of [IP sets](https://openwrt.org/docs/guide-user/firewall/firewall_configuration#options_fw4) | | (`list of dictionaries`) | | +|  `id` | Unique ipset ID | `mandatory` | `string` | `ipset_example` | +|  `name` | Unique ipset name | `mandatory` | `string` | `Example IPset` | +|  `state` | Forwarding status (`present` or `absent`) | `required` | `string` | `present` | +|  `comment` | Comment for the ipset | `optional` | `string` | `Example IP set` | +|  `match` | List of matched data types (`ip`, `port`, `mac`, `net` or `set`) and their direction (`src` or `dest`) joined by an underscore | `mandatory` | `list` | `["src_ip", "port"]` | +|  `entry` | The IP address, CIDR, or MAC | `optional` | `list` | `["00:11:22:33:44:55", "172.16.0.0/24"]` | +|  `family` | Protocol family used by ipset (`ipv4`, `ipv6` or `any`) | `optional` | `string` | `ipv4` | +|  `maxelem` | Limits of items that can be added to the ipset | `optional` | `integer` | `65536` | +|  `loadfile` | Path to file containing a list of CIDRs, subnets, host IPs | `optional` | `string` | `/tmp/ipset.list` | +|  `enabled` | Enable ipset | `optional` | `boolean` | `1` | +| `firewall_nats` | List of [NAT rules](https://openwrt.org/docs/guide-user/firewall/fw3_configurations/fw3_nat#selective_nat) | | (`list of dictionaries`) | | +|  `id` | Unique nat ID | `mandatory` | `string` | `nat_example` | +|  `name` | Unique rule name | `mandatory` | `string` | `Example NAT` | +|  `state` | Redirect status (`present` or `absent`) | `required` | `string` | `present` | +|  `src` | Traffic source zone (one of the defined `zone names`) | `required` | `string` | `wan` | +|  `src_ip` | Match forwarded traffic from the specified source IP address or range | `optional` | `string` | `172.16.0.10` | +|  `src_port` | Match forwarded traffic originating from the given source port or port range | `optional` | `string` | `22` | +|  `dest_ip` | Match forwarded traffic directed at the given IP address | `optional` | `string` | `192.168.1.1` | +|  `dest_port` | Match forwarded traffic directed at the given destination port or port range | `optional` | `string` | `22` | +|  `snat_ip` | Rewrite matched traffic to the specified source IP address (for `SNAT`) | `optional` | `string` | `172.16.0.10` | +|  `snat_port` | Rewrite matched traffic to the specified source port or port range | `optional` | `string` | `22` | +|  `target` | NAT target for the rule (`ACCEPT`, `MASQUERADE` or `SNAT`) | `mandatory` | `string` | `ACCEPT` | +|  `proto` | Match incoming traffic using the given protocol (`tcp`, `udp`, `udplite`, `icmp`, `esp`, `ah`, `sctp`, or `all`) | `optional` | `list` | `["tcp", "udp"]` | +|  `family` | Protocol family used by ipset (`ipv4`, `ipv6` or `any`) | `optional` | `string` | `ipv4` | +|  `mark` | Match traffic against the given firewall mark | `optional` | `string` | `0xFFFFFFFF` | +|  `enabled` | Enable NAT rule | `optional` | `boolean` | `0` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.firewall +``` + +## Example Vars + +```yaml +firewall_defaults: + input: "ACCEPT" + forward: "REJECT" + output: "ACCEPT" + drop_invalid: "1" + synflood_protect: "1" +firewall_zones: + - id: "iot" + name: "iot" + state: "present" + network: ["iot"] + input: "DROP" + forward: "DROP" + output: "ACCEPT" + family: "ipv4" +firewall_forwardings: + - id: "lan_iot" + state: "present" + src: "lan" + dest: "iot" + family: "ipv4" + - id: "iot_wan" + state: "present" + src: "iot" + dest: "wan" + family: "ipv4" +firewall_rules: + - id: "allow_iot_dhcp_dns" + name: "Allow DHCP and DNS for IoT" + state: "present" + src: "iot" + src_port: ["53", "67", "68"] + dest: "lan" + dest_port: ["53", "67", "68"] + target: "ACCEPT" + family: "ipv4" +firewall_redirects: + - id: "force_dns_lan" + name: "Force lan DNS" + state: "present" + src: "lan" + src_dport: "53" + target: "DNAT" + family: "ipv4" + - id: "force_dns_iot" + name: "Force iot DNS" + state: "present" + src: "iot" + src_dport: "53" + target: "DNAT" + family: "ipv4" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/firewall/firewall_configuration +- https://openwrt.org/docs/guide-user/firewall/fw3_configurations/fw3_nat#nat_examples diff --git a/roles/firewall/defaults/main.yml b/roles/firewall/defaults/main.yml new file mode 100644 index 0000000..b9ed286 --- /dev/null +++ b/roles/firewall/defaults/main.yml @@ -0,0 +1,109 @@ +--- +# defaults section +firewall_defaults: + input: "" + forward: "" + output: "" + drop_invalid: "" + synflood_protect: "" + synflood_rate: "" + synflood_burst: "" + flow_offloading: "" + flow_offloading_hw: "" + +# zones section +firewall_zones: + - id: "" + name: "" + state: "" + network: [] + masq: "" + mtu_fix: "" + input: "" + forward: "" + output: "" + family: "" + enabled: "" + +# forwardings section +firewall_forwardings: + - id: "" + state: "" + src: "" + dest: "" + family: "" + ipset: "" + enabled: "" + +# rules section +firewall_rules: + - id: "" + name: "" + desc: "" + state: "" + src: "" + src_ip: "" + src_port: [] + src_mac: "" + dest: "" + dest_ip: "" + dest_port: [] + target: "" + proto: [] + family: "" + ipset: "" + mark: "" + set_mark: "" + enabled: "" + +# redirects section +firewall_redirects: + - id: "" + name: "" + state: "" + src: "" + src_ip: "" + src_port: "" + src_mac: "" + src_dip: "" + src_dport: "" + dest: "" + dest_ip: "" + dest_port: "" + target: "" + proto: [] + family: "" + ipset: "" + mark: "" + enabled: "" + +# ip sets section +firewall_ipsets: + - id: "" + name: "" + state: "" + comment: "" + match: [] + entry: [] + family: "" + maxelem: "" + loadfile: "" + enabled: "" + +# nat section +firewall_nats: + - id: "" + name: "" + state: "" + src: "" + src_ip: "" + src_port: "" + dest_ip: "" + dest_port: "" + snat_ip: "" + snat_port: "" + target: "" + proto: [] + family: "" + mark: "" + enabled: "" diff --git a/roles/firewall/handlers/main.yml b/roles/firewall/handlers/main.yml new file mode 100644 index 0000000..fdb4bc7 --- /dev/null +++ b/roles/firewall/handlers/main.yml @@ -0,0 +1,6 @@ +--- +# Reload firewall service +- name: Reload firewall + ansible.builtin.service: + name: firewall + state: restarted diff --git a/roles/firewall/meta/main.yml b/roles/firewall/meta/main.yml new file mode 100644 index 0000000..4c2f3f7 --- /dev/null +++ b/roles/firewall/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure firewall settings + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "firewall"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/firewall/tasks/defaults.yml b/roles/firewall/tasks/defaults.yml new file mode 100644 index 0000000..23a2b51 --- /dev/null +++ b/roles/firewall/tasks/defaults.yml @@ -0,0 +1,18 @@ +--- +# Configure defaults settings +- name: Configure defaults settings + uci: + command: "set" + config: "firewall" + section: "@defaults[0]" + type: "defaults" + value: + input: "{{ firewall_defaults.input | default(omit) }}" + forward: "{{ firewall_defaults.forward | default(omit) }}" + output: "{{ firewall_defaults.output | default(omit) }}" + drop_invalid: "{{ firewall_defaults.drop_invalid | default(omit) }}" + synflood_protect: "{{ firewall_defaults.synflood_protect | default(omit) }}" + synflood_rate: "{{ firewall_defaults.synflood_rate | default(omit) }}" + synflood_burst: "{{ firewall_defaults.synflood_burst | default(omit) }}" + flow_offloading: "{{ firewall_defaults.flow_offloading | default(omit) }}" + flow_offloading_hw: "{{ firewall_defaults.flow_offloading_hw | default(omit) }}" diff --git a/roles/firewall/tasks/forwarding.yml b/roles/firewall/tasks/forwarding.yml new file mode 100644 index 0000000..e9a5511 --- /dev/null +++ b/roles/firewall/tasks/forwarding.yml @@ -0,0 +1,41 @@ +--- +# Set state status for firewall forwarding +- name: Set state status for firewall forwarding {{ item.id | default('@forwarding[-1]') }} + ansible.builtin.set_fact: + firewall_forwarding_state: "{{ item.state | default('present') }}" + +# Delete firewall forwarding +- name: Delete firewall forwarding {{ item.id }} + when: "'absent' in firewall_forwarding_state" + uci: + command: "absent" + config: "firewall" + section: "{{ item.id }}" + type: "forwarding" + +# Create and configure firewall forwarding +- name: Create and configure firewall forwarding + when: "'present' in firewall_forwarding_state" + block: + # Create firewall forwarding + - name: Create firewall forwarding {{ item.id | default('@forwarding[-1]') }} + uci: + command: "add" + config: "firewall" + section: "{{ item.id | default('@forwarding[-1]') }}" + type: "forwarding" + + # Configure firewall forwarding + - name: Configure firewall forwarding {{ item.id | default('@forwarding[-1]') }} + uci: + command: "set" + config: "firewall" + section: "{{ item.id | default('@forwarding[-1]') }}" + type: "forwarding" + value: + name: "{{ item.id | default(omit) }}" + src: "{{ item.src | default(omit) }}" + dest: "{{ item.dest | default(omit) }}" + family: "{{ item.family | default(omit) }}" + ipset: "{{ item.ipset | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" diff --git a/roles/firewall/tasks/ipset.yml b/roles/firewall/tasks/ipset.yml new file mode 100644 index 0000000..9b861b0 --- /dev/null +++ b/roles/firewall/tasks/ipset.yml @@ -0,0 +1,43 @@ +--- +# Set state status for firewall ipset +- name: Set state status for firewall ipset {{ item.id | default('@ipset[-1]') }} + ansible.builtin.set_fact: + firewall_ipset_state: "{{ item.state | default('present') }}" + +# Delete firewall ipset +- name: Delete firewall ipset {{ item.id }} + when: "'absent' in firewall_ipset_state" + uci: + command: "absent" + config: "firewall" + section: "{{ item.id }}" + type: "ipset" + +# Create and configure firewall ipset +- name: Create and configure firewall ipset + when: "'present' in firewall_ipset_state" + block: + # Create firewall ipset + - name: Create firewall ipset {{ item.id | default('@ipset[-1]') }} + uci: + command: "add" + config: "firewall" + section: "{{ item.id | default('@ipset[-1]') }}" + type: "ipset" + + # Configure firewall ipset + - name: Configure firewall ipset {{ item.id | default('@ipset[-1]') }} + uci: + command: "set" + config: "firewall" + section: "{{ item.id | default('@ipset[-1]') }}" + type: "ipset" + value: + name: "{{ item.name | default(omit) }}" + comment: "{{ item.comment | default(omit) }}" + match: "{{ item.match | default([]) | join(' ') }}" + entry: "{{ item.entry | default([]) | join(' ') }}" + family: "{{ item.family | default(omit) }}" + maxelem: "{{ item.maxelem | default(omit) }}" + loadfile: "{{ item.loadfile | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" diff --git a/roles/firewall/tasks/main.yml b/roles/firewall/tasks/main.yml new file mode 100644 index 0000000..4c9eb3a --- /dev/null +++ b/roles/firewall/tasks/main.yml @@ -0,0 +1,40 @@ +--- +# Configure deaults section +- name: Configure defaults section + ansible.builtin.include_tasks: defaults.yml + +# Configure zone section +- name: Configure zone section + ansible.builtin.include_tasks: zone.yml + loop: "{{ firewall_zones | default([]) }}" + +# Configure forwarding section +- name: Configure forwarding section + ansible.builtin.include_tasks: forwarding.yml + loop: "{{ firewall_forwardings | default([]) }}" + +# Configure rule section +- name: Configure rule section + ansible.builtin.include_tasks: rule.yml + loop: "{{ firewall_rules | default([]) }}" + +# Configure redirect section +- name: Configure redirect section + ansible.builtin.include_tasks: redirect.yml + loop: "{{ firewall_redirects | default([]) }}" + +# Configure ipset section +- name: Configure ipset section + ansible.builtin.include_tasks: ipset.yml + loop: "{{ firewall_ipsets | default([]) }}" + +# Configure nat section +- name: Configure nat section + ansible.builtin.include_tasks: nat.yml + loop: "{{ firewall_nats | default([]) }}" + +# Apply changes and reload firewall service +- name: Apply changes and reload firewall + uci: + command: commit + notify: Reload firewall diff --git a/roles/firewall/tasks/nat.yml b/roles/firewall/tasks/nat.yml new file mode 100644 index 0000000..a0ff554 --- /dev/null +++ b/roles/firewall/tasks/nat.yml @@ -0,0 +1,48 @@ +--- +# Set state status for firewall nat +- name: Set state status for firewall nat {{ item.id | default('@nat[-1]') }} + ansible.builtin.set_fact: + firewall_nat_state: "{{ item.state | default('present') }}" + +# Delete firewall nat +- name: Delete firewall nat {{ item.id }} + when: "'absent' in firewall_nat_state" + uci: + command: "absent" + config: "firewall" + section: "{{ item.id }}" + type: "nat" + +# Create and configure firewall nat +- name: Create and configure firewall nat + when: "'present' in firewall_nat_state" + block: + # Create firewall nat + - name: Create firewall nat {{ item.id | default('@nat[-1]') }} + uci: + command: "add" + config: "firewall" + section: "{{ item.id | default('@nat[-1]') }}" + type: "nat" + + # Configure firewall nat + - name: Configure firewall nat {{ item.id | default('@nat[-1]') }} + uci: + command: "set" + config: "firewall" + section: "{{ item.id | default('@nat[-1]') }}" + type: "nat" + value: + name: "{{ item.name | default(omit) }}" + src: "{{ item.src | default(omit) }}" + src_ip: "{{ item.src_ip | default(omit) }}" + src_port: "{{ item.src_port | default(omit) }}" + dest_ip: "{{ item.dest_ip | default(omit) }}" + dest_port: "{{ item.dest_port | default(omit) }}" + snat_ip: "{{ item.snat_ip | default(omit) }}" + snat_port: "{{ item.snat_port | default(omit) }}" + target: "{{ item.target | default(omit) }}" + proto: "{{ item.proto | default([]) | join(' ') }}" + family: "{{ item.family | default(omit) }}" + mark: "{{ item.mark | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" diff --git a/roles/firewall/tasks/redirect.yml b/roles/firewall/tasks/redirect.yml new file mode 100644 index 0000000..a7ff253 --- /dev/null +++ b/roles/firewall/tasks/redirect.yml @@ -0,0 +1,51 @@ +--- +# Set state status for firewall redirect +- name: Set state status for firewall redirect {{ item.id | default('@redirect[-1]') }} + ansible.builtin.set_fact: + firewall_redirect_state: "{{ item.state | default('present') }}" + +# Delete firewall redirect +- name: Delete firewall redirect {{ item.id }} + when: "'absent' in firewall_redirect_state" + uci: + command: "absent" + config: "firewall" + section: "{{ item.id }}" + type: "redirect" + +# Create and configure firewall redirect +- name: Create and configure firewall redirect + when: "'present' in firewall_redirect_state" + block: + # Create firewall redirect + - name: Create firewall redirect {{ item.id | default('@redirect[-1]') }} + uci: + command: "add" + config: "firewall" + section: "{{ item.id | default('@redirect[-1]') }}" + type: "redirect" + + # Configure firewall redirect + - name: Configure firewall redirect {{ item.id | default('@redirect[-1]') }} + uci: + command: "set" + config: "firewall" + section: "{{ item.id | default('@redirect[-1]') }}" + type: "redirect" + value: + name: "{{ item.name | default(omit) }}" + src: "{{ item.src | default(omit) }}" + src_ip: "{{ item.src_ip | default(omit) }}" + src_port: "{{ item.src_port | default(omit) }}" + src_mac: "{{ item.src_mac | default(omit) }}" + src_dip: "{{ item.src_dip | default(omit) }}" + src_dport: "{{ item.src_dport | default(omit) }}" + dest: "{{ item.dest | default(omit) }}" + dest_ip: "{{ item.dest_ip | default(omit) }}" + dest_port: "{{ item.dest_port | default(omit) }}" + target: "{{ item.target | default(omit) }}" + proto: "{{ item.proto | default([]) | join(' ') }}" + family: "{{ item.family | default(omit) }}" + ipset: "{{ item.ipset | default(omit) }}" + mark: "{{ item.mark | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" diff --git a/roles/firewall/tasks/rule.yml b/roles/firewall/tasks/rule.yml new file mode 100644 index 0000000..1d73649 --- /dev/null +++ b/roles/firewall/tasks/rule.yml @@ -0,0 +1,50 @@ +--- +# Set state status for firewall rule +- name: Set state status for firewall rule {{ item.id | default('@rule[-1]') }} + ansible.builtin.set_fact: + firewall_rule_state: "{{ item.state | default('present') }}" + +# Delete firewall rule +- name: Delete firewall rule {{ item.id }} + when: "'absent' in firewall_rule_state" + uci: + command: "absent" + config: "firewall" + section: "{{ item.id }}" + type: "rule" + +# Create and configure firewall rule +- name: Create and configure firewall rule + when: "'present' in firewall_rule_state" + block: + # Create firewall rule + - name: Create firewall rule {{ item.id | default('@rule[-1]') }} + uci: + command: "add" + config: "firewall" + section: "{{ item.id | default('@rule[-1]') }}" + type: "rule" + + # Configure firewall rule + - name: Configure firewall rule {{ item.id | default('@rule[-1]') }} + uci: + command: "set" + config: "firewall" + section: "{{ item.id | default('@rule[-1]') }}" + type: "rule" + value: + name: "{{ item.name | default(omit) }}" + src: "{{ item.src | default(omit) }}" + src_ip: "{{ item.src_ip | default(omit) }}" + src_port: "{{ item.src_port | default([]) | join(' ') }}" + src_mac: "{{ item.src_mac | default(omit) }}" + dest: "{{ item.dest | default(omit) }}" + dest_ip: "{{ item.dest_ip | default(omit) }}" + dest_port: "{{ item.dest_port | default([]) | join(' ') }}" + target: "{{ item.target | default(omit) }}" + proto: "{{ item.proto | default([]) | join(' ') }}" + family: "{{ item.family | default(omit) }}" + ipset: "{{ item.ipset | default(omit) }}" + mark: "{{ item.mark | default(omit) }}" + set_mark: "{{ item.set_mark | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" diff --git a/roles/firewall/tasks/zone.yml b/roles/firewall/tasks/zone.yml new file mode 100644 index 0000000..d3bfbb8 --- /dev/null +++ b/roles/firewall/tasks/zone.yml @@ -0,0 +1,44 @@ +--- +# Set state status for firewall zone +- name: Set state status for firewall zone {{ item.id | default('@zone[-1]') }} + ansible.builtin.set_fact: + firewall_zone_state: "{{ item.state | default('present') }}" + +# Delete firewall zone +- name: Delete firewall zone {{ item.id }} + when: "'absent' in firewall_zone_state" + uci: + command: "absent" + config: "firewall" + section: "{{ item.id }}" + type: "zone" + +# Create and configure firewall zone +- name: Create and configure firewall zone + when: "'present' in firewall_zone_state" + block: + # Create firewall zone + - name: Create firewall zone {{ item.id | default('@zone[-1]') }} + uci: + command: "add" + config: "firewall" + section: "{{ item.id | default('@zone[-1]') }}" + type: "zone" + + # Configure firewall zone + - name: Configure firewall zone {{ item.id | default('@zone[-1]') }} + uci: + command: "set" + config: "firewall" + section: "{{ item.id | default('@zone[-1]') }}" + type: "zone" + value: + name: "{{ item.name | default(omit) }}" + network: "{{ item.network | default([]) | join(' ') }}" + masq: "{{ item.masq | default(omit) }}" + mtu_fix: "{{ item.mtu_fix | default(omit) }}" + input: "{{ item.input | default(omit) }}" + forward: "{{ item.forward | default(omit) }}" + output: "{{ item.output | default(omit) }}" + family: "{{ item.family | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" diff --git a/roles/gekmihesg.openwrt/.ansible-lint b/roles/gekmihesg.openwrt/.ansible-lint new file mode 100644 index 0000000..a46546e --- /dev/null +++ b/roles/gekmihesg.openwrt/.ansible-lint @@ -0,0 +1,4 @@ +--- +skip_list: + - fqcn + - name diff --git a/roles/gekmihesg.openwrt/.github/workflows/galaxy.yml b/roles/gekmihesg.openwrt/.github/workflows/galaxy.yml new file mode 100644 index 0000000..2bb35b8 --- /dev/null +++ b/roles/gekmihesg.openwrt/.github/workflows/galaxy.yml @@ -0,0 +1,16 @@ +--- +name: Release to Ansible Galaxy + +on: + push: + branches: [master] + workflow_dispatch: + +jobs: + galaxy: + runs-on: ubuntu-latest + steps: + - uses: robertdebock/galaxy-action@1.2.0 + with: + galaxy_api_key: ${{secrets.galaxy_api_key}} + git_branch: master diff --git a/roles/gekmihesg.openwrt/.gitignore b/roles/gekmihesg.openwrt/.gitignore new file mode 100644 index 0000000..0231c12 --- /dev/null +++ b/roles/gekmihesg.openwrt/.gitignore @@ -0,0 +1,3 @@ +.*.swp +*.pyc +Pipfile* diff --git a/roles/gekmihesg.openwrt/.yamllint b/roles/gekmihesg.openwrt/.yamllint new file mode 100644 index 0000000..49821ff --- /dev/null +++ b/roles/gekmihesg.openwrt/.yamllint @@ -0,0 +1,9 @@ +--- +extends: default + +rules: + line-length: disable + truthy: disable + comments-indentation: disable + +# code: language=yaml tabSize=2 diff --git a/roles/gekmihesg.openwrt/LICENSE b/roles/gekmihesg.openwrt/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/roles/gekmihesg.openwrt/LICENSE @@ -0,0 +1,674 @@ + 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 +. diff --git a/roles/gekmihesg.openwrt/README.md b/roles/gekmihesg.openwrt/README.md new file mode 100644 index 0000000..f4769a1 --- /dev/null +++ b/roles/gekmihesg.openwrt/README.md @@ -0,0 +1,178 @@ +Ansible Role: openwrt +===================== + +Manage OpenWRT and derivatives with Ansible but without Python. + +By putting a host in the inventory group `openwrt`, some modules are replaced with a shell version running on a standard OpenWRT installation, trying to preserve most of the original functionality. Hosts, that are not in this group are not affected. This makes it possible to have tasks mixed with OpenWRT and other platforms. +There are also some new, OpenWRT specific modules included (like `uci`). +**Not all argument combinations are tested!** Some cases have only been translated from Python for completeness' sake. + +Currently, the following modules have been implemented: + * command + * copy + * fetch (implicit) + * file + * lineinfile + * nohup (new) + * opkg + * ping + * service + * setup + * shell (implicit) + * slurp + * stat + * sysctl + * template (implicit) + * uci (new) + * wait\_for\_connection (implicit) + +To achieve all this, some monkey patching is involved (in case you wonder about the `vars_plugins`). + +Compatibility +------------- + +This role was tested successfully with: + * LEDE 17.01 (manually) + * OpenWRT 18.06 + * OpenWRT 19.07 + * OpenWRT 21.02 + * OpenWRT 22.03 + +Requirements +------------ + +Some modules optionally require a way to generate SHA1 hashes or encode data Base64. In case of Base64, there is a very slow `hexdump | awk` implementation included. For SHA1 there is no workaround. +The modules will try to find usable system commands for SHA1 (`sha1sum`, `openssl`) and Base64 (`base64`, `openssl`, workaround) when needed. If no usable commands are found, most things will still work, but the fetch module for example has to be run with `validate_checksum: no`, will always download the file and return `changed: yes`. +Therefore it is recommended to install `coreutils-sha1sum` and `coreutils-base64`, if the commands are not already provided by busybox. The role does that automatically by default (see below). + +Role Variables +-------------- + + openwrt_install_recommended_packages: + Checks for some commands and installs the corresponding packages if they are + missing. See requirements above. (default: yes) + + openwrt_scp_if_ssh: + Whether to use scp instead of sftp for OpenWRT systems. Value can be `yes`, + `no` or `smart`. Ansible defaults to `smart` but this role defaults to `yes` + because OpenWRT does not offer sftp by default. (default: yes) + + openwrt_remote_tmp: + Ansibles remote_tmp setting for OpenWRT systems. Defaults to /tmp to avoid + flash wear on target device. (default: /tmp) + + openwrt_wait_for_connection, openwrt_wait_for_connection_timeout: + Whether to wait for the host (default: yes) and how long (300) after a + network or wifi restart (see handlers). + + openwrt_ssh, openwrt_scp, openwrt_ssh_host, openwrt_ssh_user, openwrt_user_host: + Helper shortcuts to do things like + "command: {{ openwrt_scp }} {{ openwrt_user_host|quote }}:/etc/rc.local /tmp" + +Example Playbook +---------------- + +Inventory: + +```ini +[aps] +ap1.example.com +ap2.example.com +ap3.example.com + +[routers] +router1.example.com + +[openwrt:children] +aps +routers +``` + +Playbook: + +```yaml +- hosts: openwrt + roles: + - gekmihesg.openwrt + tasks: + - name: copy openwrt image + command: "{{ openwrt_scp }} image.bin {{ openwrt_user_host|quote }}:/tmp/sysupgrade.bin" + delegate_to: localhost + - name: start sysupgrade + nohup: + command: sysupgrade -q /tmp/sysupgrade.bin + - name: wait for reboot + wait_for_connection: + timeout: 300 + delay: 60 + - name: install mdns + opkg: + name: mdns + state: present + - name: enable and start mdns + service: + name: mdns + state: started + enabled: yes + - name: copy authorized keys + copy: + src: authorized_keys + dest: /etc/dropbear/authorized_keys + - name: revert pending changes + uci: + command: revert + - name: configure wifi device radio0 + uci: + command: set + key: wireless.radio0 + value: + phy: phy0 + type: mac80211 + hwmode: 11g + channel: auto + - name: configure wifi interface + uci: + command: section + config: wireless + type: wifi-iface + find_by: + device: radio0 + mode: ap + value: + ssid: MySSID + encryption: psk2+ccmp + key: very secret + - name: commit changes + uci: + command: commit + notify: reload wifi +``` + +Running the modules outside of a playbook is possible like this: + +```bash +$ export ANSIBLE_LIBRARY=~/.ansible/roles/gekmihesg.openwrt/library +$ export ANSIBLE_VARS_PLUGINS=~/.ansible/roles/gekmihesg.openwrt/vars_plugins +$ ansible -i openwrt-hosts -m setup all +``` + +License +------- + +GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +Developing +---------- + +Writing custom modules for this framework isn't to hard. The modules are wrapped into a wrapper script, that provides some common functions for parameter parsing, json handling, response generation, and some more. +All modules must match `openwrt_.sh`. If module\_name is not one of Ansibles core modules, there must also be a `.py`. This does not have to have any functionality (it may have some for non OpenWRT systems) and can contain the documentation. + +Make sure to install the `requirements.txt` packages in your virtual environment and, with the venv activated, run: + +```bash +$ molecule test +``` + +before commiting and submitting your PR. + +Writing tests for your new module is also highly recommended. diff --git a/roles/gekmihesg.openwrt/defaults/main.yml b/roles/gekmihesg.openwrt/defaults/main.yml new file mode 100644 index 0000000..5b8da82 --- /dev/null +++ b/roles/gekmihesg.openwrt/defaults/main.yml @@ -0,0 +1,17 @@ +--- +openwrt_install_recommended_packages: true + +openwrt_wait_for_connection: true +openwrt_wait_for_connection_timeout: 600 + +openwrt_ssh: "{{ ansible_ssh_executable | default('ssh') }} {{ ansible_ssh_common_args | default('') }} {{ ansible_ssh_extra_args | default('') }}" +openwrt_scp: "{{ ansible_scp_executable | default('scp') }} {{ ansible_scp_common_args | default('') }} {{ ansible_scp_extra_args | default('') }}" +openwrt_ssh_host: "{{ ansible_host | default(ansible_ssh_host | default(inventory_hostname)) }}" +openwrt_ssh_user: "{{ ansible_user | default(ansible_ssh_user | default('root')) }}" + +openwrt_scp_if_ssh: true +openwrt_ssh_transfer_method: "{{ 'smart' if openwrt_scp_if_ssh == 'smart' else openwrt_scp_if_ssh | ternary('scp', 'sftp') }}" +openwrt_ssh_use_tty: false +openwrt_remote_tmp: /tmp + +openwrt_remote_opkg_lists_dir: /tmp/opkg-lists diff --git a/roles/gekmihesg.openwrt/files/wrapper.sh b/roles/gekmihesg.openwrt/files/wrapper.sh new file mode 100644 index 0000000..1fcfbfc --- /dev/null +++ b/roles/gekmihesg.openwrt/files/wrapper.sh @@ -0,0 +1,356 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +[ $# -le 1 ] || { _script="$1"; shift; } +_params="$1" + +. /usr/share/libubox/jshn.sh + +_ANSIBLE_PARAMS=" + _ansible_version/s _ansible_no_log/b _ansible_module_name/s + _ansible_syslog_facility/s _ansible_socket/s _ansible_verbosity/i + _ansible_diff/b _ansible_debug/b _ansible_check_mode/b +" +FILE_PARAMS="group/s mode/s owner/s follow/b" +CHANGED="" +FACT_VARS="" +JSON_PREFIX="" +MESSAGE="" +NO_EXIT_JSON="" +PARAMS="" +RESPONSE_VARS="" +SKIPPED="" +SUPPORTS_CHECK_MODE="1" +WANT_JSON="" + +N=" +" +T=" " + +init() { :; } +main() { :; } +cleanup() { :; } + +_exit_add_vars() { + local _var _name _type _always _value _IFS + for _var; do + _IFS="$IFS"; IFS="/"; set -- $_var; IFS="$_IFS" + _var="$1"; _type="$(_map_type "$2")"; _always="$3" + _IFS="$IFS"; IFS="="; set -- $_var; IFS="$_IFS" + _name="$1"; _var="${2:-$_name}" + eval "_value=\"\$$_var\"" + [ -z "$_value" -a -z "$_always" ] || + eval "json_add_$_type \"\$_name\" \"\$_value\"" + done +} + +_init_done="" +_exit() { + local _rc="$?" + local _v _k + [ -z "$_init_done" ] || cleanup "$_rc" || : + [ -z "$NO_EXIT_JSON" ] || return $_rc + json_set_namespace result + json_add_boolean changed $([ -z "$CHANGED" ]; echo $?) + json_add_boolean failed $([ $_rc -eq 0 ]; echo $?) + [ -z "$SKIPPED" ] || json_add_boolean skipped 1 + [ -z "$MESSAGE" ] || json_add_string msg "$MESSAGE" + [ -z "$_init_done" ] || { + [ -z "$RESPONSE_VARS" ] || _exit_add_vars $RESPONSE_VARS + [ -z "$FACT_VARS" ] || { + json_add_object ansible_facts + _exit_add_vars "$FACT_VARS" + json_close_object + } + } + [ -z "$_ansible_diff" -o -z "$_diff_set" ] || { + json_add_object diff + json_add_string before "$_diff_before${_diff_before:+$N}" + json_add_string after "$_diff_after${_diff_after:+$N}" + [ -z "$_diff_before_header" ] || + json_add_string before_header "$_diff_before_header" + [ -z "$_diff_after_header" ] || + json_add_string after_header "$_diff_after_header" + json_close_object + } + echo; json_dump + json_cleanup + return $_rc +} +trap _exit EXIT + +_map_type() { + [ -n "$1" ] || { echo "string"; return 0; } + case "$1" in + any) echo "any";; + s|str|string) echo "string";; + i|int|integer) echo "int";; + b|bool|boolean) echo "boolean";; + f|d|float|double) echo "double";; + l|a|list|array) echo "array";; + o|h|obj|object|hash|map) echo "object";; + *) fail "unknown type: $1";; + esac +} + +_verify_value_type() { + local _value="$1" + local _type="$2" + case "$_type" in + int) printf "%d" "$_value" >/dev/null 2>&1 || return 1;; + double) printf "%f" "$_value" >/dev/null 2>&1 || return 1;; + boolean) + case "$_value" in + yes|true|True|1) _value="1";; + no|false|False|0) _value="";; + *) return 1;; + esac;; + esac + echo "$_value" +} + +_parse_legacy_params() { + local _var _type _required _default _alias + local _param _value _IFS + for _param in $PARAMS; do + eval "${_param%%[/=]*}=\"\"" + done + eval "$(cat "$_params")" || fail "could not parse params" + for _param in $PARAMS $_ANSIBLE_PARAMS; do + _value=""; _IFS="$IFS"; IFS="/"; set -- $_param; IFS="$_IFS" + _var="$1"; _type="$(_map_type "$2")"; _required="$3"; _default="$4" + _IFS="$IFS"; IFS="="; set -- $_var; IFS="$_IFS"; _var="$1" + for _alias; do + eval "_value=\"\$$_alias\"" + [ -z "$_value" ] || break + done + eval "export -- _orig_$_var=\"\$_value\"" + [ -z "$_value" ] && { + [ -z "$_required" ] || fail "$_var is required" + [ -z "$_default" ] || + _value="$(_verify_value_type "$_default" "$_type")" + } || { + _value="$(_verify_value_type "$_value" "$_type")" || + fail "$_var must be $_type" + } + eval "export -- $_var=\"\$_value\" _type_$_var=\"\$_type\"" + done + return 0 +} + +_parse_json_params() { + local _var _type _required _default _alias + local _param _value _found _is_type _IFS + json_set_namespace params + json_load "$(cat -- "$_params")" || fail "could not parse params" + for _param in $PARAMS $_ANSIBLE_PARAMS; do + _value=""; _IFS="$IFS"; IFS="/"; set -- $_param; IFS="$_IFS" + _var="$1"; _type="$(_map_type "$2")"; _required="$3"; _default="$4" + _IFS="$IFS"; IFS="="; set -- $_var; IFS="$_IFS"; _var="$1" + _is_type=""; _found="" + for _alias; do + json_get_type _is_type "$_alias" && + json_get_var _value "$_alias" || + continue + _found="1"; break + done + eval "export -- _orig_$_var=\"\$_value\" _defined_$_var=\"$_found\"" + [ -n "$_found" ] || { + [ -z "$_required" ] || fail "$_var is required" + [ -z "$_default" ] || + _value="$(_verify_value_type "$_default" "$_type")" + } + case "$_is_type" in + array|object) + [ "$_type" = "$_is_type" -o "$_type" = "any" ] || + fail "$_var must be $_type" + eval "export -- _type_${_var}=\"\$_is_type\"" + json_add_string "_$_var" "$_alias";; + *) + [ -z "$_found" ] || + _value="$(_verify_value_type "$_value" "$_type")" || + fail "$_var must be $_type" + eval "export -- $_var=\"\$_value\" _type_$_var=\"\$_type\"" + json_add_string "$_var" "$_value";; + esac + done + return 0 +} + +_parse_params() { + [ -n "$WANT_JSON" ] && _parse_json_params || _parse_legacy_params +} + +_support_check_mode() { + [ -n "$_ansible_check_mode" -a -z "$SUPPORTS_CHECK_MODE" ] || return 0 + SKIPPED="1" + MESSAGE="module does not support check mode" + exit 0 +} + +json_select_real() { + local real_var + json_get_var real_var "_$1" + json_select "$real_var" +} + +changed() { + CHANGED="1" +} + +fail() { + MESSAGE="$*" + exit 1 +} + +_result="" +try() { + [ $# -eq 1 ] && { + _result="$(eval "$1" 2>&1)" || fail "$*: $_result" + } || { + _result="$("$@" 2>&1)" || fail "$*: $_result" + } +} + +final() { + try "$@" + exit 0 +} + +_diff_set="" +_diff_before="" +_diff_after="" +_diff_before_header="" +_diff_after_header="" +set_diff() { + _diff_before="${1:-$_diff_before}" + _diff_after="${2:-$_diff_after}" + _diff_before_header="${3:-$_diff_before_header}" + _diff_after_header="${4:-$_diff_after_header}" + _diff_set="1" +} + +_get_file_attributes() { + local R="${2:+Ra}" + ls -l${R:-d} -- "$1" 2>/dev/null | md5 +} + +set_file_attributes() { + [ -z "$_ansible_check_mode" ] || return 0 + [ "$mode" != "False" ] || mode="" + [ -n "$owner" -o -n "$group" -o -n "$mode" ] || return 0 + local file="$1" + local R="${2:+-R }" + local result h + local before="$(_get_file_attributes "$@")" + ! result="$(printf "%04o" "$mode" 2>/dev/null)" || mode="$result" + [ -z "$follow" ] && h="-h " || h="" + [ -z "$owner" ] || result="$(chown $h$R"$owner" -- "$file" 2>&1)" || + fail "chown ($file) failed: $result" + [ -z "$group" ] || result="$(chgrp $h$R"$group" -- "$file" 2>&1)" || + fail "chgrp ($file) failed: $result" + [ -z "$follow" -a -h "$file" ] || + [ -z "$mode" ] || result="$(chmod $R"$mode" -- "$file" 2>&1)" || + fail "chmod ($file) failed: $result" + [ "$before" = "$(_get_file_attributes "$@")" ] || changed +} + +is_abs() { + [ "${1#/}" != "$1" ] +} + +abspath() { + local dir="$(dirname -- "$1")" + local file="$(basename -- "$1")" + local P="${2:+ -P}" + [ -d "$dir" ] && dir="$(cd -- "$dir" && pwd$P)" || + is_abs "$dir" || dir="$(pwd$P)/$dir" + echo "${dir:+$dir/}$file" +} + +realpath() { + local f="$(abspath "$1" x)" + local tmp + while [ -h "$f" ]; do + tmp="$(readlink -- "$f")" + is_abs "$tmp" || tmp="$(dirname -- "$f")/$tmp" + f="$(abspath "$tmp" x)" + done + echo "$f" +} + +backup_local() { + local src="$1" + local dest + [ ! -e "$src" ] || { + dest="$src.$$.$(date "+%Y-%m-%d@%H:%M:%S~")" + try cp -a -- "$src" "$dest" + echo "$dest" + } +} + +dgst() { + local alg="$1" + local cmd checksum + shift + case "$alg" in + sha1|sha224|sha256|sha384|sha512|md5) + cmd="${alg}sum" + ! type "$cmd" >/dev/null 2>&1 || { + checksum="$($cmd -- "$@")" + echo "${checksum%% *}" + return 0 + } + ! type openssl >/dev/null 2>&1 || { + checksum="$(openssl dgst -hex -$alg "$@")" + echo "${checksum##*= }" + return 0 + } + return 1;; + *) fail "Unknown checksum algorithm '$alg'.";; + esac +} + +md5() { + dgst md5 "$@" +} + +base64() { + ! which base64 >/dev/null 2>&1 || + { try command base64 "$1"; echo "$_result"; return 0; } + ! type openssl >/dev/null 2>&1 || + { try openssl base64 -in "$1"; echo "$_result"; return 0; } + hexdump -e '16/1 "%02x" "\n"' -- "$1" | awk ' + BEGIN { b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" } + { for(c=1; c<=length($0); c++) { + d=index("0123456789abcdef",substr($0,c,1)); + if(d--) { + for(b=1; b<=4; b++) { + o=o*2+int(d/8); d=(d*2)%16; + if(!(++obc%6)) { + line=line""substr(b64,o+1,1); o=0; + if(++rc>75) { print line; line=""; rc=0; } + } + } + } + } } + END { + if(obc%6) { + while(obc++%6) { o=o*2; } + line=line""substr(b64,o+1,1); + } + while(obc%8||obc%6) { if(!(++obc%6)) { line=line"="; } } + print line; + } + ' +} + +json_set_namespace result +json_init +. "$_script" +_parse_params +_support_check_mode +init || fail "module init failed" +_init_done="1" +main diff --git a/roles/gekmihesg.openwrt/handlers/main.yml b/roles/gekmihesg.openwrt/handlers/main.yml new file mode 100644 index 0000000..e8c0bca --- /dev/null +++ b/roles/gekmihesg.openwrt/handlers/main.yml @@ -0,0 +1,30 @@ +--- +- name: setup wifi + nohup: + command: /sbin/wifi + delay: 1 + when: "'openwrt' in group_names" + +- name: reload wifi + nohup: + command: /sbin/wifi reload + delay: 1 + when: "'openwrt' in group_names" + +- name: restart network + nohup: + command: /etc/init.d/network restart + delay: 1 + when: "'openwrt' in group_names" + +- name: wait for connection + wait_for_connection: + timeout: "{{ openwrt_wait_for_connection_timeout }}" + delay: 5 + when: + - "'openwrt' in group_names" + - openwrt_wait_for_connection + listen: + - setup wifi + - reload wifi + - restart network diff --git a/roles/gekmihesg.openwrt/library/nohup.py b/roles/gekmihesg.openwrt/library/nohup.py new file mode 100644 index 0000000..288c4a4 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/nohup.py @@ -0,0 +1,36 @@ +#!/usr/bin/python +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) +ANSIBLE_METADATA = { + 'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': '@gekmihesg' +} +DOCUMENTATION = ''' +--- +module: nohup +short_description: Starts a command in background and returns +description: + - The M(nohup) module start runs a command in a shell using OpenWRTs C(start-stop-daemon). + - The module will dispatch the command and return. +author: Markus Weippert (@gekmihesg) +options: + command: + description: + - command to execute. Execution takes place in a shell. + required: true + aliases: + - cmd + delay: + description: + - seconds to wait, before command is run. + default: 0 +note: + - This module does not support check_mode. +''' +EXAMPLES = ''' +- name: wait 3 seconds, then restart network + nohup: + command: /etc/init.d/network restart + delay: 3 +''' diff --git a/roles/gekmihesg.openwrt/library/openwrt_command.sh b/roles/gekmihesg.openwrt/library/openwrt_command.sh new file mode 100644 index 0000000..5c650e3 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_command.sh @@ -0,0 +1,63 @@ +#!/bin/sh +# Copyright (c) 2021 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + cmd=raw_params=_raw_params/str/r + uses_shell=_uses_shell/bool//false + chdir/str + executable/str + creates/str + removes/str +" +RESPONSE_VARS=" + start end delta cmd + stdout/str/a stderr/str/a rc/int/a +" +SUPPORTS_CHECK_MODE="" + +init() { + stdout="" + stderr="" + start="" + end="" + delta="" + rc="0" + [ -n "$executable" ] || executable="/bin/sh" + out="$(mktemp)" && err="$(mktemp)" +} + +main() { + local ts_start ts_end s_delta + [ -z "$chdir" ] || try cd "$chdir" + + [ -z "$creates" ] || ! ls -d -- $creates >/dev/null 2>/dev/null || { + stdout="skipped, since $creates exists"; exit 0 + } + [ -z "$removes" ] || ls -d -- $removes >/dev/null 2>/dev/null || { + stdout="skipped, since $removes does not exist"; exit 0 + } + + ts_start="$(date +%s)" + [ -z "$uses_shell" ] && { + echo "$cmd" | xargs sh -c 'exec "$@"' -- >"$out" 2>"$err"; rc=$?; : + } || { + "$executable" -c "$cmd" >"$out" 2>"$err"; rc=$?; : + } + ts_end="$(date +%s)" + s_delta=$((ts_end - ts_start)) + + start="$(date -d "@$ts_start" "+%Y-%m-%d %H:%M:%S").000000" + end="$(date -d "@$ts_end" "+%Y-%m-%d %H:%M:%S").000000" + delta="$(printf "%d:%.2d:%.2d.000000" \ + $((delta / 3600)) $((delta % 3600 / 60)) $((delta % 60)))" + stdout="$(cat "$out")" + stderr="$(cat "$err")" + changed + test "$rc" -eq 0 || fail "non-zero return code" + return 0 +} + +cleanup() { + rm -f -- "$out" "$err" +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_copy.sh b/roles/gekmihesg.openwrt/library/openwrt_copy.sh new file mode 100644 index 0000000..f5856c8 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_copy.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + backup/bool + dest/str/r + directory_mode/str + force=thirsty/bool//true + original_basename=_original_basename/str + src/str + validate/str + $FILE_PARAMS +" +RESPONSE_VARS="src dest md5sum=md5sum_src checksum backup_file" + +init() { + md5sum_src="" + checksum="" + backup_file="" +} + +main() { + local tmp _IFS + [ -e "$src" ] || fail "Source $src not found" + [ -r "$src" ] || fail "Source $src not readable" + [ ! -d "$src" ] || fail "Remote copy does not support recursive copy of directory: $src" + + checksum_src="$(dgst sha1 "$src")" || : + md5sum_src="$(md5 "$src")" + md5sum_dest="" + + [ -z "$original_basename" -o "${dest%/}" = "$dest" ] || { + dest="$dest/$original_basename" + tmp="$(dirname -- "$dest")" + [ -d "$tmp" ] || { + _IFS="$IFS"; IFS="/"; set -- $tmp; IFS="$_IFS" + tmp="$mode"; mode="$directory_mode" + local d + local p="" + for d; do + [ -n "$d" ] || continue + p="$p/$d" + [ ! -d "$p" ] || continue + try mkdir "$p" + set_file_attributes "$p" + done + mode="$tmp" + } + } + + [ ! -d "$dest" ] || { + dest="${dest%/}" + [ -z "$original_basename" ] && + dest="$dest/$(basename -- "$src")" || + dest="$dest/$original_basename" + } + + tmp="$(dirname -- "$dest")" + [ -e "$dest" ] && { + [ ! -h "$dest" -o -z "$follow" ] || dest="$(realpath "$dest")" + [ -n "$force" ] || fail "file already exists" + [ ! -r "$dest" ] || md5sum_dest="$(md5 "$dest")" + } || [ -d "$tmp" ] || fail "Destination directory $tmp does not exist" + [ -w "$tmp" ] || fail "Destination $tmp not writeable" + + [ "$md5sum_src" = "$md5sum_dest" -a ! -h "$dest" ] || { + [ -n "$_ansible_check_mode" ] || { + [ -z "$backup" ] || backup_file="$(backup_local "$dest")" + [ ! -h "$dest" ] || { rm -f -- "$dest"; touch -- "$dest"; } + [ -z "$validate" ] || { + [ "${validate/%s/}" != "$validate" ] || + fail "validate must contain %s: $validate" + tmp="$($(printf "$validate" "$src") 2>&1)" || + fail "failed to validate: $tmp" + } + try 'cat -- "$src" > "$dest"' + } + changed + } + + [ -n "$_ansible_check_mode" ] || set_file_attributes "$dest" +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_file.sh b/roles/gekmihesg.openwrt/library/openwrt_file.sh new file mode 100644 index 0000000..6ec21ba --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_file.sh @@ -0,0 +1,172 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + diff_peek/str + force/bool//false + original_basename=_original_basename/str + path=dest=name/str/r + recurse/bool//false + src/str + state/str + $FILE_PARAMS +" +RESPONSE_VARS="state path appears_binary/bool" + +init() { + appears_binary="" +} + +get_state() { + local state + state="$(ls -ld -- "$1" 2>/dev/null)" && { + case "${state:0:1}" in + l) state="link";; + d) state="directory";; + *) set -- $state; [ "$2" -gt 1 ] && + state="hard" || state="file";; + esac + echo "$state" + } || { echo "absent"; } +} + +get_inode() { + set -- $(ls -id -- "$1") + echo "$1" +} + +main() { + [ -z "$diff_peek" ] || { + appears_binary="0" + hexdump -e '16/1 " %02x" " \n"' -c 8192 -- "$path" 2>/dev/null | + grep -q " 00 " && appears_binary="1" || : + exit 0 + } + + prev_state="$(get_state "$path")" + [ -n "$state" ] || + case "$prev_state" in + absent) [ -z "$recurse" ] && state="file" || state="directory";; + *) state="$prev_state";; + esac + + [ -n "$src" -o "$state" != "link" -a "$state" != "hard" ] || { + [ "$state" != "link" -o -z "$follow" ] || + fail "src and dest are required for creating links" + src="$(realpath "$path")" + } + + [ "$state" = "link" -o "$state" = "absent" -o ! -d "$path" ] || { + basename="$original_basename" + [ -n "$basename" -o -z "$src" ] || basename="$(basename -- "$src")" + [ -z "$basename" ] || { + path="${path%/}/$basename" + prev_state="$(get_state "$path")" + } + } + + [ -z "$recurse" -o "$state" = "directory" ] || + fail "recurse options requires state to be directory" + + [ "$state" = "$prev_state" ] && state_change="" || state_change="y" + + case "$state" in + absent) + [ ! -e "$path" ] || changed + [ -n "$_ansible_check_mode" ] || + result="$(rm -rf -- "$path" 2>&1)" || + fail "removing failed: $result";; + file) + [ -z "$state_change" -o -z "$follow" -o "$prev_state" != "link" ] || { + path="$(realpath "$path")" + prev_state="$(get_state "$path")" + } + + [ "$prev_state" = "file" -o "$prev_state" = "hard" ] || + fail "file ($path) is $prev_state, cannot continue" + set_file_attributes "$path";; + directory) + [ -z "$follow" -o "$prev_state" != "link" ] || { + path="$(realpath "$path")" + prev_state="$(get_state "$path")" + } + + [ -e "$path" ] || changed + case "$prev_state" in + absent) + [ -n "$_ansible_check_mode" ] || { + oIFS="$IFS"; IFS="/"; set -- $path; IFS="$oIFS" + path="" + for p; do + [ -n "$p" ] || continue + path="$path/$p" + [ ! -e "$path" ] || continue + result="$(mkdir -p -- "$path" 2>&1)" || + fail "error creating $path: $result" + changed + set_file_attributes "$path" + done + };; + directory) set_file_attributes "$path" "$recurse";; + *) fail "$path already exists as a $prev_state";; + esac;; + link|hard) + is_abs "$src" && abssrc="$src" || { + [ ! -h "$path" -a -d "$path" ] && abs="$path/$src" || + abssrc="$(dirname "$path")/$src" + } + [ -e "$abssrc" ] && { + [ ! -d "$abssrc" -o "$state" != "hard" ] || + fail "src is a directory, cannot hard link $abssrc" + } || { + [ "$state" != "hard" ] || + fail "src file does not exist, cannot hard link $abssrc" + [ -n "$force" ] || + fail "src file does not exist, use force=yes if you want to link $abssrc" + } + + if [ "$prev_state" = "absent" ]; then + changed + elif [ "$prev_state" != "$state" -a -z "$force" ]; then + fail "refusing to convert between $prev_state and $state for $path" + elif [ "$prev_state" = "link" ]; then + [ "$state" = "link" -a "$(readlink "$path")" = "$src" ] || + changed + elif [ "$prev_state" = "hard" ]; then + [ "$state" = "hard" -a "$(get_inode "$path")" = "$(get_inode "$abssrc")" ] || { + [ -n "$force" ] || + fail "cannot link, different hard link exists at destination" + changed + } + elif [ "$prev_state" = "directory" ]; then + [ -z "$(find "$path" -mindepth 1 -maxdepth 1 2>/dev/null)" ] || + fail "the directory $path is not empty refusing to convert it" + changed + else + changed + fi + + [ -n "$_ansible_check_mode" ] || { + [ -z "$CHANGED" ] || { + [ "$state" = "hard" ] && flags="" || flags="-s" + [ "$prev_state" = "absent" ] || + result="$(rm -rf -- "$path" 2>&1)" || + fail "error replacing $path: $result" + result="$(ln $flags -- "$src" "$path" 2>&1)" || + fail "error while linking $path to $src: $result" + } + set_file_attributes "$path" + };; + touch) + [ -n "$follow" -a "$prev_state" = "link" ] || { + path="$(realpath "$path")" + [ -n "$_ansible_check_mode" ] || { + result="$(touch -- "$path" 2>&1)" || + fail "error touching $path: $result" + set_file_attributes "$path" + } + changed + };; + esac +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_lineinfile.sh b/roles/gekmihesg.openwrt/library/openwrt_lineinfile.sh new file mode 100644 index 0000000..a6fdb5a --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_lineinfile.sh @@ -0,0 +1,122 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + backrefs/bool//false + create/bool//false + insertafter/str + insertbefore/str + line=value/str + path=dest=destfile=name/str/r + regex=regexp/str + state/str//present + $FILE_PARAMS +" +RESPONSE_VARS="" + +escape_slash() { + echo "$1" | sed -e 's|^/|\\/|;:a;s|\([^\]\(\\\\\)*\)/|\1\\/|g;ta;q' +} + +escape_chars() { + echo "$1" | sed 's|['"${2:-}"'\]|\\&|g;q' +} + +get_last_match() { + echo "$2" | sed -nre "/$1/=" | sed '$!d' +} + +save_changes() { + [ -n "$_ansible_check_mode" -o -z "$CHANGED" ] || + echo "$1" > "$path" 2>/dev/null || + fail "path $path not writeable" +} + +line_present() { + local index old new mode tmp + + [ -f "$path" ] && { + old="$(cat "$path")" || fail "path $path not readable" + } || { + [ -n "$create" ] || fail "path $path does not exist" + [ -n "$_ansible_check_mode" ] || + mkdir -p "$(dirname "$path")" + old="" + } + + index="$(get_last_match "$line_match" "$old")" + [ -n "$index" ] && { + tmp="$(echo "$old" | sed -n "${index}{p;q}")" + [ -z "$backrefs" ] || line="$(echo "$tmp" | + sed -re "s/$line_match/$(escape_slash "$line")/")" + [ "$tmp" = "$line" ] || { + new="$(echo "$old" | sed "${index}c $(escape_chars "$line" | + sed 's|^\s|\\&|;q')")" + changed + } + } || [ -n "$backrefs" ] || { + [ -n "${insertafter#[EB]OF}" ] && { + index="$(get_last_match "$(escape_slash "$insertafter")" "$old")" + mode="a" + } || [ -z "${insertbefore#BOF}" ] || { + index="$(get_last_match "$(escape_slash "$insertbefore")" "$old")" + mode="i" + } + [ -n "$index" ] && { + new="$(echo "$old" | sed "$index$mode $(escape_chars "$line" | + sed 's|^\s|\\&|;q')")" + } || { + [ "$insertafter" = "BOF" -o "$insertbefore" = "BOF" ] && + new="$line$N$old" || { + tmp="$(echo "$old" | sed '${/^$/d}')" + new="$tmp${tmp:+$N}$line" + } + } + changed + } + + [ -z "$CHANGED" ] || { + [ -z "$_ansible_diff" ] || set_diff "$old" "$new" "$path" "$path" + [ -n "$_ansible_check_mode" ] || save_changes "$new" + } +} + +line_absent() { + local index new old + + [ -f "$path" ] || return 0 + + old="$(cat "$path")" || fail "path $path not readable" + index="$(get_last_match "$line_match" "$old")" + [ -z "$index" ] || { + new="$(echo "$old" | sed -re "/$line_match/d")" + changed + } + + [ -z "$_ansible_diff" ] || set_diff "$old" "$new" "$path" "$path" + [ -n "$_ansible_check_mode" -o -z "$CHANGED" ] || save_changes "$new" +} + +main() { + case "$state" in + absent|present) :;; + *) fail "state must be absent or present";; + esac + [ -n "$regex" ] && + line_match="$(escape_slash "$regex")" || + line_match="^$(escape_chars "$line" '/.[*^$()+?{|')\$" + [ ! -d "$file" ] || fail "path $path is a directory" + case "$state" in + present) + [ -z "$backrefs" -o -n "$regex" ] || + fail "regexp is required with backrefs" + [ -n "$line" ] || fail "line is required with state present" + line_present;; + absent) + [ -n "$line" -o -n "$regex" ] || + fail "line or regexp is required with state absent" + line_absent;; + esac + set_file_attributes "$path" "" "y" +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_nohup.sh b/roles/gekmihesg.openwrt/library/openwrt_nohup.sh new file mode 100644 index 0000000..8ae48de --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_nohup.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS="command=cmd/str/r delay/int//0" +SUPPORTS_CHECK_MODE="" + +main() { + try /sbin/start-stop-daemon -Sbqp /dev/null -x /bin/sh -- -c \ + "sleep $delay; $command" + changed +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_opkg.sh b/roles/gekmihesg.openwrt/library/openwrt_opkg.sh new file mode 100644 index 0000000..5e98879 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_opkg.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + name=pkg/str/r + state/str//present + force/str + update_cache/bool + autoremove/bool + nodeps/bool +" + +query_package() { + [ -n "$(opkg status "$1")" ] +} + +install_packages() { + local _IFS pkg + _IFS="$IFS"; IFS=","; set -- $name; IFS="$_IFS" + for pkg; do + ! query_package "$pkg" || continue + [ -n "$_ansible_check_mode" ] || { + try opkg install$force $nodeps "$pkg" + query_package "$pkg" || fail "failed to install $pkg: $_result" + } + changed + done +} + +remove_packages() { + local _IFS pkg + _IFS="$IFS"; IFS=","; set -- $name; IFS="$_IFS" + for pkg; do + query_package "$pkg" || continue + [ -n "$_ansible_check_mode" ] || { + try opkg remove$force $autoremove $nodeps "$pkg" + ! query_package "$pkg" || fail "failed to remove $pkg: $_result" + } + changed + done +} + +main() { + case "$state" in + present|installed|absent|removed) :;; + *) fail "state must be present or absent";; + esac + [ -z "$force" ] || { + case "$force" in + depends|maintainer|reinstall|overwrite|downgrade|space) :;; + postinstall|remove|checksum|removal-of-dependent-packages) :;; + *) fail "unknown force option";; + esac + force=" --force-$force" + } + [ -z "$autoremove" ] || { + autoremove=" --autoremove" + } + + [ -z "$nodeps" ] || { + nodeps=" --nodeps" + } + + [ -z "$update_cache" -o -n "$_ansible_check_mode" ] || try opkg update + case "$state" in + present|installed) install_packages;; + absent|removed) remove_packages;; + esac +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_ping.sh b/roles/gekmihesg.openwrt/library/openwrt_ping.sh new file mode 100644 index 0000000..2c6ae70 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_ping.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS="data/any" +RESPONSE_VARS="ping data" + +__exit() { + [ -z "$NO_EXIT_JSON" ] || return $? + echo -n "{\"ping\":\"$ping\"" + [ -z "$data" ] || echo -n ",\"data\":\"${data//\"/\\\"}\"" + echo "}" +} + +main() { + [ "$data" != "crash" ] || + { NO_EXIT_JSON="y"; echo "boom"; exit 1; } + ping="pong" +} + +[ -n "$_ANSIBLE_PARAMS" ] || { + . "$1" + trap __exit EXIT + main +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_service.sh b/roles/gekmihesg.openwrt/library/openwrt_service.sh new file mode 100644 index 0000000..d20e937 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_service.sh @@ -0,0 +1,63 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + enabled/bool + name/str/r + pattern/str + state/str +" +RESPONSE_VARS="name enabled state" + +is_running() { + [ -z "$pattern" ] || { pgrep -f "$pattern" >/dev/null 2>&1; return $?; } + "$init_script" running >/dev/null 2>&1 +} + +is_enabled() { + ! "$init_script" enabled >/dev/null 2>&1 || echo 1 +} + +set_enabled() { + local status result + status="$(is_enabled)" + [ "$enabled" = "$status" ] || { + changed + [ -n "$_ansible_check_mode" ] || { + [ -n "$enabled" ] && action="enable" || action="disable" + result="$("$init_script" "$action" 2>&1)" + status="$(is_enabled)" + [ "$enabled" = "$status" ] || + fail "Unable to $action service $name: $result" + } + } + case "$status" in + 1) enabled="yes";; + *) enabled="no";; + esac +} + +set_state() { + local action result running + is_running && running="y" || running="" + case "$state" in + started) [ -n "$running" ] || action="start";; + stopped) [ -z "$running" ] || action="stop";; + restarted|reloaded) action="${state%ed}";; + *) fail "Unknown action $action";; + esac + [ -z "$action" ] || { + changed + [ -n "$_ansible_check_mode" ] || + result="$("$init_script" "$action" 2>&1)" || + fail "Unable to $action service $name: $result" + } +} + +main() { + init_script="/etc/init.d/$name" + [ -f "$init_script" ] || fail "service $name does not exist" + [ -z "$_orig_enabled" ] || set_enabled + [ -z "$state" ] || set_state +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_setup.sh b/roles/gekmihesg.openwrt/library/openwrt_setup.sh new file mode 100644 index 0000000..1ead6d1 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_setup.sh @@ -0,0 +1,67 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +NO_EXIT_JSON="1" + +add_ubus_fact() { + set -- ${1//!/ } + ubus list "$2" > /dev/null 2>&1 || return + local json="$($ubus call "$2" "$3" 2>/dev/null)" + echo -n "$seperator\"$1\":$json" + seperator="," +} + +main() { + ubus="/bin/ubus" + seperator="," + echo '{"changed":false,"ansible_facts":' + dist="OpenWRT" + dist_version="NA" + dist_release="NA" + test -f /etc/openwrt_release && { + . /etc/openwrt_release + dist="${DISTRIB_ID:-$dist}" + dist_version="${DISTRIB_RELEASE:-$dist_version}" + dist_release="${DISTRIB_CODENAME:-$dist_release}" + } || test ! -f /etc/os-release || { + . /etc/os-release + dist="${NAME:-$dist}" + dist_version="${VERSION_ID:-$dist_version}" + } + dist_major="${dist_version%%.*}" + json_set_namespace facts + json_init + json_add_string ansible_hostname "$(cat /proc/sys/kernel/hostname)" + json_add_string ansible_distribution "$dist" + json_add_string ansible_distribution_major_version "$dist_major" + json_add_string ansible_distribution_release "$dist_release" + json_add_string ansible_distribution_version "$dist_version" + json_add_string ansible_os_family OpenWRT + json_add_boolean ansible_is_chroot "$([ -r /proc/1/root/. ] && + { [ / -ef /proc/1/root/. ]; echo $?; } || + { [ "$(ls -di / | awk '{print $1}')" -eq 2 ]; echo $?; } + )" + dist_facts="$(json_dump)" + json_cleanup + json_set_namespace result + echo "${dist_facts%\}*}" + for fact in \ + info!system!info \ + devices!network.device!status \ + services!service!list \ + board!system!board \ + wireless!network.wireless!status \ + ; do + add_ubus_fact "openwrt_$fact" + done + echo "$seperator"'"openwrt_interfaces":{' + seperator="" + for net in $($ubus list); do + [ "${net#network.interface.}" = "$net" ] || + add_ubus_fact "${net##*.}!$net!status" + done + echo '}}}' +} + +[ -n "$_ANSIBLE_PARAMS" ] || main diff --git a/roles/gekmihesg.openwrt/library/openwrt_slurp.sh b/roles/gekmihesg.openwrt/library/openwrt_slurp.sh new file mode 100644 index 0000000..c31f764 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_slurp.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + src=path/str/r +" +RESPONSE_VARS="source=src content encoding" + +init() { + content="" + encoding="" +} + +main() { + [ -e "$src" ] || fail "file not found: $src" + [ -r "$src" ] || fail "file not readable: $src" + try base64 "$src" + content="$_result" + encoding="base64" +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_stat.sh b/roles/gekmihesg.openwrt/library/openwrt_stat.sh new file mode 100644 index 0000000..6e741e5 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_stat.sh @@ -0,0 +1,137 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + checksum_algorithm=checksum_algo=checksum/str//sha1 + get_checksum/bool//true + get_md5/bool//true + get_mime/bool//true + path/str/r +" +RESPONSE_VARS=" + charset/str + checksum/str + ctime/int + dev/int + executable/bool + exists/bool + gid/int + gr_name/str + inode/int + isblk/bool + ischr/bool + isdir/bool + isfifo/bool + isgid/bool + islnk/bool + isreg/bool + issock/bool + isuid/bool + lnk_source/str + md5/str + mime_type/str + mode/str + mtime/int + nlink/int + pw_name/str + readable/bool + rgrp/bool + roth/bool + rusr/bool + size/int + uid/int + wgrp/bool + woth/bool + writeable/bool + wusr/bool + xgrp/bool + xoth/bool + xusr/bool +" + +init() { + local var + for var in $RESPONSE_VARS; do eval "${var%%/*}=\"\""; done + RESPONSE_VARS="path/str $RESPONSE_VARS" +} + +parse_priv() { + local priv="$1" + local part="$2" + local octal="0" + [ -z "${priv#-??}" ] || { eval "r$part=\"1\""; octal=$((octal + 4)); } + [ -z "${priv#?-?}" ] || { eval "w$part=\"1\""; octal=$((octal + 2)); } + [ -z "${priv#??[-ST]}" ] || { eval "x$part=\"1\""; octal=$((octal + 1)); } + mode="$mode$octal" + [ -z "${priv#??[-x]}" ] || high=$((high + high_mod)) + high_mod=$((high_mod / 2)) +} + +main() { + local var privs _IFS tmp + [ ! -h "$path" -o -z "$follow" ] || { + lnk_source="$path" + path="$(readlink -f "$path")" || : + } + [ -n "$path" -a -e "$path" -o -h "$path" ] || { + exists="0" + return 0 + } + for var in $RESPONSE_VARS; do + _IFS="$IFS"; IFS="/"; set -- $var; IFS="$_IFS" + [ "${2#b}" = "$2" ] || eval "$1=\"0\"" + done + exists="1" + charset="unknown" + mime_type="unknown" + set -- $(ls -lid "$path") + inode="$1" + privs="$2" + nlink="$3" + pw_name="$4" + gr_name="$5" + size="$6" + set -- $(ls -lidn "$path") + uid="$4" + gid="$5" + [ ! -x "$path" ] || executable="1" + [ ! -r "$path" ] || readable="1" + [ ! -w "$path" ] || writeable="1" + case "$privs" in + d*) isdir="1";; + l*) islnk="1";; + s*) issock="1";; + c*) ischr="1";; + b*) isblk="1";; + p*) isfifo="1";; + -*) + [ "$readable" != "1" ] || { + [ -z "$get_md5" ] || md5="$(md5 "$path")" + [ -z "$get_checksum" ] || + checksum="$(dgst "$checksum_algorithm" "$path")" || + [ "$checksum_algorithm" = "sha1" ] || + fail "Could not hash file '$path' with algorithm '$checksum_algorithm'." + } + isreg="1";; + esac + mtime="$(date -r "$path" +%s)" + ctime="$mtime" + atime="$mtime" + [ "$(id -u)" -ne "$uid" ] || isuid="1" + [ "$(id -g)" -ne "$gid" ] || isgid="1" + high="0"; high_mod=4 + privs="${privs#?}"; parse_priv "${privs%??????}" usr + privs="${privs#???}"; parse_priv "${privs%???}" grp + privs="${privs#???}"; parse_priv "$privs" oth + mode="$high$mode" +} + +cleanup() { + json_set_namespace result + json_add_object stat + _exit_add_vars $RESPONSE_VARS + json_close_object + json_set_namespace params + RESPONSE_VARS="" +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_sysctl.sh b/roles/gekmihesg.openwrt/library/openwrt_sysctl.sh new file mode 100644 index 0000000..6b908c2 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_sysctl.sh @@ -0,0 +1,90 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +PARAMS=" + ignore_errors=ignoreerrors/bool + name=key/str/r + reload/bool//true + state/str//present + sysctl_file/str + sysctl_set/bool//false + value=val/str +" +RESPONSE_VARS="name value" + +init() { + sysctl="/sbin/sysctl" + default_sysctl_file="/etc/sysctl.conf" + tmp_file="" +} + +sysctl_set() { + local result + [ "$(echo $($sysctl -n "$name"))" = "$value" ] || { + changed + [ -n "$_ansible_check_mode" ] || + result="$($sysctl -w "$name=$value" 2>/dev/null)" || + fail "failed to set $name to $value: $result" + } +} + +sysctl_write() { + local found line v k + tmp_file="$(mktemp)" + while read line; do + set -- $line + [ -z "$1" -o "${1:0:1}" = "#" -o "${1/=/}" = "$1" ] || { + k="${1%%=*}" + [ "$k" != "$name" ] || { + found="1" + [ "$state" = "present" ] || { changed; continue; } + v="${1#*=}" + shift; while [ $# -ge 1 ]; do + [ "${1:0:1}" != "#" ] || break; v="$v $1"; shift + done + [ "$v" = "$value" ] || { + line="$k=$value${1:+ $*}" + changed + } + } + } + echo "$line" >> "$tmp_file" + done < "$sysctl_file" + [ "$state" != "present" -o -n "$found" ] || { + echo "$name=$value" >> "$tmp_file" + changed + } +} + +main() { + local result + [ -n "$sysctl_file" ] || sysctl_file="$default_sysctl_file" + case "$state" in + absent) :;; + present) + [ -n "$value" ] || + fail "value must be given with state present";; + *) fail "state must be present or absent";; + esac + + [ -w "$sysctl_file" ] || fail "sysctl file $sysctl_file not writeable" + [ "$state" = "present" ] || ignore_errors="y" + [ -n "$ignore_errors" -a -z "$sysctl_set" ] || + [ $($sysctl "$name" 2>/dev/null | wc -l) -eq 1 ] || + fail "unknown sysctl key $name" + + [ -z "$sysctl_set" ] || sysctl_set + sysctl_write + + [ -z "$CHANGED" -o -n "$_ansible_check_mode" ] || { + cat "$tmp_file" > "$sysctl_file" + [ -z "$reload" -o "$state" != "present" ] || + result="$($sysctl -p "$sysctl_file" 2>&1)" || + fail "failed to reload: $result" + } +} + +cleanup() { + [ -z "$tmp_file" ] || rm -f "$tmp_file" +} diff --git a/roles/gekmihesg.openwrt/library/openwrt_uci.sh b/roles/gekmihesg.openwrt/library/openwrt_uci.sh new file mode 100644 index 0000000..086e355 --- /dev/null +++ b/roles/gekmihesg.openwrt/library/openwrt_uci.sh @@ -0,0 +1,384 @@ +#!/bin/sh +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) + +WANT_JSON="1" +PARAMS=" + autocommit/bool + command=cmd/str + config/str + find=find_by=search/any + keep_keys=keep/any + key/str + merge/bool//false + name/str + option/str + replace/bool//false + section/str + set_find/bool//true + type/str + unique/bool//false + value/any +" +RESPONSE_VARS="result=_result command config section option" + +init() { + state_path="" + [ -z "$_ansible_check_mode" ] || state_path="$(mktemp -d)" || + fail "could not create state path" + changes="$(uci_change_hash)" + case "$_type_keep_keys" in + object) fail "keep_keys must be list or string";; + array) json_get_values keep_keys "$_keep_keys" || :;; + esac + [ -z "$key" ] && + key="${config:+$config${section:+.$section${option:+.$option}}}" || + { oIFS="$IFS"; IFS="."; set -- $key; IFS="$oIFS" + config="$1"; section="$2"; option="$3"; } + [ -z "$_ansible_diff" -o -z "$config" ] || + set_diff "$(uci export "$config")" + [ -n "$command" ] || { [ -z "$value" ] && command="get" || command="set"; } +} + +uci() { + [ -z "$state_path" ] || set -- -P "$state_path" "$@" + command uci "$@" +} + +uci_change_hash() { + uci changes | md5 +} + +uci_result_do() { + json_set_namespace result + "$@" + json_set_namespace params +} + +uci_get_safe() { + local tmp opts + while [ "${1#-}" != "$1" ]; do opts="$opts $1"; shift; done + tmp="$(uci $opts show "$1")" || return $? + echo "${tmp#*=}" +} + +uci_check_type() { + local key="$1"; local type="$2"; local t + t="$(uci -q get "$key")" || return 1 + [ -n "$type" -a "$t" != "$type" ] || return 0 + fail "$key exists with $t instead of $type" +} + +uci_compare_list() { + local k="${1:-$key}" + local match="1" + local keys values v i + json_get_keys keys + ! values="$(uci_get_safe -q "$k")" || { + eval "set -- $values" + for i in $keys; do + json_get_var v "$i" + [ $# -gt 0 -a "$v" = "$1" ] || { match=""; break; } + shift + done + [ $# -eq 0 ] || match="" + [ -z "$match" ] || return 0 + } + return 1 +} + +uci_add() { + section="${section:-$value}" + [ -n "$name" -o -z "$type" ] || name="$section" + type="${type:-$section}" + [ -n "$type" ] || fail "type required for $command" + [ -n "$name" ] && { + uci_check_type "$config.$name" "$type" || { + try uci add "$config" "$type" + try uci rename "$config.$_result=$name" + } + } || try uci add "$config" "$type" +} + +uci_set_list() { + local k="${1:-$key}" + local keys v i + ! uci_compare_list "$k" || return 0 + uci -q delete "$k" || : + json_get_keys keys + for i in $keys; do + json_get_var v "$i" + try uci add_list "$k=$v" + done +} + +uci_set_dict() { + local keys k v t + json_get_keys keys + keep_keys="$keep_keys $keys" + for k in $keys; do + json_get_type t "$k" + case "$t" in + array) + json_select "$k" + uci_set_list "$key.$k" + json_select ..;; + object) fail "cannot set $k to dict";; + *) + json_get_var v "$k" + try uci set "$key.$k=$v";; + esac + done +} + +uci_set() { + local var="${1:-value}" + local var_type + eval "var_type=\"\$_type_$var\"" + [ -z "$option" ] || keep_keys="$keep_keys $option" + case "$var_type" in + array) + [ -n "$config" -a -n "$section" -a -n "$option" ] || + fail "config, section and option required for $command" + json_select_real "$var" + uci_set_list + json_select ..;; + object) + [ -n "$config" -a -n "$section" -a -z "$option" ] || + fail "config and section but not option required for $command" + json_select_real "$var" + uci_set_dict + json_select ..;; + *) try "uci set \"\$key=\$$var\"";; + esac +} + +uci_get() { + local entry + try uci get "$key" + eval "set -- $(uci_get_safe -q "$key")" + json_set_namespace result + json_add_array result_list + for entry; do json_add_string . "$entry"; done + json_close_array + json_set_namespace params +} + +uci_find() { + local keys i c v k tmp + case "$_type_find" in + array|object) + [ -n "$config" -a -n "$type" ] || + fail "config and type required for $command" + json_select_real find + json_get_keys keys;; + *) + [ -n "$config" -a -n "$type" ] && + [ -n "$option" -o "$command" = find_all ] || + fail "config, type and option required for $command";; + esac + [ "$command" != "find_all" ] || uci_result_do json_add_array result + type="${type:-$section}" + section=""; i=0 + while [ -n "$(uci -q get "$config.@$type[$i]")" ]; do + c="@$type[$((i++))]" + case "$_type_find" in + array) + [ -z "$option" ] && { + for k in $keys; do + json_get_var v "$k" + uci -q get "$config.$c.$v" >/dev/null || continue 2 + done + } || { + uci_compare_list "$config.$c.$option" || continue + };; + object) + for k in $keys; do + json_get_type tmp "$k" + case "$tmp" in + array) + json_select "$k" + uci_compare_list "$config.$c.$k" && + tmp="1" || tmp="" + json_select .. + [ -n "$tmp" ] || continue 2;; + object) + fail "cannot compare $k with dict";; + *) + json_get_var v "$k" + tmp="$(uci -q get "$config.$c.$k")" && + [ "$tmp" = "$v" ] || continue 2 + esac + done;; + *) + [ -z "$option" ] || { + v="$(uci -q get "$config.$c.$option")" && + [ -z "$find" -o "$find" = "$v" ] || continue + };; + esac + [ "$command" = "find_all" ] || { section="$c"; break; } + uci_result_do json_add_string . "$c" + done + case "$_type_find" in + array|object) json_select ..;; + esac + case "$command" in + find_all) + uci_result_do json_close_array + _result="";; + *) + _result="$section" + [ -n "$section" ] && return 0 || return 1;; + esac +} + +uci_ensure() { + local keys k v + [ -n "$name" -o -z "$type" ] || name="$section" + type="${type:-$section}" + [ -n "$config" -a -n "$type" ] || + fail "config, type and name required for $command" + [ -n "$name" ] && uci_check_type "$config.$name" "$type" || { + [ "$_type_find" = "object" -o -n "$option" ] && uci_find && { + [ -z "$name" ] || try uci rename "$config.$section=$name" + } || { + [ "$command" = absent ] && return 0 || uci_add + } + } + section="${name:-$_result}" + key="$config.$section${option:+.$option}" + [ "$command" = "absent" ] && { + [ -z "$_defined_value" ] && + { uci -q delete "$key" || :; } || + case "$_type_value" in + array|object) + json_select_real value + json_get_keys keys + for k in $keys; do + json_get_var v "$k" + case "$_type_value" in + array) uci -q delete "$config.$section.$v";; + object) uci -q delete "$config.$section.$k=$v";; + esac + done + json_select ..;; + *) uci -q delete "$config.$section.$value";; + esac + return 0 + } + [ -z "$set_find" -o "$_type_find" != "object" -a -z "$option" ] || { + uci_set find + [ "$_type_value" != "object" ] || { + key="$config.$section" + option="" + } + } + [ -z "$_defined_value" ] || uci_set + _result="$section" +} + +uci_cleanup_section() { + case "$command" in + set|ensure|section) :;; + *) return 0;; + esac + local k v + [ -n "$replace" -a -n "$config" -a -n "$section" ] || return 0 + for k in $(uci -q show "$config.$section" | + sed -n 's/^..*\...*\.\([^.][^.]*\)=.*$/\1/p') + do + for v in $keep_keys; do + [ "$k" != "$v" ] || continue 2 + done + uci -q delete "$config.$section.$k" + done +} + +uci_revert() { + [ -z "$key" ] && rm -f -- "/tmp/.uci"/* 2>/dev/null || uci revert "$key" +} + +uci_autocommit() { + [ -n "$autocommit" ] || return 0 + case "$command" in + commit|revert) return 0;; + esac + [ "$1" -eq 0 ] && { + [ -n "$config" ] && uci commit "$config" || uci commit + } || uci_revert +} + +main() { + case "$command" in + batch|import) + [ -n "$value" ] || fail "value required for $command";; + add_list|del_list|rename|reorder) + [ -n "$key" -a -n "$value" ] || + fail "key and value required for $command";; + add|get|delete|ensure|absent) + [ -n "$key" ] || fail "key required for $command";; + esac + case "$command" in + batch) + echo "$value" | final uci $command;; + export|changes|show|commit) + local cmd="final uci $command" + [ -z "$key" ] && $cmd || $cmd "$key";; + import) + local cmd="final uci ${merge:+-m }$command" + [ -z "$key" ] && echo "$value" | $cmd || + echo "$value" | $cmd "$key";; + add) + uci_add; exit 0;; + add_list) + [ -z "$unique" ] || { + eval "set -- $(uci_get_safe -q "$key")" + for entry; do [ "$entry" = "$value" ] && exit 0; done + } + final uci add_list "$key=$value";; + del_list|reorder) + final uci $command "$key=$value";; + get) + uci_get; exit 0;; + delete) + final uci $command "$key${value:+=$value}";; + rename) + final uci $command "$key=${name:-$value}";; + revert) + final uci_revert;; + set) + uci_set; exit 0;; + find|find_all) + uci_find; exit $?;; + ensure|section) + uci_ensure; exit 0;; + absent) + [ -n "$_defined_find" ] || { + uci -q delete "$key${value:+=$value}"; exit 0 + } + uci_ensure; exit 0;; + *) fail "unknown command: $command";; + esac +} + +cleanup() { + local ec="$1" + [ "$ec" -ne 0 ] || uci_cleanup_section + [ "$changes" = "$(uci_change_hash)" ] || { + changed + [ "$_ansible_verbosity" -lt 2 ] || { + local _IFS line + _IFS="$IFS"; IFS="$N"; set -- $(uci changes); IFS="$_IFS" + json_set_namespace result + json_add_array changes + for line; do json_add_string . "$line"; done + json_close_array + json_set_namespace params + } + uci_autocommit "$ec" + } + [ -z "$_ansible_diff" -o -z "$config" ] || + set_diff "" "$(uci export "$config")" + [ -z "$_ansible_check_mode" -o -z "$state_path" -o ! -d "$state_path" ] || + rm -rf "$state_path" +} diff --git a/roles/gekmihesg.openwrt/library/uci.py b/roles/gekmihesg.openwrt/library/uci.py new file mode 100644 index 0000000..574ab0b --- /dev/null +++ b/roles/gekmihesg.openwrt/library/uci.py @@ -0,0 +1,190 @@ +#!/usr/bin/python +# Copyright (c) 2017 Markus Weippert +# GNU General Public License v3.0 (see https://www.gnu.org/licenses/gpl-3.0.txt) +ANSIBLE_METADATA = { + 'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': '@gekmihesg' +} +DOCUMENTATION = ''' +--- +module: uci +short_description: Controls OpenWRTs UCI +description: + - The M(uci) module is a Ansible wrapper for OpenWRTs C(uci). + - It supports all the command line functionality plus some extra commands. +author: Markus Weippert (@gekmihesg) +options: + autocommit: + description: + - Whether to automatically commit changes + type: bool + default: false + command: + description: + - Command to execute. Execution takes place in a shell. + default: set if value else get + choices: + - absent + - add + - add_list + - batch + - changes + - commit + - del_list + - export + - find + - get + - import + - rename + - reorder + - revert + - section + - set + - show + aliases: + - cmd + config: + description: + - Config part of the I(key). + default: extracted from I(key) + find: + description: + - Value(s) to match sections against. + - Option value to find if I(option) is set. May be list. + - Dict of options/values if I(option) is not set. Values may be list. + - Lists are compared in order. + - Required when I(command=find) or I(command=section) + aliases: + - find_by + - search + keep_keys: + description: + - Space seperated list or list of keys not in I(value) or I(find) to + keep when I(replace=yes). + aliases: + - keep + key: + description: + - The C(uci) key to operate on. + - Takes precedence over I(config), I(section) and I(option) + default: I(config).I(section).I(option) + merge: + description: + - Whether to merge or replace when I(command=import) + type: bool + default: false + name: + description: + - New name when I(command=rename) or I(command=add). + - Desired name when I(command=section). If a matching section is + found it is renamed, if not it is created with that name. + option: + description: + - Option part of the I(key). + default: extracted from I(key) + replace: + description: + - When I(command=set) or I(command=section), whether to delete all + options not mentioned in I(keep_keys), I(value) or find when + I(set_find=true). + type: bool + default: false + section: + description: + - Section part of the I(key). + default: extracted from I(key) + set_find: + description: + - When I(command=section) whether to set the options used to search + a matching section in the newly created section when no match was + found. + type: bool + default: false + type: + description: + - Section type for I(command=section), I(command=find) and + I(command=add). + default: I(section) + unique: + description: + - When I(command=add_list), whether to add the value if it is already + contained in the list. + type: bool + default: false + value: + description: + - The value for various commands. +''' +EXAMPLES = ''' +# Find a section of type wifi-iface with matching name or matching attributes. +# If not found create it and set the attributes from find. +# Unconditionally set the attributes from value and delete all other options. +- uci: + command: section + config: wireless + type: wifi-iface + name: ap0 + find: + device: radio0 + ssid: My SSID + value: + encryption: none + replace: yes + +# Find a matching wifi-iface and delete it. +- uci: + command: absent + config: wireless + type: wifi-iface + find: + ssid: My SSID broken + +# Find a matching wifi-iface and delete the options key and encryption. +- uci: + command: absent + config: wireless + type: wifi-iface + find: + ssid: My SSID public + value: + - key + - encryption + +# commit changes and notify +- uci: cmd=commit + notify: restart wifi +''' +RETURN = ''' +result: + description: output of the C(uci) command + returned: always + type: string + sample: cfg12523 +result_list: + description: the list form of result + returned: when I(command=get) + type: list of string + sample: ['0.pool.ntp.org','1.pool.ntp.org'] +config: + description: config part of I(key) + returned: when given + type: string + sample: wireless +section: + description: section part of I(key) + returned: when given + type: string + sample: '@wifi-iface[0]' +option: + description: option part of I(key) + returned: when given + type: string + sample: ssid +command: + description: command executed + returned: always + type: string + sample: section +''' + diff --git a/roles/gekmihesg.openwrt/meta/.galaxy_install_info b/roles/gekmihesg.openwrt/meta/.galaxy_install_info new file mode 100644 index 0000000..b95b4ad --- /dev/null +++ b/roles/gekmihesg.openwrt/meta/.galaxy_install_info @@ -0,0 +1,2 @@ +install_date: 'Sun 07 Jul 2024 02:07:36 PM ' +version: master diff --git a/roles/gekmihesg.openwrt/meta/main.yml b/roles/gekmihesg.openwrt/meta/main.yml new file mode 100644 index 0000000..279bdfd --- /dev/null +++ b/roles/gekmihesg.openwrt/meta/main.yml @@ -0,0 +1,27 @@ +--- +galaxy_info: + namespace: gekmihesg + role_name: openwrt + author: Markus Weippert + description: Manage OpenWRT without python + issue_tracker_url: https://github.com/gekmihesg/ansible-openwrt/issues + license: GPL-3.0 + min_ansible_version: '2.4' + platforms: + - name: GenericLinux + # platforms: + # - name: LEDE + # versions: + # - 17.01 + # - name: OpenWRT + # versions: + # - 15.05 + galaxy_tags: + - busybox + - lede + - openwrt + - shell + - uci +dependencies: [] + +# code: language=yaml tabSize=2 diff --git a/roles/gekmihesg.openwrt/molecule/default/collections.yml b/roles/gekmihesg.openwrt/molecule/default/collections.yml new file mode 100644 index 0000000..8dd5161 --- /dev/null +++ b/roles/gekmihesg.openwrt/molecule/default/collections.yml @@ -0,0 +1,3 @@ +--- +collections: + - community.general diff --git a/roles/gekmihesg.openwrt/molecule/default/converge.yml b/roles/gekmihesg.openwrt/molecule/default/converge.yml new file mode 100644 index 0000000..15cf310 --- /dev/null +++ b/roles/gekmihesg.openwrt/molecule/default/converge.yml @@ -0,0 +1,11 @@ +--- +- name: Converge + hosts: all + gather_facts: false + tasks: + - name: "Create /var/lock" + ansible.builtin.raw: "mkdir -p /var/lock" + changed_when: false + - name: "Include gekmihesg.openwrt" + ansible.builtin.include_role: + name: "gekmihesg.openwrt" diff --git a/roles/gekmihesg.openwrt/molecule/default/molecule.yml b/roles/gekmihesg.openwrt/molecule/default/molecule.yml new file mode 100644 index 0000000..7cc7d20 --- /dev/null +++ b/roles/gekmihesg.openwrt/molecule/default/molecule.yml @@ -0,0 +1,45 @@ +--- +dependency: + name: galaxy + requirements-file: collections.yml +driver: + name: docker +platforms: + - name: instance_latest + image: openwrtorg/rootfs:latest + command: sleep infinity + pre_build_image: true + groups: + - openwrt + - name: instance_x86_64-22.03.2 + image: openwrtorg/rootfs:x86_64-22.03.2 + command: sleep infinity + pre_build_image: true + groups: + - openwrt + - name: instance_x86_64-21.02.5 + image: openwrtorg/rootfs:x86_64-21.02.5 + command: sleep infinity + pre_build_image: true + groups: + - openwrt + - name: instance_x86_64-19.07.10 + image: openwrtorg/rootfs:x86_64-19.07.10 + command: "sh -c 'while true; do sleep 10000; done'" + pre_build_image: true + groups: + - openwrt + - name: instance_x86-64-18.06.6 + image: openwrtorg/rootfs:x86-64-18.06.6 + command: "sh -c 'while true; do sleep 10000; done'" + pre_build_image: true + groups: + - openwrt +provisioner: + name: ansible +verifier: + name: ansible +lint: | + set -e + yamllint . + ansible-lint . diff --git a/roles/gekmihesg.openwrt/molecule/default/verify.yml b/roles/gekmihesg.openwrt/molecule/default/verify.yml new file mode 100644 index 0000000..322fa62 --- /dev/null +++ b/roles/gekmihesg.openwrt/molecule/default/verify.yml @@ -0,0 +1,49 @@ +--- +# This is an example playbook to execute Ansible tests. + +- name: Verify + hosts: all + gather_facts: false + roles: + - gekmihesg.openwrt + vars: + openwrt_install_recommended_packages: false + tasks: + - name: Retrieve /etc/os-release + slurp: + src: /etc/os-release + register: os_release_slurp + + - name: Populate fact os_release + ansible.builtin.set_fact: + os_release: >- + {{ + _os_release_dict.keys() | map('lower') + | zip(_os_release_dict.values()) + | items2dict(key_name=0, value_name=1) + }} + vars: + _os_release_lines: "{{ os_release_slurp['content'] | b64decode | split('\n') }}" + _os_release_split: "{{ _os_release_lines | map('regex_search', '^([A-Z_0-9]+)=\"(.*)\"$', '\\1', '\\2') | reject('none') }}" + _os_release_dict: "{{ dict(_os_release_split) }}" + + - name: Run simple command + command: + cmd: "echo Holy canole, it\\'s {{ os_release.name }}" + register: holy_canole + + - name: Assert Canole + ansible.builtin.assert: + that: + - holy_canole.stdout.startswith("Holy canole, it's OpenWrt") + + - name: Read UCI + uci: + command: get + key: network.wan.ifname + register: uci_wan_ifname + + - name: Assert WAN network interface name (UCI) + ansible.builtin.assert: + that: + - uci_wan_ifname.result == "eth0" diff --git a/roles/gekmihesg.openwrt/requirements.txt b/roles/gekmihesg.openwrt/requirements.txt new file mode 100644 index 0000000..7ef2e96 --- /dev/null +++ b/roles/gekmihesg.openwrt/requirements.txt @@ -0,0 +1,4 @@ +molecule[docker,lint] +docker +yamllint +ansible-lint diff --git a/roles/gekmihesg.openwrt/tasks/main.yml b/roles/gekmihesg.openwrt/tasks/main.yml new file mode 100644 index 0000000..13180c5 --- /dev/null +++ b/roles/gekmihesg.openwrt/tasks/main.yml @@ -0,0 +1,20 @@ +--- +- name: pin defaults + set_fact: + openwrt_ssh: "{{ openwrt_ssh }}" + openwrt_scp: "{{ openwrt_scp }}" + openwrt_ssh_user: "{{ openwrt_ssh_user }}" + openwrt_ssh_host: "{{ openwrt_ssh_host }}" + openwrt_user_host: "{{ openwrt_ssh_user | quote }}@{{ openwrt_ssh_host | quote }}" + ansible_ssh_transfer_method: "{{ openwrt_ssh_transfer_method }}" + ansible_ssh_use_tty: "{{ openwrt_ssh_use_tty }}" + ansible_scp_if_ssh: "{{ openwrt_scp_if_ssh }}" + ansible_remote_tmp: "{{ openwrt_remote_tmp }}" + when: "'openwrt' in group_names" + tags: always + +- name: install recommended packages + include_tasks: packages.yml + when: + - "'openwrt' in group_names" + - "openwrt_install_recommended_packages | bool" diff --git a/roles/gekmihesg.openwrt/tasks/package.yml b/roles/gekmihesg.openwrt/tasks/package.yml new file mode 100644 index 0000000..6c7c88a --- /dev/null +++ b/roles/gekmihesg.openwrt/tasks/package.yml @@ -0,0 +1,12 @@ +--- +- name: "check for command {{ item.key }}" + command: "which {{ item.key | quote }}" + register: _package + check_mode: false + changed_when: false + failed_when: false + +- name: "install {{ item.value }} to provide {{ item.key }}" + opkg: + name: "{{ item.value }}" + when: _package.rc diff --git a/roles/gekmihesg.openwrt/tasks/packages.yml b/roles/gekmihesg.openwrt/tasks/packages.yml new file mode 100644 index 0000000..2eaaeee --- /dev/null +++ b/roles/gekmihesg.openwrt/tasks/packages.yml @@ -0,0 +1,40 @@ +--- +- name: check whether opkg caches need update + stat: + path: "{{ openwrt_remote_opkg_lists_dir }}" + register: _opkg_lists + +- name: get current system time + command: date +%s + register: _epoch + check_mode: false + changed_when: false + when: _opkg_lists.stat.exists + +- name: update opkg cache + opkg: + name: opkg + update_cache: true + register: _update + when: not _opkg_lists.stat.exists or + _epoch.stdout|int - _opkg_lists.stat.mtime > 86400 + failed_when: not _opkg_lists.stat.exists and _update.failed + changed_when: not _update.failed + +- name: check for openssl + command: which openssl + register: _openssl + check_mode: false + changed_when: false + failed_when: false + +- include_tasks: package.yml + with_dict: + base64: coreutils-base64 + md5sum: coreutils-md5sum + sha1sum: coreutils-sha1sum + when: _openssl.rc + +- name: avoid re-checking of packages + set_fact: + openwrt_install_recommended_packages: false diff --git a/roles/gekmihesg.openwrt/vars_plugins/monkeypatch.py b/roles/gekmihesg.openwrt/vars_plugins/monkeypatch.py new file mode 100644 index 0000000..d16c326 --- /dev/null +++ b/roles/gekmihesg.openwrt/vars_plugins/monkeypatch.py @@ -0,0 +1,51 @@ +import os +from ansible.plugins.action import ActionBase +from ansible.plugins.vars import BaseVarsPlugin +try: + from ansible.utils.collection_loader import resource_from_fqcr +except ImportError: + resource_from_fqcr = lambda x: x + +def _fix_module_args(module_args): + for k, v in module_args.items(): + if v is None: + module_args[k] = False + elif isinstance(v, dict): + _fix_module_args(v) + elif isinstance(v, list): + module_args[k] = [False if i is None else i for i in v] + +def _configure_module(self, module_name, module_args, task_vars=None): + if task_vars is None: + task_vars = dict() + if self._task.delegate_to: + real_vars = task_vars.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()) + else: + real_vars = task_vars + if real_vars.get('ansible_connection', '') not in ('local',) and \ + 'openwrt' in real_vars.get('group_names', list()): + leaf_module_name = resource_from_fqcr(module_name) + openwrt_module = self._shared_loader_obj.module_loader.find_plugin('openwrt_' + leaf_module_name, '.sh') + if openwrt_module: + module_name = os.path.basename(openwrt_module)[:-3] + else: + openwrt_module = None + (module_style, module_shebang, module_data, module_path) = \ + self.__configure_module(module_name, module_args, task_vars) + if openwrt_module: + with open(_wrapper_file, 'r') as f: + wrapper_data = f.read() + if type(module_data) is bytes: + module_data = module_data.decode() + module_data = wrapper_data.replace('\n. "$_script"\n', '\n' + module_data + '\n') + _fix_module_args(module_args) + return (module_style, module_shebang, module_data, module_path) + +if ActionBase._configure_module != _configure_module: + _wrapper_file = os.path.join(os.path.dirname(__file__), '..', 'files', 'wrapper.sh') + ActionBase.__configure_module = ActionBase._configure_module + ActionBase._configure_module = _configure_module + +class VarsModule(BaseVarsPlugin): + def get_vars(*args, **kwargs): + return dict() diff --git a/roles/mesh11sd/README.md b/roles/mesh11sd/README.md new file mode 100644 index 0000000..41b1a9c --- /dev/null +++ b/roles/mesh11sd/README.md @@ -0,0 +1,80 @@ +# `flyoverhead.openwrt.mesh` + +OpenWRT `mesh` configuration +- create and configure mesh network + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `mesh_enabled` | Enable mesh configuration | `required` | `boolean` | `false` | +| `ath10k_ct_fix` | Enable [ath10k-ct drivers fix](https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#wireless_hardware_support) | `optional` | `boolean` | `false` | +| `non_mesh_pkgs` | List of non-mesh wpad packages installed by default | `required` | `list` | `["wpad-mini", "wpad-basic", "wpad-basic-wolfssl", "wpad-basic-openssl", "wpad-basic-mbedtls"]` | +| `mesh_pkgs` | List of mesh wpad packages to be installed | `required` | `list` | `["wpad-mesh-wolfssl", "mesh11sd"]` | +| `mesh11sd_interfaces` | List of [wireless interfaces](https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#the_wireless_uci_config_file) to be configured as mesh nodes | | `list of dictionaries` | | +|  `id` | Unique interface ID | `mandatory` | `string` | `mesh` | +|  `name` | Unique interface name | `mandatory` | `string` | `mesh` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `device` | Radio device associated with the interface | `mandatory` | `string` | `radio0` | +|  `network` | List of networks associated with the interface | `mandatory` | `list` | `["lan"]` | +|  `mode` | Wireless interface operation mode | `required` | `string` | `mesh` | +|  `disabled` | Disable wireless network | `optional` | `boolean` | `0` | +|  `mesh_id` | ID of the mesh network (as defined in IEEE 802.11s) to join wireless interface to | `required` | `string` | `example_mesh_id` | +|  `encryption` | Wireless encryption method | `required` | `string` | `sae` | +|  `key` | Passphrase for pre-shared key | `required` | `string` | `password` | +| `mesh_settings` | List of [mesh parameters and options](https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#mesh11sd_-_setting_parameters_and_options) | | `list of dictionaries` | | +|  `mesh_fwding` | Forward packets to peer mesh nodes | `required` | `boolean` | `1` | +|  `mesh_rssi_threshold` | Minimum received signal strength from a peer meshnode for a connection to be established | `optional` | `integer` | `-80` | +|  `mesh_gate_announcements` | Enable gate announcements | `optional` | `boolean` | `1` | +|  `mesh_hwmp_rootmode` | Mesh convergence level (`0`, `1`, `2`, `3` or `4`) | `required` | `integer` | `2` | +|  `mesh_max_peer_links` | Maximum number of peer nodes that can connect | `optional` | `integer` | `150` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.mesh +``` + +## Example Vars + +```yaml +mesh_enabled: true +ath10k_ct_fix: true +mesh11sd_interfaces: + - id: "mesh0" + name: "mesh0" + state: "present" + device: "radio0" + network: ["lan"] + mode: "mesh" + mesh_id: "openwrt_mesh" + encryption: "sae" + key: "passphrase" +mesh11sd_settings: + mesh_fwding: "1" + mesh_rssi_threshold: "-80" + mesh_gate_announcements: "1" + mesh_hwmp_rootmode: "3" + mesh_max_peer_links: "150" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s +- https://openwrt.org/docs/guide-user/network/wifi/mesh/mesh11sd diff --git a/roles/mesh11sd/defaults/main.yml b/roles/mesh11sd/defaults/main.yml new file mode 100644 index 0000000..3316ca4 --- /dev/null +++ b/roles/mesh11sd/defaults/main.yml @@ -0,0 +1,41 @@ +--- +# Deafult mesh status +mesh_enabled: false + +# Enable ath10k-ct drivers fix +# https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#wireless_hardware_support +ath10k_ct_fix: false + +# Non-mesh wpad packages +non_mesh_pkgs: + [ + "wpad-mini", + "wpad-basic", + "wpad-basic-wolfssl", + "wpad-basic-openssl", + "wpad-basic-mbedtls", + ] + +# Mesh wpad packages +mesh11sd_pkgs: ["wpad-mesh-wolfssl", "mesh11sd"] + +# Mesh interface configuration +mesh11sd_interfaces: + - id: "" + name: "" + state: "" + device: "" + network: [] + mode: "" + disabled: "" + mesh_id: "" + encryption: "" + key: "" + +# Mesh interface additional settings +mesh11sd_settings: + mesh_fwding: "" + mesh_rssi_threshold: "" + mesh_gate_announcements: "" + mesh_hwmp_rootmode: "" + mesh_max_peer_links: "" diff --git a/roles/mesh11sd/handlers/main.yml b/roles/mesh11sd/handlers/main.yml new file mode 100644 index 0000000..933a224 --- /dev/null +++ b/roles/mesh11sd/handlers/main.yml @@ -0,0 +1,8 @@ +--- +# Reload wireless service +- name: Reload wireless + ansible.builtin.command: + cmd: "/sbin/wifi {{ item }}" + register: reload_wifi_status + changed_when: reload_wifi_status != 0 + loop: ["config", "reload"] diff --git a/roles/mesh11sd/meta/main.yml b/roles/mesh11sd/meta/main.yml new file mode 100644 index 0000000..c9e036f --- /dev/null +++ b/roles/mesh11sd/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure mesh + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "mesh"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/mesh11sd/tasks/ath10k.yml b/roles/mesh11sd/tasks/ath10k.yml new file mode 100644 index 0000000..b80f312 --- /dev/null +++ b/roles/mesh11sd/tasks/ath10k.yml @@ -0,0 +1,50 @@ +--- +# Check current driver release +- name: Check current ath10k firmware release + ansible.bultin.command: + cmd: "opkg list-installed | grep ath10k-firmware | awk '{print $1}'" + register: ath10k_firmware_current_release + +# Enable reinstall if installed driver contain *-ct postfix +- name: Enable replacement of current driver + ansible.builtin.set_fact: + replace_ath10k_ct_driver: true + when: "'-ct' in ath10k_firmware_current_release.stdout" + +# Replace current driver with new one +- name: Replace ath10k-ct firmware and module + when: replace_ath10k_ct_driver + block: + # Get current ath10k module package name + - name: Check current ath10k module release + ansible.builtin.command: + cmd: "opkg list-installed | grep kmod-ath10k | awk '{print $1}'" + register: ath10k_kmod_current_release + + # Set current ath10k module package name fact + - name: Set current ath10k module release fact + ansible.builtin.set_fact: + ath10k_kmod_pkg_name: "{{ ath10k_kmod_current_release.stdout }}" + + # Set current driver release name fact + - name: Set current driver release name fact + ansible.builtin.set_fact: + ath10k_driver_pkg_name: "{{ ath10k_firmware_current_release.stdout }}" + + # Remove current driver + - name: Remove current driver + opkg: + name: "{{ item }}" + state: "absent" + loop: ["{{ ath10k_kmod_pkg_name }}", "{{ ath10k_driver_pkg_name }}"] + + # Install new driver + - name: Install new driver + opkg: + name: "{{ item }}" + state: "present" + loop: + [ + "{{ ath10k_kmod_pkg_name | regex_replace('-?ct', '') }}", + "{{ ath10k_driver_pkg_name | regex_replace('-?ct', '') }}", + ] diff --git a/roles/mesh11sd/tasks/configure.yml b/roles/mesh11sd/tasks/configure.yml new file mode 100644 index 0000000..fb8cadc --- /dev/null +++ b/roles/mesh11sd/tasks/configure.yml @@ -0,0 +1,14 @@ +--- +# Configure mesh parameters +- name: Configure mesh parameters + uci: + command: "set" + config: "mesh11sd" + section: "mesh_params" + type: "mesh11sd" + value: + mesh_fwding: "{{ mesh11sd_settings.mesh_fwding | default(omit) }}" + mesh_rssi_threshold: "{{ mesh11sd_settings.mesh_rssi_threshold | default(omit) }}" + mesh_gate_announcements: "{{ mesh11sd_settings.mesh_gate_announcements | default(omit) }}" + mesh_hwmp_rootmode: "{{ mesh11sd_settings.mesh_hwmp_rootmode | default(omit) }}" + mesh_max_peer_links: "{{ mesh11sd_settings.mesh_max_peer_links | default(omit) }}" diff --git a/roles/mesh11sd/tasks/main.yml b/roles/mesh11sd/tasks/main.yml new file mode 100644 index 0000000..e333110 --- /dev/null +++ b/roles/mesh11sd/tasks/main.yml @@ -0,0 +1,31 @@ +--- +# Fix ath10k drivers +# https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s#wireless_hardware_support +- name: Fix ath10k drivers + ansible.builtin.include_tasks: ath10k.yml + when: mesh_enabled and ath10k_ct_fix + +# Install required packages +- name: Install required packages + ansible.builtin.include_tasks: prepare.yml + when: mesh_enabled + +# Create mesh interface +- name: Create mesh interface + ansible.builtin.include_role: + name: "wireless" + vars: + wireless_interfaces: "{{ mesh11sd_interfaces | default([]) }}" + when: mesh_enabled + +# Configure mesh interface +- name: Configure mesh interface + ansible.builtin.include_tasks: configure.yml + when: mesh_enabled + +# Apply changes and reload wireless service +- name: Apply changes and reload wireless + when: mesh_enabled + uci: + command: commit + notify: Reload wireless diff --git a/roles/mesh11sd/tasks/prepare.yml b/roles/mesh11sd/tasks/prepare.yml new file mode 100644 index 0000000..bc562bf --- /dev/null +++ b/roles/mesh11sd/tasks/prepare.yml @@ -0,0 +1,20 @@ +--- +# Remove non-mesh wpad packages +- name: Remove non-mesh wpad packages + opkg: + name: "{{ item }}" + state: "absent" + loop: "{{ non_mesh_pkgs }}" + +# Update opkg cache +- name: Update opkg cache + ansible.builtin.command: + cmd: "opkg update" + changed_when: false + +# Install mesh packages +- name: Install mesh packages + opkg: + name: "{{ item }}" + state: "present" + loop: "{{ mesh11sd_pkgs }}" diff --git a/roles/network/README.md b/roles/network/README.md new file mode 100644 index 0000000..84336d9 --- /dev/null +++ b/roles/network/README.md @@ -0,0 +1,123 @@ +# `flyoverhead.openwrt.network` + +OpenWRT `network` configuration +- create/delete/configure network devices +- create/delete/configure network interfaces + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `network_globals` | [Global network configuration options](https://openwrt.org/docs/guide-user/base-system/basic-networking#global_section) | | `dictionary` | | +|  `network_ula_prefix` | IPv6 ULA prefix (`IPv6-prefix` or `auto`) | `optional` | `string` | `auto` | +|  `network_packet_steering` | Enable or disable usage of every CPU to handle packet traffic | `optional` | `boolean` | `0` | +| `network_devices` | List of [network devices](https://openwrt.org/docs/guide-user/base-system/basic-networking#device_sections) | | `list of dictionaries` | | +|  `id` | Unique device ID | `required` | `string` | `guest_dev` | +|  `name` | Unique device name | `mandatory` | `string` | `br-guest` | +|  `state` | Device status (`present` or `absent`) | `required` | `string` | `present` | +|  `type` | Device type (for bridge devices only) | `optional` | `string` | `bridge` | +|  `ports` | List of ports associated with bridge device | `required` | `list` | `["eth0", "eth1"]` | +|  `stp` | Enable the Spanning Tree Protocol (STP) which prevents network loops | `optional` | `boolean` | `0` | +|  `igmp_snooping` | Enable IGMP snooping | `optional` | `boolean` | `0` | +|  `ipv6` | Enable IPv6 support | `optional` | `boolean` | `0` | +| `network_interfaces` | List of [network interfaces](https://openwrt.org/docs/guide-user/base-system/|  `igmp_snooping` | Enable IGMP snooping | `optional` | `boolean` | `0` | +|  `id` | Unique interface ID | `mandatory` | `string` | `guest` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `device` | Network device associated with the interface (for newly created interface) | `optional` | `string` | `guest_dev` | +|  `proto` | Interface protocol | `mandatory` | `string` | `static` | +|  `auto` | Specifies whether to bring up interface on boot | `optional` | `boolean` | `0` for proto `none`, else `1` | +|  `force_link` | Specifies whether ip address, route, and optionally gateway are assigned to the interface regardless of the link being active ('1') or only after the link has become active ('0') | `optional` | `boolean` | `1` for protocol `static`, else `0` | +|  `ipaddr` | IP address | `required` | `string` | `192.168.1.1` | +|  `netmask` | Netmask | `required` | `string` | `255.255.255.0` | +|  `gateway` | Default gateway | `optional` | `string` | `192.168.1.1` | +|  `peerdns` | Use peer/DHCP provided DNS server(s) | `optional` | `boolean` | `1` | +|  `dns` | Override peer/DHCP provided DNS server(s) | `optional` | `list` | `["1.1.1.1", "8.8.8.8"]` | +|  `username` | Username for PAP/CHAP authentication | `optional` | `string` | `username` | +|  `password` | Password for PAP/CHAP authentication | `optional` | `string` | `password` | +|  `mtu` | MTU value | `optional` | `integer` | `1532` | +|  `ipv6` | Enable IPv6 support | `optional` | `boolean` | `0` | +|  `delegate` | Enable prefix delegation | `optional` | `boolean` | `0` | +|  `ip6assign` | Assign a part of given length of every public IPv6-prefix to this interface | `optional` | `integer` | `60` | +| `network_rules` | List of [network rules](https://openwrt.org/docs/guide-user/network/routing/ip_rules) | | (`list of dictionaries`) | | +|  `id` | Unique rule ID | `mandatory` | `string` | `rule_example` | +|  `state` | Rule status (`present` or `absent`) | `required` | `string` | `present` | +|  `mark` | fwmark and optionally its mask to match | `optional` | `string` | `0xFF` | +|  `in` | Incoming logical interface name | `optional` | `string` | `lan` | +|  `out` | Outgoing logical interface name | `optional` | `string` | `wan` | +|  `src` | Source subnet to match (CIDR notation) | `optional` | `string` | `172.16.0.0/16` | +|  `dest` | Destination subnet to match (CIDR notation) | `optional` | `string` | `192.168.1.0/24` | +|  `invert` | Invert the meaning of the match options | `optional` | `boolean` | `0` | +|  `priority` | Priority of the IP rule | `optional` | `integer` | `100` | +|  `lookup` | Protocol ID to use for the route declared in `/etc/iproute2/rt_tables` | `mandatory` | `string` | `main` | +|  `goto` | Rule to jump to specified by its `priority` value | `optional` | `integer` | `99` | +|  `action` | Routing action (`prohibit`, `unreachable`, `blackhole` or `throw`) | `optional` | `string` | `prohibit` | +|  `disabled` | Disable the rule | `optional` | `boolean` | `0` | +| `network_routes` | List of [network routes](https://openwrt.org/docs/guide-user/network/routing/routes_configuration) | | (`list of dictionaries`) | | +|  `id` | Unique route ID | `mandatory` | `string` | `route_example` | +|  `state` | Route status (`present` or `absent`) | `required` | `string` | `present` | +|  `interface` | Logical interface name of the parent (or master) interface the route belongs to | `mandatory` | `string` | `lan` | +|  `target` | Network address | `mandatory` | `string` | `172.16.0.10` | +|  `netmask` | Route netmask | `optional` | `string` | `255.255.255.255` | +|  `gateway` | Network gateway | `optional` | `string` | `172.16.0.1` | +|  `table` | Table ID to use for the route | `optional` | `string` | `main` | +|  `source` | Route source address in source-address dependent routes | `optional` | `boolean` | `0` | +|  `type` | Routing type (`unicast`, `local`, `broadcast`, `multicast`, `unreachable`, `prohibit`, `blackhole` or `anycast`) | `optional` | `string` | `unicast` | +|  `proto` | Protocol ID to use for the route declared in `/etc/iproute2/rt_tables` | `mandatory` | `string` | `main` | +|  `disabled` | Disable the rule | `optional` | `boolean` | `0` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.network +``` + +## Example Vars + +```yaml +network_devices: + - id: "iot_dev" + name: "br-iot" + state: "present" + type: "bridge" +network_interfaces: + - id: "lan" + proto: "static" + ipaddr: "192.168.1.1" + netmask: "255.255.255.0" + - id: "wan" + proto: "dhcp" + - id: "iot" + state: "present" + device: "br-iot" + proto: "static" + auto: "1" + force_link: "1" + ipaddr: "192.168.2.1" + netmask: "255.255.255.0" + - id: "wan6" + state: "absent" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/base-system/basic-networking +- https://openwrt.org/docs/guide-user/network/ucicheatsheet +- https://openwrt.org/docs/guide-user/network/routing/ip_rules +- https://openwrt.org/docs/guide-user/network/routing/routes_configuration +- https://openwrt.org/docs/guide-user/network/wan/wan_interface_protocols diff --git a/roles/network/defaults/main.yml b/roles/network/defaults/main.yml new file mode 100644 index 0000000..3a01c42 --- /dev/null +++ b/roles/network/defaults/main.yml @@ -0,0 +1,74 @@ +--- +# globals section +# network_globals: +# network_ula_prefix: "" +# network_packet_steering: "" + +# #switch section +# network_switch_vlans: +# - id: "" +# vlan: "" +# vid: "" +# ports: "" +# description: "" + +# device section +network_devices: + - id: "" + name: "" + state: "" + type: "" + ports: [] + stp: "" + igmp_snooping: "" + ipv6: "" + +# interface section +network_interfaces: + - id: "" + state: "" + device: "" + proto: "" + auto: "" + force_link: "" + ipaddr: "" + netmask: "" + gateway: "" + peerdns: "" + dns: [] + username: "" + password: "" + mtu: "" + ipv6: "" + delegate: "" + ip6assign: "" + +# rule section +network_rules: + - id: "" + state: "" + mark: "" + in: "" + out: "" + src: "" + dest: "" + invert: "" + priority: "" + lookup: "" + goto: "" + action: "" + disabled: "" + +# route section +network_routes: + - id: "" + state: "" + interface: "" + target: "" + netmask: "" + gateway: "" + table: "" + source: "" + type: "" + proto: "" + disabled: "" diff --git a/roles/network/handlers/main.yml b/roles/network/handlers/main.yml new file mode 100644 index 0000000..11ab20f --- /dev/null +++ b/roles/network/handlers/main.yml @@ -0,0 +1,5 @@ +--- +# Reload network service using nohup +- name: Reload network + nohup: + command: /etc/init.d/network restart \ No newline at end of file diff --git a/roles/network/meta/main.yml b/roles/network/meta/main.yml new file mode 100644 index 0000000..4596e33 --- /dev/null +++ b/roles/network/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure network settings + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "network"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/network/tasks/device.yml b/roles/network/tasks/device.yml new file mode 100644 index 0000000..b5532d9 --- /dev/null +++ b/roles/network/tasks/device.yml @@ -0,0 +1,42 @@ +--- +# Set state status for network device +- name: Set state status for network device {{ item.id | default('@device[-1]') }} + ansible.builtin.set_fact: + network_device_state: "{{ item.state | default('present') }}" + +# Delete network device +- name: Delete network device {{ item.id }} + when: "'absent' in network_device_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "device" + +# Create and configure network device +- name: Create and configure network device + when: "'present' in network_device_state" + block: + # Create network device + - name: Create network device {{ item.id | default('@device[-1]') }} + uci: + command: "add" + config: "network" + section: "{{ item.id | default('@device[-1]') }}" + type: "device" + + # Configure network device + - name: Configure network device {{ item.id | default('@device[-1]') }} + uci: + command: "set" + config: "network" + section: "{{ item.id | default('@device[-1]') }}" + type: "device" + value: + name: "{{ item.name | default(omit) }}" + type: "{{ item.type | default(omit) }}" + ports: "{{ item.ports | default([]) | join(' ') }}" + stp: "{{ item.stp | default(omit) }}" + vlan: "{{ item.vlan | default(omit) }}" + igmp_snooping: "{{ item.igmp_snooping | default(omit) }}" + ipv6: "{{ item.ipv6 | default(omit) }}" diff --git a/roles/network/tasks/globals.yml b/roles/network/tasks/globals.yml new file mode 100644 index 0000000..de566de --- /dev/null +++ b/roles/network/tasks/globals.yml @@ -0,0 +1,11 @@ +--- +# Configure globals settings +- name: Configure globals settings + uci: + command: "set" + config: "network" + section: "globals" + type: "globals" + value: + ula_prefix: "{{ network_globals.network_ula_prefix | default(omit) }}" + packet_steering: "{{ network_globals.network_packet_steering | default(omit) }}" diff --git a/roles/network/tasks/interface.yml b/roles/network/tasks/interface.yml new file mode 100644 index 0000000..49a60bb --- /dev/null +++ b/roles/network/tasks/interface.yml @@ -0,0 +1,50 @@ +--- +# Set state status for network interface +- name: Set state status for network interface {{ item.id }} + ansible.builtin.set_fact: + network_interface_state: "{{ item.state | default('present') }}" + +# Delete network interface +- name: Delete network interface {{ item.id }} + when: "'absent' in network_interface_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "interface" + +# Create and configure network interface +- name: Create and configure network interface + when: "'present' in network_interface_state" + block: + # Create network interface + - name: Create network interface {{ item.id }} + uci: + command: "add" + config: "network" + section: "{{ item.id }}" + type: "interface" + + # Configure network interface + - name: Configure network interface {{ item.id }} + uci: + command: "set" + config: "network" + section: "{{ item.id }}" + type: "interface" + value: + device: "{{ item.device | default(omit) }}" + proto: "{{ item.proto | default(omit) }}" + auto: "{{ item.auto | default(omit) }}" + force_link: "{{ item.force_link | default(omit) }}" + ipaddr: "{{ item.ipaddr | default(omit) }}" + netmask: "{{ item.netmask | default(omit) }}" + gateway: "{{ item.gateway | default(omit) }}" + peerdns: "{{ item.peerdns | default(omit) }}" + dns: "{{ item.dns | default([]) | join(' ') }}" + username: "{{ item.username | default(omit) }}" + password: "{{ item.password | default(omit) }}" + mtu: "{{ item.mtu | default(omit) }}" + ipv6: "{{ item.ipv6 | default(omit) }}" + delegate: "{{ item.delegate | default(omit) }}" + ip6assign: "{{ item.ip6assign | default(omit) }}" diff --git a/roles/network/tasks/main.yml b/roles/network/tasks/main.yml new file mode 100644 index 0000000..ced6c81 --- /dev/null +++ b/roles/network/tasks/main.yml @@ -0,0 +1,43 @@ +--- +# Configure globals section +- name: Configure globals section + when: network_globals is defined + ansible.builtin.include_tasks: globals.yml + +# Configure swconfig switch vlan section +- name: Configure swconfig switch vlan section + ansible.builtin.include_tasks: switch_swconfig.yml + when: network_swconfig_switch_vlans is defined + loop: "{{ network_swconfig_switch_vlans | default([]) }}" + +# Configure dsa switch vlan section +- name: Configure dsa switch vlan section + ansible.builtin.include_tasks: switch_dsa.yml + when: network_dsa_switch_vlans is defined + loop: "{{ network_dsa_switch_vlans | default([]) }}" + +# Configure device section +- name: Configure device section + ansible.builtin.include_tasks: device.yml + loop: "{{ network_devices | default([]) }}" + +# Configure interface section +- name: Configure interface section + ansible.builtin.include_tasks: interface.yml + loop: "{{ network_interfaces | default([]) }}" + +# Configure rule section +- name: Configure rule section + ansible.builtin.include_tasks: rule.yml + loop: "{{ network_rules | default([]) }}" + +# Configure route section +- name: Configure route section + ansible.builtin.include_tasks: route.yml + loop: "{{ network_routes | default([]) }}" + +# Apply changes and reload network service +- name: Apply changes and reload network + uci: + command: commit + notify: Reload network \ No newline at end of file diff --git a/roles/network/tasks/route.yml b/roles/network/tasks/route.yml new file mode 100644 index 0000000..3f7029f --- /dev/null +++ b/roles/network/tasks/route.yml @@ -0,0 +1,44 @@ +--- +# Set state status for network route +- name: Set state status for network route {{ item.id | default('@route[-1]') }} + ansible.builtin.set_fact: + network_route_state: "{{ item.state | default('present') }}" + +# Delete network route +- name: Delete network route {{ item.id }} + when: "'absent' in network_route_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "route" + +# Create and configure network route +- name: Create and configure network route + when: "'present' in network_route_state" + block: + # Create network route + - name: Create network route {{ item.id | default('@route[-1]') }} + uci: + command: "add" + config: "network" + section: "{{ item.id | default('@route[-1]') }}" + type: "route" + + # Configure network route + - name: Configure network route {{ item.id | default('@route[-1]') }} + uci: + command: "set" + config: "network" + section: "{{ item.id | default('@route[-1]') }}" + type: "route" + value: + interface: "{{ item.interface | default(omit) }}" + target: "{{ item.target | default(omit) }}" + netmask: "{{ item.netmask | default(omit) }}" + gateway: "{{ item.gateway | default(omit) }}" + table: "{{ item.table | default(omit) }}" + source: "{{ item.source | default(omit) }}" + type: "{{ item.type | default(omit) }}" + proto: "{{ item.proto | default(omit) }}" + disabled: "{{ item.disabled | default(omit) }}" diff --git a/roles/network/tasks/rule.yml b/roles/network/tasks/rule.yml new file mode 100644 index 0000000..8cb16dd --- /dev/null +++ b/roles/network/tasks/rule.yml @@ -0,0 +1,46 @@ +--- +# Set state status for network rule +- name: Set state status for network rule {{ item.id | default('@rule[-1]') }} + ansible.builtin.set_fact: + network_rule_state: "{{ item.state | default('present') }}" + +# Delete network rule +- name: Delete network rule {{ item.id }} + when: "'absent' in network_rule_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "rule" + +# Create and configure network rule +- name: Create and configure network rule + when: "'present' in network_rule_state" + block: + # Create network rule + - name: Create network rule {{ item.id | default('@rule[-1]') }} + uci: + command: "add" + config: "network" + section: "{{ item.id | default('@rule[-1]') }}" + type: "rule" + + # Configure network rule + - name: Configure network rule {{ item.id | default('@rule[-1]') }} + uci: + command: "set" + config: "network" + section: "{{ item.id | default('@rule[-1]') }}" + type: "rule" + value: + mark: "{{ item.mark | default(omit) }}" + in: "{{ item.in | default(omit) }}" + out: "{{ item.out | default(omit) }}" + src: "{{ item.src | default(omit) }}" + dest: "{{ item.dest | default(omit) }}" + invert: "{{ item.invert | default(omit) }}" + priority: "{{ item.priority | default(omit) }}" + lookup: "{{ item.lookup | default(omit) }}" + goto: "{{ item.goto | default([]) | join(' ') }}" + action: "{{ item.action | default(omit) }}" + disabled: "{{ item.disabled | default(omit) }}" diff --git a/roles/network/tasks/switch_dsa.yml b/roles/network/tasks/switch_dsa.yml new file mode 100644 index 0000000..144c3d0 --- /dev/null +++ b/roles/network/tasks/switch_dsa.yml @@ -0,0 +1,40 @@ +--- +# Set state status for switch vlan +- name: Set state status for switch vlan {{ item.id | default('@switch_vlan[-1]') }} + ansible.builtin.set_fact: + switch_vlan_state: "{{ item.state | default('present') }}" + +# Delete switch vlan +- name: Delete switch vlan {{ item.id }} + when: "'absent' in switch_vlan_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "switch_vlan" + +# Create and configure switch vlan +- name: Create and configure switch vlan + when: "'present' in switch_vlan_state" + block: + # Create switch vlan + - name: Create switch vlan {{ item.id | default('@switch_vlan[-1]') }} + uci: + command: "add" + config: "network" + section: "{{ item.id | default('@switch_vlan[-1]') }}" + type: "switch_vlan" + + # Configure switch vlan + - name: Configure switch vlan {{ item.id | default('@switch_vlan[-1]') }} + uci: + command: "set" + config: "network" + section: "{{ item.id | default('@switch_vlan[-1]') }}" + type: "switch_vlan" + value: + device: "{{ item.device | default('switch0') }}" + vlan: "{{ item.vlan | mandatory }}" + vid: "{{ item.vid | default(item.vlan | default(omit)) }}" + ports: "{{ item.ports | default([]) }}" + description: "{{ item.description | default(omit) }}" \ No newline at end of file diff --git a/roles/network/tasks/switch_swconfig.yml b/roles/network/tasks/switch_swconfig.yml new file mode 100644 index 0000000..144c3d0 --- /dev/null +++ b/roles/network/tasks/switch_swconfig.yml @@ -0,0 +1,40 @@ +--- +# Set state status for switch vlan +- name: Set state status for switch vlan {{ item.id | default('@switch_vlan[-1]') }} + ansible.builtin.set_fact: + switch_vlan_state: "{{ item.state | default('present') }}" + +# Delete switch vlan +- name: Delete switch vlan {{ item.id }} + when: "'absent' in switch_vlan_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "switch_vlan" + +# Create and configure switch vlan +- name: Create and configure switch vlan + when: "'present' in switch_vlan_state" + block: + # Create switch vlan + - name: Create switch vlan {{ item.id | default('@switch_vlan[-1]') }} + uci: + command: "add" + config: "network" + section: "{{ item.id | default('@switch_vlan[-1]') }}" + type: "switch_vlan" + + # Configure switch vlan + - name: Configure switch vlan {{ item.id | default('@switch_vlan[-1]') }} + uci: + command: "set" + config: "network" + section: "{{ item.id | default('@switch_vlan[-1]') }}" + type: "switch_vlan" + value: + device: "{{ item.device | default('switch0') }}" + vlan: "{{ item.vlan | mandatory }}" + vid: "{{ item.vid | default(item.vlan | default(omit)) }}" + ports: "{{ item.ports | default([]) }}" + description: "{{ item.description | default(omit) }}" \ No newline at end of file diff --git a/roles/pbr/README.md b/roles/pbr/README.md new file mode 100644 index 0000000..6457eec --- /dev/null +++ b/roles/pbr/README.md @@ -0,0 +1,91 @@ +# `flyoverhead.openwrt.pbr` + +OpenWRT `Policy-Based Routing` configuration +- create and configure pbr rules and routes + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `pbr_pkgs` | List of PBR packages to be installed | `required` | `list` | `["pbr", "luci-app-pbr"]` | +| `dnsmasq_full_required_version` | Dnsmasq-full package version required for dnsmasq nft sets support | `required` | `string` | `2.89` | +| `pbr_service` | PBR service configuration settings to be applied | | `dictionary` | | +|  `enabled` | Enable pbr service | `required` | `boolean` | `1` | +|  `verbosity` | Console and system log output verbosity (`0`, `1` or `2`) | `optional` | `integer` | `2` | +|  `strict_enforcement` | Enforce policies when their interface is down | `required` | `boolean` | `1` | +|  `resolver_set` | Resolver’s set support for domains (`none`, `adguardhome.ipset`, `dnsmasq.ipset` or `dnsmasq.nftset`) | `required` | `string` | `dnsmasq.nftset` | +|  `resolver_instance` | List of resolver’s set support instances (available for `dnsmasq.ipset` and `dnsmasq.nftset`) | `optional` | `string` | `*` | +|  `ipv6_enabled` | Enable IPv6 support | `optional` | `boolean` | `0` | +|  `supported_interface` | List of network interfaces to be explicitly supported by the pbr service | `optional` | `list` | `["lan", "wan"]` | +|  `ignored_interface` | List of network interfaces to be ignored by the pbr service | `optional` | `list` | `["vpnserver", "wgserver"]` | +|  `boot_timeout` | Time in seconds for pbr service to wait for WAN gateway discovery on boot | `optional` | `integer` | `30` | +|  `rule_create_option` | Policy rule creation option (`add` or `insert`) | `required` | `string` | `add` | +|  `icmp_interface` | Default ICMP protocol network interface | `optional` | `string` | `wan` | +|  `wan_mark` | Firewall mark for marks used by the pbr service | `optional` | `string` | `010000` | +|  `fw_mask` | Firewall mask used by the pbr service | `optional` | `string` | `ff0000` | +|  `secure_reload` | Enable killing router traffic (activates killswitch) during service start/restart/reload operations to prevent traffic leaks on unwanted interface (`experimental`) | `optional` | `boolean` | `0` | +|  `webui_show_ignore_target` | Show `ignore` in the list of interfaces | `optional` | `boolean` | `0` | +|  `webui_supported_protocol` | List of protocols to display in the `Protocol` column for policies (`all`, `tcp`, `udp` or `icmp`) | `optional` | `list` | `0` | +| `pbr_policies` | List of PBR policies | | `list of dictionaries` | | +|  `id` | Unique policy ID | `mandatory` | `string` | `example_policy` | +|  `name` | Unique policy name | `mandatory` | `string` | `Example policy` | +|  `state` | Policy status (`present` or `absent`) | `required` | `string` | `present` | +|  `enabled` | Enable policy | `required` | `boolean` | `1` | +|  `interface` | Policy associated network interface | `mandatory` | `string` | `vpn0` | +|  `src_addr` | List of local/source IP addresses, CIDRs, hostnames, mac addresses, local physical devices or URLs to list of addresses (not compatible with the `secure_reload` option) | `required` | `list` | `["192.168.1.0/24"]` | +|  `src_port` | List of space-separated local/source ports or port-ranges | `required` | `list` | `["22", "8000-9000"]` | +|  `dest_addr` | List of remote/target IP addresses, CIDRs, hostnames/domain names or URLs to list of addresses | `required` | `list` | `["192.168.2.0/24"]` | +|  `dest_port` | List of space-separated remote/target ports or port-ranges | `required` | `list` | `["22", "8000-9000"]` | +|  `proto` | Policy protocol (any valid protocol from `/etc/protocols` for CLI/uci or selected from the values set in `webui_supported_protocol`) | `required` | `string` | `auto` | +|  `chain` | Policy chain (`forward`, `input`, `prerouting`, `postrouting` or `output`) | `required` | `string` | `prerouting` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.pbr +``` + +## Example Vars + +```yaml +pbr_service: + enabled: "1" + verbosity: "0" + strict_enforcement: "0" + resolver_set: "dnsmasq.nftset" + ipv6_enabled: "0" + ignored_interface: ["vpnserver"] + boot_timeout: "30" + rule_create_option: "add" + webui_show_ignore_target: "0" + webui_supported_protocol: ["all", "tcp", "udp", "tcp udp", "icmp"] +pbr_policies: + - id: "example_policy" + name: "Example policy" + state: "present" + enabled: "1" + interface: "vpn0" + dest_addr: ["blocked.example.com", "blocked.com"] + chain: "prerouting" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/network/routing/pbr_app +- https://docs.openwrt.melmac.net/pbr/#a-word-about-default-routing diff --git a/roles/pbr/defaults/main.yml b/roles/pbr/defaults/main.yml new file mode 100644 index 0000000..f5f0304 --- /dev/null +++ b/roles/pbr/defaults/main.yml @@ -0,0 +1,39 @@ +--- +# Policy-Based Routing packages +pbr_pkgs: ["pbr", "luci-app-pbr"] + +# Dnsmasq-full required version +dnsmasq_full_required_version: "2.89" + +# PBR service configuration +pbr_service: + enabled: "" + verbosity: "" + strict_enforcement: "" + resolver_set: "" + resolver_instance: [] + ipv6_enabled: "" + supported_interface: [] + ignored_interface: [] + boot_timeout: "" + rule_create_option: "" + icmp_interface: "" + wan_mark: "" + fw_mask: "" + secure_reload: "" + webui_show_ignore_target: "" + webui_supported_protocol: [] + +# PBR policies +pbr_policies: + - id: "" + name: "" + state: "" + enabled: "" + interface: "" + src_addr: [] + src_port: [] + dest_addr: [] + dest_port: [] + proto: "" + chain: "" diff --git a/roles/pbr/handlers/main.yml b/roles/pbr/handlers/main.yml new file mode 100644 index 0000000..8d63455 --- /dev/null +++ b/roles/pbr/handlers/main.yml @@ -0,0 +1,7 @@ +--- +# Reload pbr service +- name: Reload pbr + ansible.builtin.service: + name: pbr + state: reloaded + enabled: true diff --git a/roles/pbr/meta/main.yml b/roles/pbr/meta/main.yml new file mode 100644 index 0000000..7e7f2d3 --- /dev/null +++ b/roles/pbr/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure Policy-Based Routing + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "pbr"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/pbr/tasks/main.yml b/roles/pbr/tasks/main.yml new file mode 100644 index 0000000..c276b07 --- /dev/null +++ b/roles/pbr/tasks/main.yml @@ -0,0 +1,19 @@ +--- +# Install required packages +- name: Install required packages + ansible.builtin.include_tasks: prepare.yml + +# Configure pbr service settings +- name: Configure pbr service settings + ansible.builtin.include_tasks: service.yml + +# Configure pbr policies +- name: Configure pbr policies + ansible.builtin.include_tasks: policy.yml + loop: "{{ pbr_policies | default([]) }}" + +# Apply changes and reload pbr service +- name: Apply changes and reload pbr + uci: + command: commit + notify: Reload pbr diff --git a/roles/pbr/tasks/policy.yml b/roles/pbr/tasks/policy.yml new file mode 100644 index 0000000..9f507b9 --- /dev/null +++ b/roles/pbr/tasks/policy.yml @@ -0,0 +1,44 @@ +--- +# Set state status for policy +- name: Set state status for policy {{ item.id | default('@policy[-1]') }} + ansible.builtin.set_fact: + policy_state: "{{ item.state | default('present') }}" + +# Delete policy +- name: Delete policy {{ item.id }} + when: "'absent' in policy_state" + uci: + command: "absent" + config: "pbr" + section: "{{ item.id | default('@policy[-1]') }}" + type: "policy" + +# Create and configure policy +- name: Create and configure policy + when: "'present' in policy_state" + block: + # Create policy + - name: Create policy {{ item.id | default('@policy[-1]') }} + uci: + command: "add" + config: "pbr" + section: "{{ item.id | default('@policy[-1]') }}" + type: "policy" + + # Configure policy + - name: Configure policy {{ item.id | default('@policy[-1]') }} + uci: + command: "set" + config: "pbr" + section: "{{ item.id | default('@policy[-1]') }}" + type: "policy" + value: + name: "{{ item.name | default(omit) }}" + enabled: "{{ item.enabled | default(omit) }}" + interface: "{{ item.interface | default(omit) }}" + src_addr: "{{ item.src_addr | default([]) | join(' ') }}" + src_port: "{{ item.src_port | default([]) | join(' ') }}" + dest_addr: "{{ item.dest_addr | default([]) | join(' ') }}" + dest_port: "{{ item.dest_port | default([]) | join(' ') }}" + proto: "{{ item.proto | default(omit) }}" + chain: "{{ item.chain | default(omit) }}" diff --git a/roles/pbr/tasks/prepare.yml b/roles/pbr/tasks/prepare.yml new file mode 100644 index 0000000..7a21715 --- /dev/null +++ b/roles/pbr/tasks/prepare.yml @@ -0,0 +1,88 @@ +--- +# Update opkg cache +- name: Update opkg cache + ansible.builtin.command: + cmd: "opkg update" + changed_when: false + +# Install pbr packages +- name: Install pbr packages + opkg: + name: "{{ item }}" + state: "present" + loop: "{{ pbr_pkgs }}" + +# Check dnsmasq-full installed version +- name: Check dnsmasq-full installed version + ansible.builtin.command: + cmd: "opkg list-installed | grep dnsmasq-full | awk '{print $3}'" + uses_shell: true + register: dnsmasq_full_installed_version + changed_when: false + +# Check dnsmasq-full release version +- name: Check dnsmasq-full release version + ansible.builtin.command: + cmd: "opkg find dnsmasq-full | awk '{print $3}'" + uses_shell: true + register: dnsmasq_full_release_version + changed_when: false + +# Install dnsmasq-full release version +- name: Install dnsmasq-full release version + when: > + (dnsmasq_full_installed_version.stdout is undefined or + dnsmasq_full_installed_version.stdout < dnsmasq_full_required_version) and + dnsmasq_full_release_version.stdout >= dnsmasq_full_required_version + block: + # Remove dnsmasq-base packages + - name: Remove dnsmasq-base package + opkg: + name: "{{ item }}" + state: "absent" + loop: ["dnsmasq", "dnsmasq-full"] + + # Install dnsmasq-full release version + - name: Install dnsmasq-full release version + opkg: + name: "dnsmasq-full" + state: "present" + +# Install dnsmasq-full snapshot version +- name: Install dnsmasq-full snapshot version + when: > + (dnsmasq_full_installed_version.stdout is undefined or + dnsmasq_full_installed_version.stdout < dnsmasq_full_required_version) and + dnsmasq_full_release_version.stdout < dnsmasq_full_required_version + block: + # Remove current dnsmasq-base packages + - name: Remove current dnsmasq packages + opkg: + name: "{{ item }}" + state: "absent" + loop: ["dnsmasq", "dnsmasq-full"] + + # Install curl for package downloading + - name: Install curl + opkg: + name: "curl" + state: "present" + + # Get current package architecture + - name: Get current package architecture + ansible.builtin.command: + cmd: "opkg print-architecture | tail -n 1 | awk '{print $2}'" + uses_shell: true + register: current_package_architecture + changed_when: false + + # Set snapshot packages facts + - name: Set snapshot packages facts + ansible.builtin.set_fact: + snapshot_repo_url: "https://downloads.openwrt.org/snapshots/packages/{{ current_package_architecture.stdout }}/base/" + snapshot_pkgs_list: ["libubox[0-9]", "libubus[0-9]", "dnsmasq-full"] + + # Download and install snapshot packages + - name: Download and install snapshot packages + ansible.builtin.include_tasks: snapshot.yml + loop: "{{ snapshot_pkgs_list }}" diff --git a/roles/pbr/tasks/service.yml b/roles/pbr/tasks/service.yml new file mode 100644 index 0000000..d9080ee --- /dev/null +++ b/roles/pbr/tasks/service.yml @@ -0,0 +1,25 @@ +--- +# Configure service settings +- name: Configure service settings + uci: + command: "set" + config: "pbr" + section: "config" + type: "pbr" + value: + enabled: "{{ pbr_service.enabled | default(omit) }}" + verbosity: "{{ pbr_service.verbosity | default(omit) }}" + strict_enforcement: "{{ pbr_service.strict_enforcement | default(omit) }}" + resolver_set: "{{ pbr_service.resolver_set | default(omit) }}" + resolver_instance: "{{ pbr_service.resolver_instance | default([]) | join(' ') }}" + ipv6_enabled: "{{ pbr_service.ipv6_enabled | default(omit) }}" + supported_interface: "{{ pbr_service.supported_interface | default([]) | join(' ') }}" + ignored_interface: "{{ pbr_service.ignored_interface | default([]) | join(' ') }}" + boot_timeout: "{{ pbr_service.boot_timeout | default(omit) }}" + rule_create_option: "{{ pbr_service.rule_create_option | default(omit) }}" + icmp_interface: "{{ pbr_service.icmp_interface | default(omit) }}" + wan_mark: "{{ pbr_service.wan_mark | default(omit) }}" + fw_mask: "{{ pbr_service.fw_mask | default(omit) }}" + secure_reload: "{{ pbr_service.secure_reload | default(omit) }}" + webui_show_ignore_target: "{{ pbr_service.webui_show_ignore_target | default(omit) }}" + webui_supported_protocol: "{{ pbr_service.webui_supported_protocol | default([]) | join(' ') }}" diff --git a/roles/pbr/tasks/snapshot.yml b/roles/pbr/tasks/snapshot.yml new file mode 100644 index 0000000..8bde1d7 --- /dev/null +++ b/roles/pbr/tasks/snapshot.yml @@ -0,0 +1,32 @@ +--- +# Get package file name +- name: Get package file name {{ item }} + ansible.builtin.command: + cmd: 'curl {{ snapshot_repo_url }} | grep {{ item }} | sed ''s/.*href=\"//'' | sed -r ''s/\".+//''' + uses_shell: true + register: snapshot_package_file_name + changed_when: false + +# Set package file name fact +- name: Set package file name fact + ansible.builtin.set_fact: + snapshot_package_name: "{{ snapshot_package_file_name.stdout }}" + +# Download package file +- name: Download package file {{ snapshot_package_name }} + ansible.builtin.command: + cmd: "curl {{ snapshot_repo_url }}{{ snapshot_package_name }} -o {{ snapshot_package_name }}" + uses_shell: true + chdir: "/tmp" + +# Install package file +- name: Install package from file {{ snapshot_package_name }} + ansible.builtin.command: + cmd: "opkg install {{ snapshot_package_name }}" + chdir: "/tmp" + +# Clean package file +- name: Clean package file {{ snapshot_package_name }} + ansible.builtin.command: + cmd: "rm -f {{ snapshot_package_name }}" + chdir: "/tmp" diff --git a/roles/system/README.md b/roles/system/README.md new file mode 100644 index 0000000..9485a49 --- /dev/null +++ b/roles/system/README.md @@ -0,0 +1,58 @@ +# `flyoverhead.openwrt.system` + +OpenWRT `system` configuration +- configure system settings + +## Role Variables + +| Variable | Descritpion | Status | Type | Example | +| :--- | :--- | :--- | :--- | :--- | +| `system` | System settings configuration | | `dictionary` | | +|  `system_hostname` | Device hostname | `required` | `string` | `OpenWrt` | +|  `system_description` | Short device description | `optional` | `string` | `OpenWrt device` | +|  `system_klogconloglevel` | Maximum log level for kernel messages | `optional` | `integer` | `7` | +|  `system_log_file` | Path to file to write log messages to | `optional` | `string` | `/var/log/messages` | +|  `system_log_ip` | IP address of a remote syslog server to which the log messages should be sent | `optional` | `string` | `192.168.1.1` | +|  `system_log_port` | Port number of a remote syslog server | `optional` | `integer` | `514` | +|  `system_log_proto` | Protocol used for the connection with a remote syslog server | `optional` | `string` | `udp` | +|  `system_log_remote` | Enable remote logging | `optional` | `boolean` | `1` | +|  `system_log_size` | Size of the file based log buffer in KiB | `optional` | `integer` | `64` | +|  `system_log_type` | Log type (`circular` or `file`) | `optional` | `string` | `circular` | +|  `system_timezone` | POSIX.1 format system timezone | `required` | `string` | `UTC` | +|  `system_zonename` | IANA/Olson format system timezone | `required` | `string` | `UTC` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.system +``` + +## Example Vars + +```yaml +system: + hostname: "mikrotik" + description: "MikroTik hAP ac2" + timezone: UTC" + zonename: "UTC" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/base-system/system_configuration diff --git a/roles/system/defaults/main.yml b/roles/system/defaults/main.yml new file mode 100644 index 0000000..5aea4d7 --- /dev/null +++ b/roles/system/defaults/main.yml @@ -0,0 +1,15 @@ +--- +# system section +system: + hostname: "" + description: "" + klogconloglevel: "" + log_file: "" + log_ip: "" + log_port: "" + log_proto: "" + log_remote: "" + log_size: "" + log_type: "" + timezone: "" + zonename: "" diff --git a/roles/system/handlers/main.yml b/roles/system/handlers/main.yml new file mode 100644 index 0000000..4cef3ad --- /dev/null +++ b/roles/system/handlers/main.yml @@ -0,0 +1,6 @@ +--- +# Reload system service +- name: Reload system + ansible.builtin.service: + name: system + state: reloaded diff --git a/roles/system/meta/main.yml b/roles/system/meta/main.yml new file mode 100644 index 0000000..6ff37a3 --- /dev/null +++ b/roles/system/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure system settings + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "system"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/system/tasks/main.yml b/roles/system/tasks/main.yml new file mode 100644 index 0000000..e78cdb2 --- /dev/null +++ b/roles/system/tasks/main.yml @@ -0,0 +1,17 @@ +--- +# Configure system section +- name: Configure system section + ansible.builtin.include_tasks: system.yml + +# Apply changes and reload system service +- name: Apply changes and reload system + block: + # Commit changes + - name: Commit changes + uci: + command: commit + notify: Reload system + + # Reload system service + - name: Reload system service + ansible.builtin.meta: flush_handlers diff --git a/roles/system/tasks/system.yml b/roles/system/tasks/system.yml new file mode 100644 index 0000000..0189f7f --- /dev/null +++ b/roles/system/tasks/system.yml @@ -0,0 +1,22 @@ +--- +# Configure system settings +- name: Configure system settings + uci: + command: "set" + config: "system" + section: "@system[0]" + type: "system" + value: + hostname: "{{ system.hostname | default(omit) }}" + description: "{{ system.description | default(omit) }}" + klogconloglevel: "{{ system.klogconloglevel | default(omit) }}" + log_file: "{{ system.log_file | default(omit) }}" + log_hostname: "{{ system.log_hostname | default(omit) }}" + log_ip: "{{ system.log_ip | default(omit) }}" + log_port: "{{ system.log_port | default(omit) }}" + log_proto: "{{ system.log_proto | default(omit) }}" + log_remote: "{{ system.log_remote | default(omit) }}" + log_size: "{{ system.log_size | default(omit) }}" + log_type: "{{ system.log_type | default(omit) }}" + timezone: "{{ system.timezone | default(omit) }}" + zonename: "{{ system.zonename | default(omit) }}" diff --git a/roles/wireguard/README.md b/roles/wireguard/README.md new file mode 100644 index 0000000..27bb8d9 --- /dev/null +++ b/roles/wireguard/README.md @@ -0,0 +1,95 @@ +# `flyoverhead.openwrt.wireguard` + +OpenWRT `wireguard` configuration +- create and configure wireguard interfaces +- create and configure wireguard peers + +## Role Variables + +| Variable | Descritpion | Status | Type | Default/Example | +| :--- | :--- | :--- | :--- | :--- | +| `wireguard_pkgs` | List of wireguard packages to be installed | `required` | `list` | `["wireguard-tools", "luci-proto-wireguard", "luci-app-wireguard", "qrencode"]` | +| `wireguard_interfaces` | List of [wireguard network interfaces](https://openwrt.org/docs/guide-user/services/vpn/wireguard/server#network) to be configured | | `list of dictionaries` | | +|  `id` | Unique wireguard server interface ID | `mandatory` | `string` | `wg0` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `proto` | Interface protocol | `mandatory` | `string` | `wireguard` | +|  `private_key` | Wireguard server private key (will be generated automatically when omit) | `optional` | `string` | `null` | +|  `addresses` | Wireguard server IP address in CIDR notation | `required` | `string` | `192.168.10.1/32` | +|  `listen_port` | Wireguard server listening port | `required` | `string` | `51820` | +|  `peers` | List of wireguard peers to be generated automatically | `required` | `list` | `["mobile", "desktop"]` | +| `wireguard_peers` | List of [wireguard peers](https://openwrt.org/docs/guide-user/services/vpn/wireguard/client#network) | | `list of dictionaries` | | +|  `id` | Unique peer ID | `mandatory` | `string` | `example_peer` | +|  `name` | Unique peer name | `mandatory` | `string` | `Wireguard peer` | +|  `state` | Peer status (`present` or `absent`) | `required` | `string` | `present` | +|  `public_key` | Peer public key | `mandatory` | `string` | `example_public_key` | +|  `preshared_key` | Peer preshared key | `required` | `list` | `example_preshared_key` | +|  `endpoint_host` | Wireguard server (endpoint) public IP address | `required` | `string` | `192.168.2.1` | +|  `endpoint_port` | Wireguard server (endpoint) listening port | `required` | `integer` | `51820` | +|  `route_allowed_ips` | Create routes for allowed IPs | `optional` | `boolean` | `0` | +|  `persistent_keepalive` | Set keep alive messages interval in seconds | `optional` | `integer` | `25` | +|  `allowed_ips` | IP addresses and prefixes that are allowed to use inside the tunnel | `required` | `list` | `["0.0.0.0/0"]` | +|  `wireguard_interface_name` | Wireguard associated interface name | `required` | `string` | `wg0` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.wireguard +``` + +## Example Vars + +### Server Mode + +```yaml +wireguard_interfaces: + - name: "wg0" + state: "present" + proto: "wireguard" + addresses: "192.168.2.1/32" + port: "51820" + peers: ["mobile_peer", "desktop_peer"] +``` + +### Client Mode + +```yaml +wireguard_interfaces: + - id: "wg1" + state: "present" + proto: "wireguard" + private_key: "private_key" + addresses: "192.168.2.2/32" +wireguard_peers: + - id: "vps" + name: "Example VPS" + state: "present" + public_key: "public_key" + preshared_key: "preshared_key" + endpoint_host: "192.168.2.1" + endpoint_port: "51820" + route_allowed_ips: "0" + persistent_keepalive: 25"" + allowed_ips: ["0.0.0.0/0"] + wireguard_interface_name: "wg1" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/services/vpn/wireguard/server +- https://openwrt.org/docs/guide-user/services/vpn/wireguard/client diff --git a/roles/wireguard/defaults/main.yml b/roles/wireguard/defaults/main.yml new file mode 100644 index 0000000..555d750 --- /dev/null +++ b/roles/wireguard/defaults/main.yml @@ -0,0 +1,28 @@ +--- +# Wireguard packages +wireguard_pkgs: + ["wireguard-tools", "luci-proto-wireguard", "luci-app-wireguard", "qrencode"] + +# Wireguard servers +wireguard_interfaces: + - id: "" + state: "" + proto: "" + private_key: "" + addresses: "" + listen_port: "" + peers: [] + +# Wireguard peers +wireguard_peers: + - id: "" + name: "" + state: "" + public_key: "" + preshared_key: "" + endpoint_host: "" + endpoint_port: "" + route_allowed_ips: "" + persistent_keepalive: "" + allowed_ips: [] + wireguard_interface_name: "" diff --git a/roles/wireguard/handlers/main.yml b/roles/wireguard/handlers/main.yml new file mode 100644 index 0000000..10f0f6e --- /dev/null +++ b/roles/wireguard/handlers/main.yml @@ -0,0 +1,6 @@ +--- +# Reload network service +- name: Reload network + ansible.builtin.service: + name: network + state: reloaded diff --git a/roles/wireguard/meta/main.yml b/roles/wireguard/meta/main.yml new file mode 100644 index 0000000..a5c8027 --- /dev/null +++ b/roles/wireguard/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure wireguard + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "wireguard"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/wireguard/tasks/main.yml b/roles/wireguard/tasks/main.yml new file mode 100644 index 0000000..7c1af39 --- /dev/null +++ b/roles/wireguard/tasks/main.yml @@ -0,0 +1,23 @@ +--- +# Install required packages +- name: Install required packages + ansible.builtin.include_tasks: prepare.yml + +# Configure wireguard interfaces +- name: Configure wireguard interfaces + ansible.builtin.include_tasks: server.yml + loop: "{{ wireguard_interfaces | default([]) }}" + +# Configure wireguard peers +- name: Configure wireguard peers + ansible.builtin.include_tasks: peer.yml + loop: "{{ wireguard_peers | default([]) }}" + loop_control: + loop_var: wgpeer + label: "{{ wgpeer }}" + +# Apply changes and reload network service +- name: Apply changes and reload network + uci: + command: commit + notify: Reload network diff --git a/roles/wireguard/tasks/peer.yml b/roles/wireguard/tasks/peer.yml new file mode 100644 index 0000000..3e011e6 --- /dev/null +++ b/roles/wireguard/tasks/peer.yml @@ -0,0 +1,128 @@ +--- +# Configure user-defined wireguard peer +- name: Configure user-defined wireguard peer + when: wgpeer is defined and wgpeer | type_debug == "dict" + block: + # Set state status for wireguard peer + - name: Set state status for wireguard peer {{ wgpeer.id }} + ansible.builtin.set_fact: + wireguard_peer_state: "{{ wgpeer.state | default('present') }}" + + # Delete wireguard peer + - name: Delete wireguard peer {{ wgpeer.id }} + when: "'absent' in wireguard_peer_state" + uci: + command: "absent" + config: "network" + section: "{{ wgpeer.id }}" + type: "wireguard_{{ wgpeer.wireguard_interface_name }}" + + # Create and configure wireguard peer + - name: Create and configure wireguard peer + when: "'present' in wireguard_peer_state" + block: + # Create wireguard peer + - name: Create wireguard peer {{ wgpeer.id }} + uci: + command: "add" + config: "network" + section: "{{ wgpeer.id }}" + type: "wireguard_{{ wgpeer.wireguard_interface_name }}" + + # Configure wireguard peer + - name: Configure wireguard peer {{ wgpeer.id }} + uci: + command: "set" + config: "network" + section: "{{ wgpeer.id }}" + type: "wireguard_{{ wgpeer.wireguard_interface_name }}" + value: + description: "{{ wgpeer.name | default(omit) }}" + public_key: "{{ wgpeer.public_key | default(omit) }}" + preshared_key: "{{ wgpeer.preshared_key | default(omit) }}" + endpoint_host: "{{ wgpeer.endpoint_host | default(omit) }}" + endpoint_port: "{{ wgpeer.endpoint_port | default(omit) }}" + route_allowed_ips: "{{ wgpeer.route_allowed_ips | default(omit) }}" + persistent_keepalive: "{{ wgpeer.persistent_keepalive | default(omit) }}" + allowed_ips: "{{ wgpeer.allowed_ips | default([]) | join(' ') }}" + +# Generate wireguard peer +- name: Generate wireguard peer + when: wgpeer is defined and wgpeer | type_debug == "str" + block: + # Create wireguard peer + - name: Create wireguard peer {{ wgpeer }} + uci: + command: "add" + config: "network" + section: "{{ wgpeer }}" + type: "{{ wireguard_interface_name }}" + + # Check current wireguard private key + - name: Check current wireguard private key + uci: + command: "get" + config: "network" + section: "{{ wgpeer }}.private_key" + type: "{{ wireguard_interface_name }}" + register: current_wireguard_private_key + failed_when: > + current_wireguard_private_key.result is undefined and + 'Entry not found' not in current_wireguard_private_key.result + + # Set current generated wireguard private key fact + - name: Set current wireguard private key fact + ansible.builtin.set_fact: + wireguard_private_key: "{{ current_wireguard_private_key.result }}" + when: > + (current_wireguard_private_key.result is defined and + current_wireguard_private_key.result | length > 0) and + 'Entry not found' not in current_wireguard_private_key.result + + # Generate wireguard key pair + - name: Generate wireguard key pair + when: > + current_wireguard_private_key.result is undefined or + 'Entry not found' in current_wireguard_private_key.result + block: + # Generate wireguard private key + - name: Generate wireguard private key + ansible.builtin.command: + cmd: "umask go= && wg genkey" + uses_shell: true + register: new_wireguard_private_key + + # Set newely generated wireguard private key fact + - name: Set newely generated wireguard private key fact + ansible.builtin.set_fact: + wireguard_private_key: "{{ new_wireguard_private_key.stdout }}" + + # Generate wireguard public key + - name: Generate wireguard public key + ansible.builtin.command: + cmd: 'umask go= && echo "{{ wireguard_private_key }}" | wg pubkey' + uses_shell: true + register: wireguard_public_key + + # Generate wireguard preshared key + - name: Generate wireguard preshared key + ansible.builtin.command: + cmd: "umask go= && wg genpsk" + uses_shell: true + register: wireguard_preshared_key + + # Configure wireguard peer + - name: Configure wireguard peer {{ wgpeer }} + uci: + command: "set" + config: "network" + section: "{{ wgpeer }}" + type: "{{ wireguard_interface_name }}" + value: + description: "{{ wgpeer }}" + private_key: "{{ wireguard_private_key | default(omit) }}" + public_key: "{{ wireguard_public_key.stdout | default(omit) }}" + preshared_key: "{{ wireguard_preshared_key.stdout | default(omit) }}" + route_allowed_ips: "1" + persistent_keepalive: "25" + allowed_ips: "{{ wireguard_interface_addresses | ansible.utils.ipmath(ansible_loop.index) }}" diff --git a/roles/wireguard/tasks/prepare.yml b/roles/wireguard/tasks/prepare.yml new file mode 100644 index 0000000..e573112 --- /dev/null +++ b/roles/wireguard/tasks/prepare.yml @@ -0,0 +1,13 @@ +--- +# Update opkg cache +- name: Update opkg cache + ansible.builtin.command: + cmd: "opkg update" + changed_when: false + +# Install wireguard packages +- name: Install wireguard packages + opkg: + name: "{{ item }}" + state: "present" + loop: "{{ wireguard_pkgs }}" diff --git a/roles/wireguard/tasks/server.yml b/roles/wireguard/tasks/server.yml new file mode 100644 index 0000000..2b8961f --- /dev/null +++ b/roles/wireguard/tasks/server.yml @@ -0,0 +1,111 @@ +--- +# Set state status for wireguard interface +- name: Set state status for wireguard interface {{ item.id }} + ansible.builtin.set_fact: + wireguard_interface_state: "{{ item.state | default('present') }}" + +# Delete wireguard interface +- name: Delete wireguard interface {{ item.id }} + when: "'absent' in wireguard_interface_state" + uci: + command: "absent" + config: "network" + section: "{{ item.id }}" + type: "interface" + +# Create and configure wireguard interface +- name: Create and configure user-defined wireguard interface + when: "'present' in wireguard_interface_state" + block: + # Create wireguard interface + - name: Create wireguard interface {{ item.id }} + uci: + command: "add" + config: "network" + section: "{{ item.id }}" + type: "interface" + + # Configure wireguard interface + - name: Configure user-defined wireguard interface {{ item.id }} + when: > + item.private_key is defined and + item.private_key | length > 0 + uci: + command: "set" + config: "network" + section: "{{ item.id }}" + type: "interface" + value: + proto: "{{ item.proto | default(omit) }}" + private_key: "{{ item.private_key | default(omit) }}" + addresses: "{{ item.addresses | default(omit) }}" + listen_port: "{{ item.listen_port | default(omit) }}" + + # Configure new wireguard interface + - name: Configure new wireguard interface + when: > + item.private_key is undefined or + item.private_key | length == 0 + block: + # Check current wireguard private key + - name: Check current wireguard private key + uci: + command: "get" + config: "network" + section: "{{ item.id }}.private_key" + type: "interface" + register: current_wireguard_private_key + failed_when: > + current_wireguard_private_key.result is undefined and + 'Entry not found' not in current_wireguard_private_key.result + + # Set current generated wireguard private key fact + - name: Set current wireguard private key fact + ansible.builtin.set_fact: + wireguard_private_key: "{{ current_wireguard_private_key.result }}" + when: > + (current_wireguard_private_key.result is defined and + current_wireguard_private_key.result | length > 0) and + 'Entry not found' not in current_wireguard_private_key.result + + # Generate wireguard private key + - name: Generate wireguard private key + ansible.builtin.command: + cmd: "umask go= && wg genkey" + uses_shell: true + register: new_wireguard_private_key + when: > + current_wireguard_private_key.result is undefined or + 'Entry not found' in current_wireguard_private_key.result + + # Set newely generated wireguard private key fact + - name: Set newely generated wireguard private key fact + ansible.builtin.set_fact: + wireguard_private_key: "{{ new_wireguard_private_key.stdout }}" + when: > + new_wireguard_private_key.stdout is defined and + new_wireguard_private_key.stdout | length > 0 + + # Configure wireguard interface + - name: Configure wireguard interface {{ item.id }} + uci: + command: "set" + config: "network" + section: "{{ item.id }}" + type: "interface" + value: + proto: "{{ item.proto | default(omit) }}" + private_key: "{{ wireguard_private_key }}" + addresses: "{{ item.addresses | default(omit) }}" + listen_port: "{{ item.listen_port | default(omit) }}" + + # Configure wireguard peers + - name: Configure wireguard peers + ansible.builtin.include_tasks: peer.yml + vars: + wireguard_interface_name: "wireguard_{{ item.id }}" + wireguard_interface_addresses: "{{ item.addresses }}" + loop: "{{ item.peers | default([]) }}" + loop_control: + extended: true + loop_var: wgpeer diff --git a/roles/wireless/README.md b/roles/wireless/README.md new file mode 100644 index 0000000..04e938f --- /dev/null +++ b/roles/wireless/README.md @@ -0,0 +1,83 @@ +# `flyoverhead.openwrt.wireless` + +OpenWRT `wireless` configuration +- configure wireless devices +- create/delete/configure wireless interfaces + +## Role Variables + +| Variable | Descritpion | Status | Type | Example | +| :--- | :--- | :--- | :--- | :--- | +| `wireless_devices` | List of [wireless devices](https://openwrt.org/docs/guide-user/network/wifi/basic#wi-fi_devices) | | `list of dictionaries` | | +|  `id` | Radio device ID | `mandatory` | `string` | `radio0` | +|  `type` | Radio device type | `optional` | `string` | `mac80211` | +|  `disabled` | Disable radio adapter | `required` | `boolean` | `0` | +|  `channel` | Wireless channel (`integer` of `auto`) | `optional` | `string` | `auto` | +|  `band` | Wireless band (`2g` or `5g`) | `optional` | `string` | `2g` | +|  `htmode` | Wireless channel width | `optional` | `string` | `HT20` | +|  `country` | Country code for adaptive channels and transmission powers | `optional` | `string` | `US` | +| `wireless_interfaces` | List of [wireless interfaces](https://openwrt.org/docs/guide-user/network/wifi/basic#wi-fi_interfaces) | | `list of dictionaries` | | +|  `id` | Unique interface ID | `mandatory` | `string` | `iot0` | +|  `name` | Unique interface name | `mandatory` | `string` | `iot0` | +|  `state` | Interface status (`present` or `absent`) | `required` | `string` | `present` | +|  `device` | Radio device associated with the interface | `mandatory` | `string` | `radio0` | +|  `network` | List of networks associated with the interface | `required` | `list` | `iot` | +|  `mode` | Wireless interface operation mode | `required` | `string` | `ap` | +|  `disabled` | Disable wireless network | `required` | `boolean` | `0` | +|  `ssid` | Wireless network SSID | `required` | `string` | `OpenWrt` | +|  `mesh_id` | ID of the mesh network (as defined in IEEE 802.11s) to join wireless interface to | `optional` | `string` | `example_mesh_id` | +|  `hidden` | Disable broadcasting of beacon frames to hide ESSID | `optional` | `boolean` | `0` | +|  `isolate` | Isolate wireless clients from each other | `optional` | `boolean` | `0` | +|  `encryption` | Wireless encryption method | `required` | `string` | `psk2` | +|  `key` | Passphrase for pre-shared key | `required` | `string` | `password` | +|  `macfilter` | MAC filter policy (`disable`, `allow` or `deny`) | `optional` | `string` | `disable` | +|  `maclist` | List of MAC addresses used fot MAC filter policy | `optional` | `list` | `["00:11:22:33:44:55", "55:44:33:22:11:00"]` | +|  `ieee80211r` | Enable fast BSS transition (802.11r) support | `optional` | `boolean` | `0` | +|  `mobility_domain` | Enable Mobility Domain identifier used to indicate a group of APs between which a STA can use fast BSS transition (will be generated automatically) | `optional` | `boolean` | `1` | +|  `ft_over_ds` | Enable FT-over-DS | `optional` | `boolean` | `1` | +|  `ft_psk_generate_local` | Enable local generation of FT response for PSK networks | `optional` | `boolean` | `1` | + +## Dependencies + +| Name | Description | +| :--- | :--- | +| `Ansible Role: openwrt` | [Ansible role by gekmihesg](https://github.com/gekmihesg/ansible-openwrt) for managing OpenWRT and derivatives | + +## Example Playbook + +```yaml +- hosts: openwrt + roles: + - role: flyoverhead.openwrt.wireless +``` + +## Example Vars + +```yaml +wireless_devices: + - id: "radio0" + type: "mac80211" + channel: "auto" +wireless_interfaces: + - id: "lan0" + name: "lan0" + state: "present" + device: "radio0" + network: ["lan"] + mode: "ap" + ssid: "openwrt" + encryption: "psk2" + key: "password" +``` + +## License + +[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.txt) + +## Author Information + +fly0v3rH34D + +## References + +- https://openwrt.org/docs/guide-user/network/wifi/basic diff --git a/roles/wireless/defaults/main.yml b/roles/wireless/defaults/main.yml new file mode 100644 index 0000000..ce07e86 --- /dev/null +++ b/roles/wireless/defaults/main.yml @@ -0,0 +1,32 @@ +--- +# device section +wireless_devices: + - id: "" + type: "" + disabled: "" + channel: "" + band: "" + htmode: "" + country: "" + +# interface section +wireless_interfaces: + - id: "" + name: "" + state: "" + device: "" + network: [] + mode: "" + disabled: "" + ssid: "" + mesh_id: "" + hidden: "" + isolate: "" + encryption: "" + key: "" + macfilter: "" + maclist: [] + ieee80211r: "" + mobility_domain: "" + ft_over_ds: "" + ft_psk_generate_local: "" diff --git a/roles/wireless/handlers/main.yml b/roles/wireless/handlers/main.yml new file mode 100644 index 0000000..933a224 --- /dev/null +++ b/roles/wireless/handlers/main.yml @@ -0,0 +1,8 @@ +--- +# Reload wireless service +- name: Reload wireless + ansible.builtin.command: + cmd: "/sbin/wifi {{ item }}" + register: reload_wifi_status + changed_when: reload_wifi_status != 0 + loop: ["config", "reload"] diff --git a/roles/wireless/meta/main.yml b/roles/wireless/meta/main.yml new file mode 100644 index 0000000..2ea15ce --- /dev/null +++ b/roles/wireless/meta/main.yml @@ -0,0 +1,12 @@ +--- +galaxy_info: + author: flyoverhead + description: Configure wireless settings + license: GPL-3.0 + min_ansible_version: "2.13" + platforms: + - name: OpenWrt + versions: ["22.03"] + galaxy_tags: ["openwrt", "wireless"] +dependencies: + - role: gekmihesg.openwrt diff --git a/roles/wireless/tasks/device.yml b/roles/wireless/tasks/device.yml new file mode 100644 index 0000000..c78da39 --- /dev/null +++ b/roles/wireless/tasks/device.yml @@ -0,0 +1,31 @@ +--- +# # Configure wireless device +# - name: Configure wireless device {{ item.id }} +# when: item.id != "" +# uci: +# command: "set" +# config: "wireless" +# section: "{{ item.id }}" +# type: "wifi-device" +# value: +# type: "{{ item.type | default(omit) }}" +# disabled: "{{ item.disabled | default(omit) }}" +# channel: "{{ item.channel | default(omit) }}" +# band: "{{ item.band | default(omit) }}" +# htmode: "{{ item.htmode | default(omit) }}" +# country: "{{ item.country | default(omit) }}" +# Configure wireless device +- name: Configure wireless device {{ item }} + uci: + command: "section" + config: "wireless" + section: "{{ item }}" + type: "wifi-device" + value: + type: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='type') | first | default(omit)) }}" + disabled: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='disabled') | first | default(wireless_devices_default.disabled | default(omit))) }}" + channel: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='channel') | first | default(omit)) }}" + band: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='band') | first | default(omit)) }}" + htmode: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='htmode') | first | default(omit)) }}" + country: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='country') | first | default(wireless_devices_default.country | default(omit))) }}" + txpower: "{{ (wireless_devices | selectattr('id', 'equalto', item) | map(attribute='txpower') | first | default(omit)) }}" \ No newline at end of file diff --git a/roles/wireless/tasks/interface.yml b/roles/wireless/tasks/interface.yml new file mode 100644 index 0000000..05df49d --- /dev/null +++ b/roles/wireless/tasks/interface.yml @@ -0,0 +1,93 @@ +--- +# Set state status for wireless interface +- name: Set state status for wireless interface {{ outerItem.ssid }} + ansible.builtin.set_fact: + wireless_interface_state: "{{ outerItem.state | default('present') }}" + +# Override wifi devices +- name: Override wifi add devices for {{ outerItem.ssid }} + when: "'present' in wireless_interface_state" + ansible.builtin.set_fact: + wireless_devices_add: "{{ (wireless_interfaces_override | default() | selectattr('ssid', 'equalto', outerItem.ssid) | map(attribute='device') | list | first) | default(outerItem.device) }}" +- name: Set wifi device del for {{ outerItem.ssid }} + when: "'present' in wireless_interface_state" + ansible.builtin.set_fact: + wireless_devices_del: "{{ ansible_facts.openwrt_wireless | list | difference(wireless_devices_add) | default([]) }}" + +# - name: test +# debug: +# msg: "{{ outerItem }}" +# loop: "{{ outerItem.device }}" + +# Delete wireless interface by name on all radios +- name: Delete wireless interface {{ outerItem.ssid }} on all radios + when: "'absent' in wireless_interface_state" + uci: + command: "absent" + config: "wireless" + type: "wifi-iface" + find: + ssid: "{{ outerItem.ssid }}" + +# Delete wireless interface +- name: Delete wireless interface {{ outerItem.ssid }} on radio {{ item }} + when: wireless_devices_del is defined and wireless_devices_del | length > 0 + uci: + command: "absent" + config: "wireless" + type: "wifi-iface" + find: + ssid: "{{ outerItem.ssid }}" + device: "{{ item }}" + loop: "{{ wireless_devices_del }}" + +# Create and configure wireless interface +- name: Create and configure wireless interface + when: "'present' in wireless_interface_state and wireless_devices_add | length > 0" + block: + # Generate mobility domain identifier + - name: Generate mobility domain identifier + ansible.builtin.command: + cmd: "echo -n {{ item.ssid }} | md5sum | cut -c-4" + uses_shell: true + register: mobility_domain_identifier + when: > + (mobility_domain is defined and mobility_domain == 1) and + (item.ssid is defined and item.ssid | length > 0) + + # Configure wireless interface + - name: Configure wireless interface + uci: + command: "section" + config: "wireless" + type: "wifi-iface" + find: + device: "{{ item }}" + ssid: "{{ outerItem.ssid }}" + value: + ifname: "{{ outerItem.ifname ~ ansible_loop.index0 | default(omit) }}" + device: "{{ item | default(omit) }}" + network: "{{ outerItem.network | default([]) | join(' ') }}" + mode: "{{ outerItem.mode | default(omit) }}" + disabled: "{{ outerItem.disabled | default(omit) }}" + ssid: "{{ outerItem.ssid | default(omit) }}" + mesh_id: "{{ outerItem.mesh_id | default(omit) }}" + hidden: "{{ outerItem.hidden | default(omit) }}" + isolate: "{{ outerItem.isolate | default(omit) }}" + encryption: "{{ outerItem.encryption | default(omit) }}" + key: "{{ outerItem.key | default(omit) }}" + auth_server: "{{ outerItem.auth_server | default(omit) }}" + auth_secret: "{{ outerItem.auth_secret | default(omit) }}" + dynamic_vlan: "{{ outerItem.dynamic_vlan | default(omit) }}" + vlan_tagged_interface: "{{ outerItem.vlan_tagged_interface | default(omit) }}" + vlan_bridge: "{{ outerItem.vlan_bridge | default(omit) }}" + vlan_naming: "{{ outerItem.vlan_naming | default(omit) }}" + macfilter: "{{ outerItem.macfilter | default(omit) }}" + maclist: "{{ outerItem.maclist | default([]) | join(' ') }}" + ieee80211r: "{{ outerItem.ieee80211r | default(omit) }}" + mobility_domain: "{{ mobility_domain_identifier.stdout | default(omit) }}" + ft_over_ds: "{{ outerItem.ft_over_ds | default(omit) }}" + ft_psk_generate_local: "{{ outerItem.ft_psk_generate_local | default(omit) }}" + loop: "{{ wireless_devices_add }}" + loop_control: + extended: true \ No newline at end of file diff --git a/roles/wireless/tasks/main.yml b/roles/wireless/tasks/main.yml new file mode 100644 index 0000000..f61681f --- /dev/null +++ b/roles/wireless/tasks/main.yml @@ -0,0 +1,19 @@ +--- +# Configure device section +- name: Configure device section + ansible.builtin.include_tasks: device.yml + # loop: "{{ (wireless_devices | default([])) }}" + loop: "{{ ansible_facts.openwrt_wireless | list }}" + +# Configure interface section +- name: Configure interface section + ansible.builtin.include_tasks: interface.yml + loop: "{{ wireless_interfaces | default([]) }}" + loop_control: + loop_var: outerItem + +# Apply changes and reload wireless service +- name: Apply changes and reload wireless + uci: + command: commit + notify: Reload wireless diff --git a/setupAllAPs.yml b/setupAllAPs.yml new file mode 100644 index 0000000..1e20edb --- /dev/null +++ b/setupAllAPs.yml @@ -0,0 +1,34 @@ +- hosts: accessPoints + ignore_unreachable: true + gather_facts: true + + pre_tasks: + - name: update time + command: + cmd: ntpd -dnq -p pool.ntp.org + changed_when: false + + roles: + - system + - network + - wireless + + post_tasks: + - name: Install prometheus-node-exporter-lua + opkg: + name: prometheus-node-exporter-lua + state: present + - name: Configure prometheus-node-exporter-lua + uci: + command: section + config: prometheus-node-exporter-lua + type: prometheus-node-exporter-lua + name: main + value: + listen_interface: mgmnt + listen_port: 9100 + autocommit: true + # - name: Reboot device + # ansible.builtin.command: + # cmd: "reboot" + # changed_when: false diff --git a/templates/host_vars.j2 b/templates/host_vars.j2 new file mode 100644 index 0000000..86439ae --- /dev/null +++ b/templates/host_vars.j2 @@ -0,0 +1,33 @@ +device_ip_address: "{{ ip_address }}" +device_hostname: "" + +# network_switch_vlans: +# - id: "@switch_vlan[1]" +# vlan: "128" +# ports: "0t 1t 2 3t 4 5" +# description: "hoste" +# - id: "@switch_vlan[2]" +# vlan: "136" +# ports: "0t 1t" +# description: "studenti" +# - id: "@switch_vlan[3]" +# vlan: "144" +# ports: "0t 1t 3t" +# description: "ucitele" +# - id: "@switch_vlan[4]" +# vlan: "152" +# ports: "0t 1t" +# description: "free" + +# wireless_devices: +# - id: "{# {{ device_2g_radio }} #}" +# channel: "6" +# txpower: "5" + +# wireless_interfaces_override: + # - ssid: "aurora" + # device: "{# {{ device_2g_radio }} #}" + # - ssid: "aurora - free" + # device: "{# {{ device_2g_radio }} #}" + # - ssid: "Aurora" + # device: "{# {{ device_2g_radio }} #}" \ No newline at end of file