3 Commits

Author SHA1 Message Date
itdoginfo
df8ecd5cdc fix 2024-04-18 15:29:08 +03:00
itdoginfo
5e9576258e Added workflow 2024-04-18 15:26:59 +03:00
itdoginfo
60b94f4e48 Added role 2024-04-18 15:16:25 +03:00
15 changed files with 240 additions and 1069 deletions

View File

@@ -3,9 +3,8 @@ name: Public to Ansible Galaxy
on:
push:
branches: [ "role" ]
paths:
- .github/**
- domain-routing-openwrt/**
tags:
- '*'
jobs:
build:
@@ -13,9 +12,8 @@ jobs:
steps:
- name: checkout
uses: actions/checkout@v4
- name: galaxy
uses: robertdebock/galaxy-action@1.2.0
- name: Publish Ansible role to Galaxy
uses: robertdebock/galaxy-action@1.2.1
with:
galaxy_api_key: ${{ secrets.galaxy_api_key }}
path: domain-routing-openwrt
git_branch: role

160
README-old.md Normal file
View File

@@ -0,0 +1,160 @@
# Описание
Shell скрипт и playbook для Ansible. Автоматизируют настройку роутера на OpenWrt для роутинга по доменам и спискам IP-адресов.
Полное описание происходящего: [Статья на хабре](https://habr.com/ru/articles/767464/)
[Копия в моём блоге](https://itdog.info/tochechnyj-obhod-blokirovok-po-domenam-na-routere-s-openwrt/)
## Скрипт для установки
Запуск без скачивания
```
sh <(wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-install.sh)
```
Подробности описаны в статье указаной выше.
## Ansible
Для взаимодействия c OpenWRT используется модуль [gekmihesg/ansible-openwrt](https://github.com/gekmihesg/ansible-openwrt)
Домены берутся из [отсюда](https://github.com/itdoginfo/allow-domains). Списки IP-адресов берутся с [antifilter.download](https://antifilter.download/)
Тестировалось с
- Ansible 2.10.8
- OpenWrt 21.02.7
- OpenWrt 22.03.5
- OpenWrt 23.05.2
### Выбор туннеля
- Wireguard настраивается автоматически через переменные
- OpenVPN устанавливается пакет, настраивается роутинг и зона. Само подключение (скопировать конфиг и перезапустить openvpn) нужно [настроить вручную](https://itdog.info/nastrojka-klienta-openvpn-na-openwrt/)
- Sing-box устанавливает пакет, настраивается роутинг и зона. Также кладётся темплейт в `/etc/sing-box/config.json`. Нужно настроить `config.json` и сделать `service sing-box restart`
Не работает под 21ой версией. Поэтому при его выборе playbook выдаст ошибку.
Для 22ой версии нужно установить пакет вручную.
- tun2socks настраивается только роутинг и зона. Всё остальное нужно настроить вручную
Для **tunnel** четыре возможных значения:
- wg
- openvpn
- singbox
- tun2socks
В случае использования WG обязательно нужно задать:
**wg_server_address** - ip/url wireguard сервера
**wg_private_key**, **wg_public_key** - ключи для "клиента"
**wg_client_address** - адрес роутера в wg сети
Если ваш wg сервер использует preshared_key, то раскомментируйте **wg_preshared_key** и задайте ключ
Остальное можно менять, в зависимости от того, как настроен wireguard сервер
**wg_access** и **wg_access_network** для доступа к роутеру через WG. Переменная wg_access_network должна иметь значение подсети, например 192.168.10.0/24.
### Шифрование DNS
Если ваш провайдер не подменяет DNS-запросы, ничего устанавливать не нужно.
Для **dns_encrypt** три возможных значения:
- dnscrypt
- stubby
- false/закомментировано - пропуск, ничего не устанавливается и не настраивается
### Выбор страны
Для **county** три [возможных значения](https://github.com/itdoginfo/allow-domains):
- russia-inside
- russia-outside
- ukraine
###
### Списки IP-адресов и домены
Переменные **list_** обозначают, какие списки нужно установить. true - установить, false - не устанавливать и удалить, если уже есть
Я советую использовать только домены
```
list_domains: true
```
Если вам требуются списки IP-адресов, они также поддерживаются.
При использовании **list_domains** нужен пакет dnsmasq-full.
Для 23.05 dnsmasq-full устанавливается автоматически.
Для OpenWrt 22.03 версия dnsmasq-full должна быть => 2.87, её нет в официальном репозитории, но можно установить из dev репозитория. Если это условие не выполнено, плейбук завершится с ошибкой.
[Инструкция для OpenWrt 22.03](https://t.me/itdoginf/12)
[Инструкция для OpenWrt 21.02](https://t.me/itdoginfo/8)
### Использование
Установить модуль gekmihesg/ansible-openwrt
```
ansible-galaxy install gekmihesg.openwrt
```
Скачать playbook и темплейты в /etc/ansible
```
cd /etc/ansible
git clone https://github.com/itdoginfo/domain-routing-openwrt
mv domain-routing-openwrt/* .
rm -rf domain-routing-openwrt README.md
```
Добавить роутер в файл hosts в группу openwrt
```
[openwrt]
192.168.1.1
```
Подставить переменные в **hivpn.yml**
Для работы Ansible c OpenWrt необходимо, чтоб было выполнено одно из условий:
- Отсутствие пароля для root (не рекомендуется)
- Настроен доступ через публичный SSH-ключ в [конфиге dropbear](https://openwrt.org/docs/guide-user/security/dropbear.public-key.auth)
Запуск playbook
```
ansible-playbook playbooks/hivpn.yml --limit 192.168.1.1
```
После выполнения playbook роутер сразу начнёт роутить необходмые домены в туннель/прокси.
Если у вас были ошибки и они исправились при повторном запуске playbook, но при этом роутинг не заработал, сделайте рестарт сети и скрипта:
```
service network restart
service getdomains start
```
# Скрипт для проверки конфигурации
Написан для OpenWrt 23.05 и 22.03. На 21.02 работает только половина проверок.
[x] - не обязательно означает, что эта часть не работает. Но это повод для ручной проверки.
Есть функционал сохранения вывода скрипта, конфигурации сети и firewall в файл. Все чувствительные переменные при этом затираются.
### Запуск
```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh
```
### Запустить с проверкой на подмену DNS
```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh -s dns
```
### Запустить с созданием dump
```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh -s dump
```
Поиск ошибок вручную: https://habr.com/ru/post/702388/
---
[Telegram-канал с обновлениями](https://t.me/+lW1HmBO_Fa00M2Iy)

200
README.md
View File

@@ -1,160 +1,104 @@
# Описание
Shell скрипт и playbook для Ansible. Автоматизируют настройку роутера на OpenWrt для роутинга по доменам и спискам IP-адресов.
Domain routing OpenWrt
=========
Полное описание происходящего: [Статья на хабре](https://habr.com/ru/articles/767464/)
Configuring domain routing on Openwrt router.
[Копия в моём блоге](https://itdog.info/tochechnyj-obhod-blokirovok-po-domenam-na-routere-s-openwrt/)
## Скрипт для установки
Запуск без скачивания
Role Variables
--------------
Lists
```
sh <(wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-install.sh)
country: russia-inside|russia-outside|ukraine
list_domains: true|falase
list_subnet: false|true
list_ip: false|true
list_community: false|true
```
Подробности описаны в статье указаной выше.
## Ansible
Для взаимодействия c OpenWRT используется модуль [gekmihesg/ansible-openwrt](https://github.com/gekmihesg/ansible-openwrt)
Домены берутся из [отсюда](https://github.com/itdoginfo/allow-domains). Списки IP-адресов берутся с [antifilter.download](https://antifilter.download/)
Тестировалось с
- Ansible 2.10.8
- OpenWrt 21.02.7
- OpenWrt 22.03.5
- OpenWrt 23.05.2
### Выбор туннеля
- Wireguard настраивается автоматически через переменные
- OpenVPN устанавливается пакет, настраивается роутинг и зона. Само подключение (скопировать конфиг и перезапустить openvpn) нужно [настроить вручную](https://itdog.info/nastrojka-klienta-openvpn-na-openwrt/)
- Sing-box устанавливает пакет, настраивается роутинг и зона. Также кладётся темплейт в `/etc/sing-box/config.json`. Нужно настроить `config.json` и сделать `service sing-box restart`
Не работает под 21ой версией. Поэтому при его выборе playbook выдаст ошибку.
Для 22ой версии нужно установить пакет вручную.
- tun2socks настраивается только роутинг и зона. Всё остальное нужно настроить вручную
Для **tunnel** четыре возможных значения:
- wg
- openvpn
- singbox
- tun2socks
В случае использования WG обязательно нужно задать:
**wg_server_address** - ip/url wireguard сервера
**wg_private_key**, **wg_public_key** - ключи для "клиента"
**wg_client_address** - адрес роутера в wg сети
Если ваш wg сервер использует preshared_key, то раскомментируйте **wg_preshared_key** и задайте ключ
Остальное можно менять, в зависимости от того, как настроен wireguard сервер
**wg_access** и **wg_access_network** для доступа к роутеру через WG. Переменная wg_access_network должна иметь значение подсети, например 192.168.10.0/24.
### Шифрование DNS
Если ваш провайдер не подменяет DNS-запросы, ничего устанавливать не нужно.
Для **dns_encrypt** три возможных значения:
- dnscrypt
- stubby
- false/закомментировано - пропуск, ничего не устанавливается и не настраивается
### Выбор страны
Для **county** три [возможных значения](https://github.com/itdoginfo/allow-domains):
- russia-inside
- russia-outside
- ukraine
###
### Списки IP-адресов и домены
Переменные **list_** обозначают, какие списки нужно установить. true - установить, false - не устанавливать и удалить, если уже есть
Я советую использовать только домены
Tunnel
```
list_domains: true
```
Если вам требуются списки IP-адресов, они также поддерживаются.
При использовании **list_domains** нужен пакет dnsmasq-full.
Для 23.05 dnsmasq-full устанавливается автоматически.
Для OpenWrt 22.03 версия dnsmasq-full должна быть => 2.87, её нет в официальном репозитории, но можно установить из dev репозитория. Если это условие не выполнено, плейбук завершится с ошибкой.
[Инструкция для OpenWrt 22.03](https://t.me/itdoginf/12)
[Инструкция для OpenWrt 21.02](https://t.me/itdoginfo/8)
### Использование
Установить модуль gekmihesg/ansible-openwrt
```
ansible-galaxy install gekmihesg.openwrt
tunnel: wg|openvpn|singbox|tun2socks
```
Скачать playbook и темплейты в /etc/ansible
DoH or DoT
```
cd /etc/ansible
git clone https://github.com/itdoginfo/domain-routing-openwrt
mv domain-routing-openwrt/* .
rm -rf domain-routing-openwrt README.md
dns_encrypt: false|dnscrypt|stubby
```
Добавить роутер в файл hosts в группу openwrt
Nano package
```
[openwrt]
192.168.1.1
nano: true|false
```
Подставить переменные в **hivpn.yml**
Для работы Ansible c OpenWrt необходимо, чтоб было выполнено одно из условий:
- Отсутствие пароля для root (не рекомендуется)
- Настроен доступ через публичный SSH-ключ в [конфиге dropbear](https://openwrt.org/docs/guide-user/security/dropbear.public-key.auth)
Запуск playbook
Acces from wg network to router
```
ansible-playbook playbooks/hivpn.yml --limit 192.168.1.1
wg_access: false|true
```
После выполнения playbook роутер сразу начнёт роутить необходмые домены в туннель/прокси.
Если у вас были ошибки и они исправились при повторном запуске playbook, но при этом роутинг не заработал, сделайте рестарт сети и скрипта:
If wireguard is used:
```
service network restart
service getdomains start
wg_server_address: wg-server-host
wg_private_key: privatekey-client
wg_public_key: publickey-client
#wg_preshared_key: presharedkey-client
wg_client_port: 51820
wg_client_address: ip-client
wg_access_network: wg-network
```
# Скрипт для проверки конфигурации
Dependencies
------------
Написан для OpenWrt 23.05 и 22.03. На 21.02 работает только половина проверок.
[gekmihesg.openwrt](https://github.com/gekmihesg/ansible-openwrt)
[x] - не обязательно означает, что эта часть не работает. Но это повод для ручной проверки.
Есть функционал сохранения вывода скрипта, конфигурации сети и firewall в файл. Все чувствительные переменные при этом затираются.
Example Playbook
----------------
### Запуск
The inventory file must contain the group `[openwrt]` where your router will be located.
Wireguard, only domains, stubby, Russia, acces from wg network, host 192.168.1.1
```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh
- hosts: 192.168.1.1
remote_user: root
roles:
- domain-routing-openwrt
vars:
tunnel: wg
dns_encrypt: stubby
country: russia-inside
wg_access: true
wg_server_address: wg-server-host
wg_private_key: privatekey-client
wg_public_key: publickey-client
wg_preshared_key: presharedkey-client
wg_listen_port: 51820
wg_client_port: 51820
wg_client_address: ip-client
wg_access_network: wg-network
```
### Запустить с проверкой на подмену DNS
Sing-box, stubby, Russia
```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh -s dns
- hosts: 192.168.1.1
remote_user: root
roles:
- domain-routing-openwrt
vars:
tunnel: singbox
dns_encrypt: stubby
country: russia-inside
```
### Запустить с созданием dump
```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh -s dump
```
License
-------
Поиск ошибок вручную: https://habr.com/ru/post/702388/
---
[Telegram-канал с обновлениями](https://t.me/+lW1HmBO_Fa00M2Iy)
GNU General Public License v3.0

View File

@@ -1,104 +0,0 @@
Domain routing OpenWrt
=========
Configuring domain routing on Openwrt router.
Role Variables
--------------
Lists
```
country: russia-inside|russia-outside|ukraine
list_domains: true|falase
list_subnet: false|true
list_ip: false|true
list_community: false|true
```
Tunnel
```
tunnel: wg|openvpn|singbox|tun2socks
```
DoH or DoT
```
dns_encrypt: false|dnscrypt|stubby
```
Nano package
```
nano: true|false
```
Acces from wg network to router
```
wg_access: false|true
```
If wireguard is used:
```
wg_server_address: wg-server-host
wg_private_key: privatekey-client
wg_public_key: publickey-client
#wg_preshared_key: presharedkey-client
wg_client_port: 51820
wg_client_address: ip-client
wg_access_network: wg-network
```
Dependencies
------------
[gekmihesg.openwrt](https://github.com/gekmihesg/ansible-openwrt)
Example Playbook
----------------
The inventory file must contain the group `[openwrt]` where your router will be located.
Wireguard, only domains, stubby, Russia, acces from wg network, host 192.168.1.1
```
- hosts: 192.168.1.1
remote_user: root
roles:
- domain-routing-openwrt
vars:
tunnel: wg
dns_encrypt: stubby
country: russia-inside
wg_access: true
wg_server_address: wg-server-host
wg_private_key: privatekey-client
wg_public_key: publickey-client
wg_preshared_key: presharedkey-client
wg_listen_port: 51820
wg_client_port: 51820
wg_client_address: ip-client
wg_access_network: wg-network
```
Sing-box, stubby, Russia
```
- hosts: 192.168.1.1
remote_user: root
roles:
- domain-routing-openwrt
vars:
tunnel: singbox
dns_encrypt: stubby
country: russia-inside
```
License
-------
GNU General Public License v3.0

View File

@@ -1,5 +0,0 @@
config sing-box 'main'
option enabled '1'
option user 'root'
option conffile '/etc/sing-box/config.json'
option workdir '/usr/share/sing-box'

View File

@@ -1,8 +0,0 @@
#!/bin/sh
{% if tunnel == "wg" %}
ip route add table vpn default dev wg0
{% elif (tunnel == "openvpn") or (tunnel == "singbox") or (tunnel == "tun2socks") %}
sleep 10
ip route add table vpn default dev tun0
{% endif %}

View File

@@ -1,70 +0,0 @@
#!/bin/sh /etc/rc.common
START=99
start () {
{% if ansible_distribution_major_version >= "22" and country == "russia-inside" %}
DOMAINS=https://raw.githubusercontent.com/itdoginfo/allow-domains/main/Russia/inside-dnsmasq-nfset.lst
{% endif %}
{% if ansible_distribution_major_version >= "22" and country == "russia-outside" %}
DOMAINS=https://raw.githubusercontent.com/itdoginfo/allow-domains/main/Russia/outside-dnsmasq-nfset.lst
{% endif %}
{% if ansible_distribution_major_version >= "22" and country == "ukraine" %}
DOMAINS=https://raw.githubusercontent.com/itdoginfo/allow-domains/main/Ukraine/inside-dnsmasq-nfset.lst
{% endif %}
{% if ansible_distribution_major_version < "22" and country == "russia-inside" %}
DOMAINS=https://raw.githubusercontent.com/itdoginfo/allow-domains/main/Russia/inside-dnsmasq-ipset.lst
{% endif %}
{% if ansible_distribution_major_version < "22" and country == "russia-outside" %}
DOMAINS=https://raw.githubusercontent.com/itdoginfo/allow-domains/main/Russia/outside-dnsmasq-ipset.lst
{% endif %}
{% if ansible_distribution_major_version < "22" and country == "ukraine" %}
DOMAINS=https://raw.githubusercontent.com/itdoginfo/allow-domains/main/Ukraine/inside-dnsmasq-ipset.lst
{% endif %}
count=0
while true; do
if curl -m 3 github.com; then
curl -f $DOMAINS --output /tmp/dnsmasq.d/domains.lst
break
else
echo "GitHub is not available. Check the internet availability [$count]"
count=$((count+1))
fi
done
if dnsmasq --conf-file=/tmp/dnsmasq.d/domains.lst --test 2>&1 | grep -q "syntax check OK"; then
/etc/init.d/dnsmasq restart
fi
{% if ansible_distribution_major_version >= "22" and (list_ip or list_community) %}
echo "Flush sets"
nft flush ruleset
{% endif %}
{% if list_subnet or list_ip or list_community %}
dir=/tmp/lst
mkdir -p $dir
count=0
while true; do
if curl -m 3 https://antifilter.download/; then
{% if list_subnet %}
curl -f -z $dir/subnet.lst https://antifilter.download/list/subnet.lst --output $dir/subnet.lst
{% endif %}
{% if list_ip %}
curl -f -z $dir/ip.lst https://antifilter.download/list/ip.lst --output $dir/ip.lst
{% endif %}
{% if list_community %}
curl -f -z $dir/community.lst https://community.antifilter.download/list/community.lst --output $dir/community.lst
{% endif %}
break
else
echo "antifilter.download is not available. Check the internet availability [$count]"
count=$((count+1))
fi
done
echo "Firewall restart"
/etc/init.d/firewall restart
{% endif %}
}

View File

@@ -1,28 +0,0 @@
{
"log": {
"level": "debug"
},
"inbounds": [
{
"type": "tun",
"interface_name": "tun0",
"domain_strategy": "ipv4_only",
"inet4_address": "172.16.250.1/30",
"auto_route": false,
"strict_route": false,
"sniff": true
}
],
"outbounds": [
{
"type": "$TYPE",
"server": "$HOST",
"server_port": $PORT,
"method": "$METHOD",
"password": "$PASS"
}
],
"route": {
"auto_detect_interface": true
}
}

View File

@@ -1,4 +1,7 @@
---
galaxy_info:
role_name: domain_routing_openwrt
namespace: itdoginfo
author: itdog
description: Configuring domain routing on Openwrt router
issue_tracker_url: https://github.com/itdoginfo/domain-routing-openwrt/issues

View File

@@ -1,719 +0,0 @@
---
- hosts: openwrt
remote_user: root
roles:
- gekmihesg.openwrt
vars:
ansible_template_dir: /etc/ansible/templates/
list_domains: true
list_subnet: false
list_ip: false
list_community: false
tunnel: wg
dns_encrypt: false
country: russia-inside
nano: true
wg_access: false
wg_server_address: wg-server-host
wg_private_key: privatekey-client
wg_public_key: publickey-client
#wg_preshared_key: presharedkey-client
wg_listen_port: 51820
wg_client_port: 51820
wg_client_address: ip-client
wg_access_network: wg-network
tasks:
# Dnsmasq version check
- name: Get dnsmasq version
shell: opkg list-installed | grep dnsmasq-full | awk '{print $3}'
register: dnsmasqfull_version
- name: debug
debug:
var: ansible_distribution_major_version
# Packages installation
- name: install wg
opkg:
name: "{{ item }}"
state: present
loop:
- kmod-wireguard
- wireguard-tools
when: tunnel == "wg"
- name: install openvpn
opkg:
name: "{{ item }}"
state: present
loop:
- openvpn-openssl
when: tunnel == "openvpn"
- name: install singbox
opkg:
name: "{{ item }}"
state: present
loop:
- sing-box
when: tunnel == "singbox" and ansible_distribution_major_version >= "23"
- name: install curl
opkg:
name: "{{ item }}"
state: present
loop:
- curl
- name: install nano
opkg:
name: "{{ item }}"
state: present
loop:
- nano
when: nano
- name: install ipset
opkg:
name: ipset
state: present
when: ansible_distribution_major_version < "22"
- name: install dnsmasq-full (23)
shell: opkg update && cd /tmp/ && opkg download dnsmasq-full && opkg remove dnsmasq && opkg install dnsmasq-full --cache /tmp/ && [ -f /etc/config/dhcp-opkg ] && cp etc/config/dhcp /etc/config/dhcp-old && mv /etc/config/dhcp-opkg /etc/config/dhcp
when: ansible_distribution_major_version >= "23" and list_domains and not dnsmasqfull_version.stdout
ignore_errors: true
# Getdomains script configure
- name: getdomains script copy
template:
src: "{{ ansible_template_dir }}openwrt-getdomains.j2"
dest: "/etc/init.d/getdomains"
mode: a+x
trim_blocks: false
notify:
- Run getdomains script
- name: create simplink in rc.d
file:
src: "/etc/init.d/getdomains"
dest: "/etc/rc.d/S99getdomains"
state: link
notify:
- Run getdomains script
- name: check string in crontab
shell: grep "getdomains" /etc/crontabs/root
register: check_cron
ignore_errors: true
- name: add script to cron
lineinfile:
path: /etc/crontabs/root
create: yes
line: "0 4 * * * /etc/init.d/getdomains start"
when: check_cron.stdout == ""
- name: enable and start crontab
service:
name: cron
state: started
enabled: yes
# Configure route table
- name: Route for vpn table
template:
src: "{{ ansible_template_dir }}openwrt-30-vpnroute.j2"
dest: "/etc/hotplug.d/iface/30-vpnroute"
mode: 0644
- name: Check string in rt_tables
shell: grep "99 vpn" /etc/iproute2/rt_tables
register: check_rt_tables
ignore_errors: true
- name: add route table
lineinfile:
path: /etc/iproute2/rt_tables
line: "99 vpn"
when: check_rt_tables.stdout == ""
notify:
- Restart network
# Configure WG
- name: add wg interface
uci:
command: add
config: network
type: interface
name: wg0
when: tunnel == "wg"
- name: configure wg interface
uci:
command: set
key: network.wg0
value:
proto: wireguard
private_key: "{{ wg_private_key }}"
listen_port: "{{ wg_listen_port }}"
addresses:
- "{{ wg_client_address }}"
when: tunnel == "wg"
notify:
- Restart network
- name: set wg client without wg_preshared_key
uci:
command: section
config: network
type: wireguard_wg0
find_by:
name: wg0_client
value:
public_key: "{{ wg_public_key }}"
route_allowed_ips: 0
persistent_keepalive: 25
endpoint_host: "{{ wg_server_address }}"
allowed_ips: 0.0.0.0/0
endpoint_port: "{{ wg_client_port }}"
when: wg_preshared_key is undefined and tunnel == "wg"
notify:
- Restart network
- name: set wg client with wg_preshared_key
uci:
command: section
config: network
type: wireguard_wg0
find_by:
name: wg0_client
value:
public_key: "{{ wg_public_key }}"
preshared_key: "{{ wg_preshared_key }}"
route_allowed_ips: 0
persistent_keepalive: 25
endpoint_host: "{{ wg_server_address }}"
allowed_ips: 0.0.0.0/0
endpoint_port: "{{ wg_client_port }}"
when: wg_preshared_key is defined and tunnel == "wg"
- name: set WG firewall zone
uci:
command: section
config: firewall
type: zone
find_by:
name: wg
value:
forward: REJECT
output: ACCEPT
name: wg
input: REJECT
masq: 1
mtu_fix: 1
network: wg0
family: ipv4
when: tunnel == "wg"
- name: add WG forwarding
uci:
command: section
config: firewall
type: forwarding
find_by:
name: wg-lan
value:
dest: wg
src: lan
family: ipv4
when: tunnel == "wg"
# Configure Sing-box
- name: set sing-box firewall zone. Only >=22
uci:
command: section
config: firewall
type: zone
find_by:
name: tun
value:
forward: ACCEPT
output: ACCEPT
name: tun
input: ACCEPT
masq: 1
mtu_fix: 1
device: tun0
family: ipv4
when: tunnel == "singbox"
failed_when: ansible_distribution_major_version < "22"
notify:
- Restart firewall
- name: template for sing-box.json
template:
src: "{{ ansible_template_dir }}sing-box-json.j2"
dest: "/etc/sing-box/config.json"
mode: 0644
when: tunnel == "singbox"
failed_when: ansible_distribution_major_version < "22"
- name: template for config/sing-box
template:
src: "{{ ansible_template_dir }}config-sing-box.j2"
dest: "/etc/config/sing-box"
mode: 0600
when: tunnel == "singbox"
failed_when: ansible_distribution_major_version < "22"
# Configure OpenVPN, tun2socks
- name: set {{ tunnel }} firewall zone
uci:
command: section
config: firewall
type: zone
find_by:
name: tun
value:
forward: REJECT
output: ACCEPT
name: tun
input: REJECT
masq: 1
mtu_fix: 1
device: tun0
family: ipv4
when: tunnel == "openvpn" or tunnel == "tun2socks"
notify:
- Restart firewall
- name: add {{ tunnel }} forwarding
uci:
command: section
config: firewall
type: forwarding
find_by:
name: lan-tun
value:
dest: tun
src: lan
family: ipv4
when: tunnel == "openvpn" or tunnel == "tun2socks" or tunnel == "singbox"
notify:
- Restart firewall
# Configure network
- name: set rule mark0x1
uci:
command: section
config: network
type: rule
find_by:
name: mark0x1
value:
mark: "0x1"
priority: 100
lookup: vpn
- name: set disable dns for wan
uci:
command: set
key: network.wan
value:
peerdns: 0
when: ansible_distribution_major_version < "22"
- name: uci commit firewall
uci:
command: commit
config: firewall
notify:
- Restart firewall
- name: uci commit network
uci:
command: commit
config: network
notify:
- Restart network
# Configure firewall
- name: add ipset for subnet (<22)
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_subnets
value:
match: dst_net
storage: hash
loadfile: /tmp/lst/subnet.lst
when: ansible_distribution_major_version < "22" and list_subnet
- name: add ipset for ip (<22)
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_ip
value:
match: dst_net
storage: hash
loadfile: /tmp/lst/ip.lst
hashsize: 9900000
maxelem: 9900000
when: ansible_distribution_major_version < "22" and list_ip
- name: add ipset for community (<22)
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_community
value:
match: dst_net
storage: hash
loadfile: /tmp/lst/community.lst
hashsize: 9900000
maxelem: 9900000
when: ansible_distribution_major_version < "22" and list_community
- name: add nfset for subnet (22)
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_subnets
value:
match: dst_net
loadfile: /tmp/lst/subnet.lst
when: ansible_distribution_major_version >= "22" and list_subnet
- name: add nfset for ip (22)
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_ip
value:
match: dst_net
loadfile: /tmp/lst/ip.lst
when: ansible_distribution_major_version >= "22" and list_ip
- name: add nfset for community (22)
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_community
value:
match: dst_net
loadfile: /tmp/lst/community.lst
when: ansible_distribution_major_version >= "22" and list_community
- name: add ipset for domains (<22). If failed, repeat playbook. If failed is repeated check dnsmasq-full.
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_domains
value:
match: dst_net
storage: hash
when: ansible_distribution_major_version < "22" and list_domains
- name: add nfset for domains (>=22). If failed, repeat playbook. If failed is repeated check dnsmasq-full.
uci:
command: section
config: firewall
type: ipset
find_by:
name: vpn_domains
value:
match: dst_net
when: ansible_distribution_major_version >= "22" and list_domains
- name: add mark rule vpn_subnet
uci:
command: section
config: firewall
type: rule
find_by:
name: mark_subnet
value:
src: lan
dest: "*"
proto: all
ipset: vpn_subnets
set_mark: "0x1"
target: MARK
family: ipv4
when: list_subnet
- name: add mark rule vpn_ip
uci:
command: section
config: firewall
type: rule
find_by:
name: mark_ip
value:
src: lan
dest: "*"
proto: all
ipset: vpn_ip
set_mark: "0x1"
target: MARK
family: ipv4
when: list_ip
- name: add mark rule vpn_community
uci:
command: section
config: firewall
type: rule
find_by:
name: mark_community
value:
src: lan
dest: "*"
proto: all
ipset: vpn_community
set_mark: "0x1"
target: MARK
family: ipv4
when: list_community
- name: add mark rule vpn_domains
uci:
command: section
config: firewall
type: rule
find_by:
name: mark_domains
value:
src: lan
dest: "*"
proto: all
ipset: vpn_domains
set_mark: "0x1"
target: MARK
family: ipv4
when: (ansible_distribution_major_version < "22" and list_domains) or (ansible_distribution_major_version >= "22" and list_domains)
- name: wg access route
uci:
command: section
config: network
type: route
find_by:
name: wg_access_route
value:
interface: wg0
target: "{{ wg_access_network }}"
when: wg_access
- name: set WG firewall zone
uci:
command: section
config: firewall
type: zone
find_by:
name: wg
value:
input: ACCEPT
when: wg_access
# Remove unused rules and ipset
- name: Remove ipset for ip
uci:
command: absent
config: firewall
type: ipset
find_by:
name: vpn_ip
when: not list_ip
- name: Remove rule for ip
uci:
command: absent
config: firewall
type: rule
find_by:
name: mark_ip
when: not list_ip
- name: Remove ipset for subnet
uci:
command: absent
config: firewall
type: ipset
find_by:
name: vpn_subnets
when: not list_subnet
- name: Remove rule for subnet
uci:
command: absent
config: firewall
type: rule
find_by:
name: mark_subnet
when: not list_subnet
- name: Remove ipset for community
uci:
command: absent
config: firewall
type: ipset
find_by:
name: vpn_community
when: not list_community
- name: Remove rule for community
uci:
command: absent
config: firewall
type: rule
find_by:
name: mark_community
when: not list_community
- name: Remove ipset for domains
uci:
command: absent
config: firewall
type: ipset
find_by:
name: vpn_domains
when: not list_domains
- name: Remove rule for domains
uci:
command: absent
config: firewall
type: rule
find_by:
name: mark_domains
when: not list_domains
# Configure DNS resolver
- name: install dnscrypt-proxy2
opkg:
name: dnscrypt-proxy2
state: present
when: dns_encrypt == "dnscrypt"
- name: check string in dnscrypt-proxy.toml
shell: grep "# server_names" /etc/dnscrypt-proxy2/dnscrypt-proxy.toml
register: check_server_names
ignore_errors: true
when: dns_encrypt == "dnscrypt"
- name: dnscrypt2 enable exact servers
lineinfile:
path: /etc/dnscrypt-proxy2/dnscrypt-proxy.toml
regexp: "# server_names ="
line: "server_names = ['google', 'cloudflare', 'scaleway-fr', 'yandex']"
when: dns_encrypt == "dnscrypt" and check_server_names.stdout
notify:
- Restart dnscrypt-proxy
- name: edit dhcp config. add localhost server
lineinfile:
path: /etc/config/dhcp
firstmatch: "true"
insertafter: "option leasefile '/tmp/dhcp.leases'"
line: "{{ item }}"
with_items:
- " list server '127.0.0.53#53'"
- " option noresolv '1'"
notify:
- Restart dnsmasq
when: dns_encrypt == "dnscrypt"
- name: install stubby
opkg:
name: stubby
state: present
when: dns_encrypt == "stubby"
- name: edit dhcp config. add localhost server
lineinfile:
path: /etc/config/dhcp
firstmatch: "true"
insertafter: "option leasefile '/tmp/dhcp.leases'"
line: "{{ item }}"
with_items:
- " list server '127.0.0.1#5453'"
- " option noresolv '1'"
notify:
- Restart dnsmasq
when: dns_encrypt == "stubby"
# Commit and handlers
- name: uci commit firewall
uci:
command: commit
config: firewall
notify:
- Restart firewall
- name: uci commit network
uci:
command: commit
config: network
notify:
- Restart network
handlers:
- name: Restart network
service:
name: network
state: restarted
- name: Restart firewall
service:
name: firewall
state: restarted
- name: Run getdomains script
service:
name: getdomains
state: restarted
- name: Restart dnscrypt-proxy
service:
name: dnscrypt-proxy
state: restarted
enabled: yes
- name: Restart dnsmasq
service:
name: dnsmasq
state: restarted

View File

@@ -3,4 +3,4 @@
remote_user: root
roles:
- domain-routing-openwrt
- domain_routing_openwrt