15 Commits

Author SHA1 Message Date
itdoginfo
96c8ceee44 Merge pull request #9 from itdoginfo/role
Conversion to a role
2024-04-18 16:59:35 +03:00
itdoginfo
92f25df564 Changed to master branch 2024-04-18 16:58:59 +03:00
itdoginfo
ec9971ef4b Redrafting 2024-04-18 16:54:27 +03:00
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
itdoginfo
8ca4fb08d6 Fixed route check 2024-04-10 14:17:40 +03:00
itdoginfo
301da76110 Added show date 2024-04-04 14:37:27 +03:00
itdoginfo
d9e9317995 Cleanup 2024-04-02 18:59:15 +03:00
itdoginfo
15ad1f5115 Added UCI sing-box validation, curl to --interface check for proxy 2024-03-13 20:41:59 +03:00
itdoginfo
d0fad434cc (・x・) 2024-03-09 12:29:54 +03:00
itdoginfo
8f18b95b1e Some fixes 2024-02-20 13:53:13 +03:00
itdoginfo
6ec2438165 Fixed wg_access_network 2024-01-18 12:33:26 +03:00
itdoginfo
9baaddabc6 Added wg_access and fixed dnsmasq check issue 2024-01-12 13:34:13 +03:00
itdoginfo
388ad72492 Some fixes 2024-01-12 13:33:19 +03:00
12 changed files with 399 additions and 286 deletions

18
.github/workflows/public-galaxy.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Public to Ansible Galaxy
on:
push:
branches: [ "master" ]
tags:
- '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v4
- name: Publish Ansible role to Galaxy
uses: robertdebock/galaxy-action@1.2.1
with:
galaxy_api_key: ${{ secrets.galaxy_api_key }}

107
README.EN.md Normal file
View File

@@ -0,0 +1,107 @@
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
wg_access_network: 192.168.80.0/24 (for example)
```
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: true
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

233
README.md
View File

@@ -1,39 +1,116 @@
[English role README](https://github.com/itdoginfo/domain-routing-openwrt/blob/master/README.EN.md)
# Описание # Описание
Shell скрипт и playbook для Ansible. Автоматизируют настройку OpenWrt роутера для обхода блокировок по доменам и спискам IP-адресов. Shell скрипт и playbook для Ansible. Автоматизируют настройку роутера на OpenWrt для роутинга по доменам и спискам IP-адресов.
Полное описание происходящего: [Статья на хабре](https://habr.com/ru/articles/767464/) Полное описание происходящего:
- [Статья на хабре](https://habr.com/ru/articles/767464/)
- [Копия в моём блоге](https://itdog.info/tochechnyj-obhod-blokirovok-po-domenam-na-routere-s-openwrt/)
[Копия в моём блоге](https://itdog.info/tochechnyj-obhod-blokirovok-po-domenam-na-routere-s-openwrt/) # Скрипт для установки
## Скрипт для установки
Запуск без скачивания
``` ```
sh <(wget -O - https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/getdomains-install.sh) sh <(wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-install.sh)
``` ```
Запуск со скачиванием ## Скрипт для проверки конфигурации
Написан для OpenWrt 23.05 и 22.03. На 21.02 работает только половина проверок.
[x] - не обязательно означает, что эта часть не работает. Но это повод для ручной проверки.
### Запуск
``` ```
wget https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/getdomains-install.sh && sh getdomains-install.sh 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
```
## Ansible ### Запустить с созданием dump
Для взаимодействия c OpenWRT используется модуль [gekmihesg/ansible-openwrt](https://github.com/gekmihesg/ansible-openwrt) Все чувствительные переменные затираются.
Домены берутся из [отсюда](https://github.com/itdoginfo/allow-domains). Списки IP-адресов берутся с [antifilter.download](https://antifilter.download/) ```
wget -O - https://raw.githubusercontent.com/itdoginfo/domain-routing-openwrt/master/getdomains-check.sh | sh -s dump
```
Поиск ошибок вручную: https://habr.com/ru/post/702388/
# Ansible
Установить роль
```
ansible-galaxy role install itdoginfo.domain_routing_openwrt
```
Примеры playbooks
Wireguard, only domains, stubby, Russia, acces from wg network (примерное значение 192.168.80.0/24), host 192.168.1.1
```
- hosts: 192.168.1.1
remote_user: root
roles:
- itdoginfo.domain_routing_openwrt
vars:
tunnel: wg
dns_encrypt: stubby
country: russia-inside
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: true
wg_access_network: wg-network
```
Sing-box, stubby, Russia
```
- hosts: 192.168.1.1
remote_user: root
roles:
- itdoginfo.domain_routing_openwrt
vars:
tunnel: singbox
dns_encrypt: stubby
country: russia-inside
```
В inventory файле роутер обязательно должен быть в группе `[openwrt]`
```
[openwrt]
192.168.1.1
```
Для работы Ansible c OpenWrt необходимо, чтоб было выполнено одно из условий:
- Отсутствие пароля для root (не рекомендуется)
- Настроен доступ через публичный SSH-ключ в [конфиге dropbear](https://openwrt.org/docs/guide-user/security/dropbear.public-key.auth)
После выполнения playbook роутер сразу начнёт роутить необходмые домены в туннель/прокси.
Если у вас были ошибки и они исправились при повторном запуске playbook, но при этом роутинг не заработал, сделайте рестарт сети и скрипта:
```
service network restart
service getdomains start
```
Тестировалось с Тестировалось с
- Ansible 2.10.8 - Ansible 2.10.8
- OpenWrt 21.02.7 - OpenWrt 21.02.7
- OpenWrt 22.03.5 - OpenWrt 22.03.5
- OpenWrt 23.05.0 - OpenWrt 23.05.2
### Выбор туннеля ## Выбор туннеля
- Wireguard настраивается автоматически через переменные - Wireguard настраивается автоматически через переменные
- OpenVPN устанавливается пакет, настраивается роутинг и зона. Само подключение (скопировать конфиг и перезапустить openvpn) нужно [настроить вручную](https://itdog.info/nastrojka-klienta-openvpn-na-openwrt/) - OpenVPN устанавливается пакет, настраивается роутинг и зона. Само подключение (скопировать конфиг и перезапустить openvpn) нужно [настроить вручную](https://itdog.info/nastrojka-klienta-openvpn-na-openwrt/)
- Sing-box устанавливает пакет, настраивается роутинг и зона. Также кладётся темплейт в `/etc/sing-box/config.json`. Нужно настроить `config.json` и сделать `service sing-box restart` - Sing-box устанавливает пакет, настраивается роутинг и зона. Также кладётся темплейт в `/etc/sing-box/config.json`. [Нужно настроить](https://habr.com/ru/articles/767458/) `config.json` и сделать `service sing-box restart`
Не работает под 21ой версией. Поэтому при его выборе playbook выдаст ошибку. Не работает под 21ой версией. Поэтому при его выборе playbook выдаст ошибку.
Для 22ой версии нужно установить пакет вручную. Для 22ой версии нужно установить пакет вручную.
- tun2socks настраивается только роутинг и зона. Всё остальное нужно настроить вручную - tun2socks настраивается только роутинг и зона. Всё остальное нужно настроить вручную
@@ -44,19 +121,25 @@ wget https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/ge
- singbox - singbox
- tun2socks - tun2socks
В случае использования WG обязательно нужно задать: В случае использования WG:
```
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_server_address** - ip/url wireguard сервера Если ваш wg сервер не использует `preshared_key`, то просто не задавайте её.
**wg_private_key**, **wg_public_key** - ключи для "клиента" **wg_access** и **wg_access_network** для доступа к роутеру через WG. Переменная wg_access_network должна иметь значение подсети, например 192.168.10.0/24.
```
wg_access_network: wg-network
wg_access: true
```
**wg_client_address** - адрес роутера в wg сети ## Шифрование DNS
Если ваш wg сервер использует preshared_key, то раскомментируйте **wg_preshared_key** и задайте ключ
Остальное можно менять, в зависимости от того, как настроен wireguard сервер
### Шифрование DNS
Если ваш провайдер не подменяет DNS-запросы, ничего устанавливать не нужно. Если ваш провайдер не подменяет DNS-запросы, ничего устанавливать не нужно.
Для **dns_encrypt** три возможных значения: Для **dns_encrypt** три возможных значения:
@@ -64,15 +147,25 @@ wget https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/ge
- stubby - stubby
- false/закомментировано - пропуск, ничего не устанавливается и не настраивается - false/закомментировано - пропуск, ничего не устанавливается и не настраивается
### Выбор страны ## Выбор страны
Для **county** три [возможных значения](https://github.com/itdoginfo/allow-domains): Выбор списка доменов.
Для **county** три [возможных значения](https://github.com/itdoginfo/allow-domains):
- russia-inside - russia-inside
- russia-outside - russia-outside
- ukraine - ukraine
### Списки IP-адресов и домены ## Списки IP-адресов
Списки IP-адресов берутся с [antifilter.download](https://antifilter.download/)
Переменные **list_** обозначают, какие списки нужно установить. true - установить, false - не устанавливать и удалить, если уже есть Переменные **list_** обозначают, какие списки нужно установить. true - установить, false - не устанавливать и удалить, если уже есть
Доступные переменные
```
list_domains: true
list_subnet: false
list_ip: falses
list_community: false
```
Я советую использовать только домены Я советую использовать только домены
``` ```
list_domains: true list_domains: true
@@ -89,85 +182,13 @@ wget https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/ge
[Инструкция для OpenWrt 21.02](https://t.me/itdoginfo/8) [Инструкция для OpenWrt 21.02](https://t.me/itdoginfo/8)
### Использование ## Текстовый редактор nano
Устанавливается по умолчанию
Установить модуль gekmihesg/ansible-openwrt Можно выключить
``` ```
ansible-galaxy install gekmihesg.openwrt nano: false
``` ```
Скачать playbook и темплейты в /etc/ansible
```
cd /etc/ansible
git clone https://github.com/itdoginfo/ansible-openwrt-hirkn
mv ansible-openwrt-hirkn/* .
rm -rf ansible-openwrt-hirkn README.md
```
Добавить роутер в файл hosts в группу openwrt
```
[openwrt]
192.168.1.1
```
Подставить переменные в **hirkn.yml**
Для работы Ansible c OpenWrt необходимо, чтоб было выполнено одно из условий:
- Отсутствие пароля для root (не рекомендуется)
- Настроен доступ через публичный SSH-ключ в [конфиге dropbear](https://openwrt.org/docs/guide-user/security/dropbear.public-key.auth)
Запуск playbook
```
ansible-playbook playbooks/hirkn.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/ansible-openwrt-hirkn/master/getdomains-check.sh | sh
```
### Запустить с проверкой на подмену DNS
```
wget -O - https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/getdomains-check.sh | sh -s dns
```
### Запустить с созданием dump
```
wget -O - https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/getdomains-check.sh | sh -s dump
```
### Скачать и потом запустить
```
wget https://raw.githubusercontent.com/itdoginfo/ansible-openwrt-hirkn/master/getdomains-check.sh
chmod +x check-hirkn.sh
./check-hirkn.sh
```
С созданием dump
```
./check-hirkn.sh dump
```
Поиск ошибок вручную: https://habr.com/ru/post/702388/
--- ---
[Telegram-канал с обновлениями](https://t.me/+lW1HmBO_Fa00M2Iy) [Telegram-канал с обновлениями](https://t.me/+lW1HmBO_Fa00M2Iy)

12
defaults/main.yml Normal file
View File

@@ -0,0 +1,12 @@
---
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_listen_port: 51820

View File

@@ -1,6 +1,6 @@
#!/bin/sh #!/bin/sh
HIRKN=/etc/init.d/hirkn HIVPN=/etc/init.d/hivpn
GETDOMAINS=/etc/init.d/getdomains GETDOMAINS=/etc/init.d/getdomains
DUMP=/tmp/dump.txt DUMP=/tmp/dump.txt
@@ -23,6 +23,7 @@ MODEL=$(grep machine /proc/cpuinfo | cut -d ':' -f 2)
RELEASE=$(grep OPENWRT_RELEASE /etc/os-release | awk -F '"' '{print $2}') RELEASE=$(grep OPENWRT_RELEASE /etc/os-release | awk -F '"' '{print $2}')
printf "\033[34;1mModel:$MODEL\033[0m\n" printf "\033[34;1mModel:$MODEL\033[0m\n"
printf "\033[34;1mVersion: $RELEASE\033[0m\n" printf "\033[34;1mVersion: $RELEASE\033[0m\n"
printf "\033[34;1mDate: $(date)\033[0m\n"
VERSION_ID=$(grep VERSION_ID /etc/os-release | awk -F '"' '{print $2}' | awk -F. '{print $1}') VERSION_ID=$(grep VERSION_ID /etc/os-release | awk -F '"' '{print $2}' | awk -F. '{print $1}')
RAM=$(free -m | grep Mem: | awk '{print $2}') RAM=$(free -m | grep Mem: | awk '{print $2}')
@@ -93,14 +94,16 @@ if curl -6 -s https://ifconfig.io | egrep -q "(::)?[0-9a-fA-F]{1,4}(::?[0-9a-fA-
checkpoint_false "IPv6 detected. This script does not currently work with IPv6" checkpoint_false "IPv6 detected. This script does not currently work with IPv6"
fi fi
# PPPoE
if uci show network.wan.proto | grep -q "pppoe"; then
checkpoint_false "PPPoE is used. That could be a problem"
fi
# Tunnels # Tunnels
WIREGUARD=$(opkg list-installed | grep -c wireguard-tools ) WIREGUARD=$(opkg list-installed | grep -c wireguard-tools )
if [ $WIREGUARD -eq 1 ]; then if [ $WIREGUARD -eq 1 ]; then
checkpoint_true "Wireguard-tools package" checkpoint_true "Wireguard-tools package"
WG=true WG=true
else
checkpoint_false "Wireguard-tools package"
echo "If you don't use WG it's OK"
fi fi
if [ "$WG" == true ]; then if [ "$WG" == true ]; then
@@ -127,7 +130,7 @@ if [ "$WG" == true ]; then
fi fi
# Check route table # Check route table
ROUTE_TABLE=$(ip route show table vpn | grep -c "default dev wg0 scope link" ) ROUTE_TABLE=$(ip route show table vpn | grep -c "default dev wg0" )
if [ $ROUTE_TABLE -eq 1 ]; then if [ $ROUTE_TABLE -eq 1 ]; then
checkpoint_true "Route table WG" checkpoint_true "Route table WG"
else else
@@ -139,9 +142,6 @@ fi
if opkg list-installed | grep -q openvpn; then if opkg list-installed | grep -q openvpn; then
checkpoint_true "OpenVPN package" checkpoint_true "OpenVPN package"
OVPN=true OVPN=true
else
checkpoint_false "OpenVPN package"
echo "If you don't use OpenVPN it's OK"
fi fi
# Check OpenVPN # Check OpenVPN
@@ -166,7 +166,7 @@ if [ "$OVPN" == true ]; then
fi fi
# Check route table # Check route table
if ip route show table vpn | grep -q "default dev tun0 scope link"; then if ip route show table vpn | grep -q "default dev tun0"; then
checkpoint_true "Route table OpenVPN" checkpoint_true "Route table OpenVPN"
else else
checkpoint_false "Route table OpenVPN" checkpoint_false "Route table OpenVPN"
@@ -178,34 +178,37 @@ if opkg list-installed | grep -q sing-box; then
checkpoint_true "Sing-box package" checkpoint_true "Sing-box package"
# Check route table # Check route table
if ip route show table vpn | grep -q "default dev tun0 scope link"; then if ip route show table vpn | grep -q "default dev tun0"; then
checkpoint_true "Route table Sing-box" checkpoint_true "Route table Sing-box"
else else
checkpoint_false "Route table Sing-box. Try service network restart. Details: https://cli.co/n7xAbc1" checkpoint_false "Route table Sing-box. Try service network restart. Details: https://cli.co/n7xAbc1"
fi fi
# Sing-box uci validation
if uci show sing-box 2>&1 | grep -q "Parse error"; then
checkpoint_false "Sing-box UCI config. Check /etc/config/sing-box"
else
checkpoint_true "Sing-box UCI config"
fi
# Check traffic
IP_EXTERNAL=$(curl -s ifconfig.me) IP_EXTERNAL=$(curl -s ifconfig.me)
IFCONFIG=$(nslookup -type=a ifconfig.me | awk '/^Address: / {print $2}') IFCONFIG=$(nslookup -type=a ifconfig.me | awk '/^Address: / {print $2}')
ip route add $IFCONFIG via 172.19.0.1 dev tun0 IP_VPN=$(curl --interface tun0 -s ifconfig.me)
IP_VPN=$(curl -s ifconfig.me)
ip route del $IFCONFIG via 172.19.0.1 dev tun0
if [ "$IP_EXTERNAL" != $IP_VPN ]; then if [ "$IP_EXTERNAL" != $IP_VPN ]; then
checkpoint_true "Sing-box. VPN IP: $IP_VPN" checkpoint_true "Sing-box. VPN IP: $IP_VPN"
else else
checkpoint_false "Sing-box. Check config: https://cli.co/Badmn3K" checkpoint_false "Sing-box. Check config: https://cli.co/Badmn3K"
fi fi
else
checkpoint_false "Sing-box package"
echo "If you don't use sing-box it's OK"
fi fi
if which tun2socks | grep -q tun2socks; then if which tun2socks | grep -q tun2socks; then
checkpoint_true "tun2socks package" checkpoint_true "tun2socks package"
# Check route table # Check route table
if ip route show table vpn | grep -q "default dev tun0 scope link"; then if ip route show table vpn | grep -q "default dev tun0"; then
checkpoint_true "Route table tun2socks" checkpoint_true "Route table tun2socks"
else else
checkpoint_false "Route table tun2socks. Try service network restart. Details: https://cli.co/n7xAbc1" checkpoint_false "Route table tun2socks. Try service network restart. Details: https://cli.co/n7xAbc1"
@@ -214,18 +217,13 @@ if which tun2socks | grep -q tun2socks; then
IP_EXTERNAL=$(curl -s ifconfig.me) IP_EXTERNAL=$(curl -s ifconfig.me)
IFCONFIG=$(nslookup -type=a ifconfig.me | awk '/^Address: / {print $2}') IFCONFIG=$(nslookup -type=a ifconfig.me | awk '/^Address: / {print $2}')
ip route add $IFCONFIG via 172.16.250.1 dev tun0 IP_VPN=$(curl --interface tun0 -s ifconfig.me)
IP_VPN=$(curl -s ifconfig.me)
ip route del $IFCONFIG via 172.16.250.1 dev tun0
if [ "$IP_EXTERNAL" != $IP_VPN ]; then if [ "$IP_EXTERNAL" != $IP_VPN ]; then
checkpoint_true "tun2socks. VPN IP: $IP_VPN" checkpoint_true "tun2socks. VPN IP: $IP_VPN"
else else
checkpoint_false "tun2socks. Check config: https://cli.co/VNZISEM" checkpoint_false "tun2socks. Check config: https://cli.co/VNZISEM"
fi fi
else
checkpoint_false "tun2socks package"
echo "If you don't use tun2socks it's OK"
fi fi
# Check sets # Check sets
@@ -250,7 +248,7 @@ if [ $((vpn_domain_ipset_string + vpn_domain_rule_string)) -eq 10 ]; then
else else
checkpoint_false "IPs in vpn_domains" checkpoint_false "IPs in vpn_domains"
echo "If you don't use vpn_domains, it's OK" echo "If you don't use vpn_domains, it's OK"
echo "But if you want use, check configs" echo "But if you want use, check configs. And run `service getdomains start`"
output_21 output_21
fi fi
else else
@@ -275,10 +273,9 @@ if [ $((vpn_ip_ipset_string + vpn_ip_rule_string)) -eq 11 ]; then
echo "But if you want use, check configs" echo "But if you want use, check configs"
output_21 output_21
fi fi
else elif uci show firewall | grep -q "vpn_ip"; then
checkpoint_false "vpn_ip set" checkpoint_false "vpn_ip set"
echo "If you don't use vpn_ip set, it's OK" echo "Check config: https://cli.co/AwUGeM6"
echo "But if you want use, check config: https://cli.co/AwUGeM6"
fi fi
# vpn_subnet set # vpn_subnet set
@@ -297,10 +294,9 @@ if [ $((vpn_subnet_ipset_string + vpn_subnet_rule_string)) -eq 11 ]; then
echo "But if you want use, check configs" echo "But if you want use, check configs"
output_21 output_21
fi fi
else elif uci show firewall | grep -q "vpn_subnet"; then
checkpoint_false "vpn_subnet set" checkpoint_false "vpn_subnet set"
echo "If you don't use vpn_subnet set, it's OK" echo "Check config: https://cli.co/AwUGeM6"
echo "But if you want use, check config: https://cli.co/AwUGeM6"
fi fi
# vpn_community set # vpn_community set
@@ -319,25 +315,9 @@ if [ $((vpn_community_ipset_string + vpn_community_rule_string)) -eq 11 ]; then
echo "But if you want use, check configs" echo "But if you want use, check configs"
output_21 output_21
fi fi
else elif uci show firewall | grep -q "vpn_community"; then
checkpoint_false "vpn_community set" checkpoint_false "vpn_community set"
echo "If you don't use vpn_community set, it's OK" echo "Check config: https://cli.co/AwUGeM6"
echo "But if you want use, check config: https://cli.co/AwUGeM6"
output_21
fi
# hirkn script
if [ -s "$HIRKN" ]; then
checkpoint_true "Script hirkn"
if crontab -l | grep -q $HIRKN; then
checkpoint_true "Script hirkn in crontab"
else
checkpoint_false "Script hirkn in crontab"
echo "Script is not enabled in crontab. Check: crontab -l"
fi
else
checkpoint_false "Script hirkn"
echo "Script don't exists in $HIRKN. If you don't use old hirkn script, it's OK"
fi fi
# getdomains script # getdomains script
@@ -374,9 +354,6 @@ if opkg list-installed | grep -q dnscrypt-proxy2; then
checkpoint_false "Dnsmasq config for DNSCrypt" checkpoint_false "Dnsmasq config for DNSCrypt"
echo "Check config: https://cli.co/rooc0uz" echo "Check config: https://cli.co/rooc0uz"
fi fi
else
checkpoint_false "Dnscrypt-proxy2 package"
echo "If you don't use Dnscrypt, it's OK"
fi fi
# Stubby # Stubby
@@ -397,16 +374,13 @@ if opkg list-installed | grep -q stubby; then
checkpoint_false "Dnsmasq config for Stubby" checkpoint_false "Dnsmasq config for Stubby"
echo "Check config: https://cli.co/HbDBT2V" echo "Check config: https://cli.co/HbDBT2V"
fi fi
else
checkpoint_false "Stubby package"
echo "If you don't use Stubby, it's OK"
fi fi
# Create dump # Create dump
if [[ "$1" == dump ]]; then if [[ "$1" == dump ]]; then
printf "\033[36;1mCreate dump without private variables\033[0m\n" printf "\033[36;1mCreate dump without private variables\033[0m\n"
date > $DUMP date > $DUMP
$HIRKN start >> $DUMP 2>&1 $HIVPN start >> $DUMP 2>&1
$GETDOMAINS start >> $DUMP 2>&1 $GETDOMAINS start >> $DUMP 2>&1
uci show firewall >> $DUMP uci show firewall >> $DUMP
uci show network | sed -r 's/(.*private_key=|.*preshared_key=|.*public_key=|.*endpoint_host=|.*wan.ipaddr=|.*wan.netmask=|.*wan.gateway=|.*wan.dns|.*.macaddr=).*/\1REMOVED/' >> $DUMP uci show network | sed -r 's/(.*private_key=|.*preshared_key=|.*public_key=|.*endpoint_host=|.*wan.ipaddr=|.*wan.netmask=|.*wan.gateway=|.*wan.dns|.*.macaddr=).*/\1REMOVED/' >> $DUMP

View File

@@ -9,16 +9,16 @@ check_repo() {
route_vpn () { route_vpn () {
if [ "$TUNNEL" == wg ]; then if [ "$TUNNEL" == wg ]; then
cat << EOF > /etc/hotplug.d/iface/30-rknroute cat << EOF > /etc/hotplug.d/iface/30-vpnroute
#!/bin/sh #!/bin/sh
ip route add table vpn default dev wg0 ip route add table vpn default dev wg0
EOF EOF
elif [ "$TUNNEL" == singbox ] || [ "$TUNNEL" == ovpn ] || [ "$TUNNEL" == tun2socks ]; then elif [ "$TUNNEL" == singbox ] || [ "$TUNNEL" == ovpn ] || [ "$TUNNEL" == tun2socks ]; then
cat << EOF > /etc/hotplug.d/iface/30-rknroute cat << EOF > /etc/hotplug.d/iface/30-vpnroute
#!/bin/sh #!/bin/sh
sleep 5 sleep 10
ip route add table vpn default dev tun0 ip route add table vpn default dev tun0
EOF EOF
fi fi
@@ -107,9 +107,9 @@ add_tunnel() {
read -r -p "Enter the public key (from [Peer]):"$'\n' WG_PUBLIC_KEY read -r -p "Enter the public key (from [Peer]):"$'\n' WG_PUBLIC_KEY
read -r -p "If use PresharedKey, Enter this (from [Peer]). If your don't use leave blank:"$'\n' WG_PRESHARED_KEY read -r -p "If use PresharedKey, Enter this (from [Peer]). If your don't use leave blank:"$'\n' WG_PRESHARED_KEY
read -r -p "Enter Enpoint host without port (Domain or IP) (from [Peer]):"$'\n' WG_ENDPOINT read -r -p "Enter Endpoint host without port (Domain or IP) (from [Peer]):"$'\n' WG_ENDPOINT
read -r -p "Enter Enpoint host port (from [Peer]) [51820]:"$'\n' WG_ENDPOINT_PORT read -r -p "Enter Endpoint host port (from [Peer]) [51820]:"$'\n' WG_ENDPOINT_PORT
WG_ENDPOINT_PORT=${WG_ENDPOINT_PORT:-51820} WG_ENDPOINT_PORT=${WG_ENDPOINT_PORT:-51820}
if [ "$WG_ENDPOINT_PORT" = '51820' ]; then if [ "$WG_ENDPOINT_PORT" = '51820' ]; then
echo $WG_ENDPOINT_PORT echo $WG_ENDPOINT_PORT
@@ -563,8 +563,8 @@ VERSION_ID=$(grep VERSION_ID /etc/os-release | awk -F '"' '{print $2}' | awk -F.
if [ "$VERSION_ID" -ne 23 ]; then if [ "$VERSION_ID" -ne 23 ]; then
printf "\033[31;1mScript only support OpenWrt 23.05\033[0m\n" printf "\033[31;1mScript only support OpenWrt 23.05\033[0m\n"
echo "For OpenWrt 21.02 and 22.03 you can:" echo "For OpenWrt 21.02 and 22.03 you can:"
echo "1) Use ansible https://github.com/itdoginfo/ansible-openwrt-hirkn" echo "1) Use ansible https://github.com/itdoginfo/domain-routing-openwrt"
echo "2) Configure manually. Old manual: https://itdog.info/tochechnyj-obhod-blokirovok-rkn-na-routere-s-openwrt-s-pomoshhyu-wireguard-i-dnscrypt/" echo "2) Configure manually. Old manual: https://itdog.info/tochechnaya-marshrutizaciya-na-routere-s-openwrt-wireguard-i-dnscrypt/"
exit 1 exit 1
fi fi

26
handlers/main.yml Normal file
View File

@@ -0,0 +1,26 @@
---
- 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

22
meta/main.yml Normal file
View File

@@ -0,0 +1,22 @@
---
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
license: GPL-3.0
min_ansible_version: 2.10.7
platforms:
- name: OpenWrt
galaxy_tags:
- openwrt
- dnsmasq
- ipset
- wireguard
- sing-box
- openvpn
- bypass
- routing
dependencies:
- role: gekmihesg.openwrt

View File

@@ -1,31 +1,5 @@
--- ---
- 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
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
tasks:
# Dnsmasq version check # Dnsmasq version check
- name: Get dnsmasq version - name: Get dnsmasq version
@@ -63,13 +37,20 @@
- sing-box - sing-box
when: tunnel == "singbox" and ansible_distribution_major_version >= "23" when: tunnel == "singbox" and ansible_distribution_major_version >= "23"
- name: install curl and nano - name: install curl
opkg: opkg:
name: "{{ item }}" name: "{{ item }}"
state: present state: present
loop: loop:
- curl - curl
- name: install nano
opkg:
name: "{{ item }}"
state: present
loop:
- nano - nano
when: nano
- name: install ipset - name: install ipset
opkg: opkg:
@@ -86,7 +67,7 @@
- name: getdomains script copy - name: getdomains script copy
template: template:
src: "{{ ansible_template_dir }}openwrt-getdomains.j2" src: "openwrt-getdomains.j2"
dest: "/etc/init.d/getdomains" dest: "/etc/init.d/getdomains"
mode: a+x mode: a+x
trim_blocks: false trim_blocks: false
@@ -121,60 +102,10 @@
# Configure route table # Configure route table
# - name: Create vpn0 interface
# uci:
# command: section
# config: network
# type: interface
# find_by:
# name: vpn0
# name: vpn0
# value:
# name: vpn0
# proto: none
# auto: 1
# device: tun0
# when: tunnel == "openvpn" or tunnel == "singbox" or tunnel == "tun2socks"
# notify:
# - Restart network
# - name: tunnel routing. tun0
# uci:
# command: section
# config: network
# type: route
# find_by:
# name: vpn_route
# name: vpn_route
# value:
# name: vpn_route
# interface: vpn0
# table: vpn
# target: 0.0.0.0/0
# when: tunnel == "openvpn" or tunnel == "singbox" or tunnel == "tun2socks"
# notify:
# - Restart network
# - name: tunnel routing. wg0
# uci:
# command: section
# config: network
# type: route
# find_by:
# name: vpn
# name: vpn_route
# value:
# interface: wg0
# table: vpn
# target: 0.0.0.0/0
# when: tunnel == "wg"
# notify:
# - Restart network
- name: Route for vpn table - name: Route for vpn table
template: template:
src: "{{ ansible_template_dir }}openwrt-30-rknroute.j2" src: "openwrt-30-vpnroute.j2"
dest: "/etc/hotplug.d/iface/30-rknroute" dest: "/etc/hotplug.d/iface/30-vpnroute"
mode: 0644 mode: 0644
- name: Check string in rt_tables - name: Check string in rt_tables
@@ -305,7 +236,7 @@
- name: template for sing-box.json - name: template for sing-box.json
template: template:
src: "{{ ansible_template_dir }}sing-box-json.j2" src: "sing-box-json.j2"
dest: "/etc/sing-box/config.json" dest: "/etc/sing-box/config.json"
mode: 0644 mode: 0644
when: tunnel == "singbox" when: tunnel == "singbox"
@@ -313,7 +244,7 @@
- name: template for config/sing-box - name: template for config/sing-box
template: template:
src: "{{ ansible_template_dir }}config-sing-box.j2" src: "config-sing-box.j2"
dest: "/etc/config/sing-box" dest: "/etc/config/sing-box"
mode: 0600 mode: 0600
when: tunnel == "singbox" when: tunnel == "singbox"
@@ -483,7 +414,6 @@
value: value:
match: dst_net match: dst_net
storage: hash storage: hash
failed_when: ansible_distribution_major_version < "22" and list_domains and not dnsmasqfull_version.stdout
when: ansible_distribution_major_version < "22" and list_domains 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. - name: add nfset for domains (>=22). If failed, repeat playbook. If failed is repeated check dnsmasq-full.
@@ -495,7 +425,6 @@
name: vpn_domains name: vpn_domains
value: value:
match: dst_net match: dst_net
failed_when: ansible_distribution_major_version >= "22" and list_domains and (not dnsmasqfull_version.stdout or dnsmasqfull_version.stdout < "2.87")
when: ansible_distribution_major_version >= "22" and list_domains when: ansible_distribution_major_version >= "22" and list_domains
- name: add mark rule vpn_subnet - name: add mark rule vpn_subnet
@@ -564,7 +493,30 @@
set_mark: "0x1" set_mark: "0x1"
target: MARK target: MARK
family: ipv4 family: ipv4
when: (ansible_distribution_major_version < "22" and list_domains and dnsmasqfull_version.stdout) or (ansible_distribution_major_version >= "22" and list_domains and dnsmasqfull_version.stdout >= "2.87") 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 # Remove unused rules and ipset
- name: Remove ipset for ip - name: Remove ipset for ip
@@ -694,7 +646,7 @@
- Restart dnsmasq - Restart dnsmasq
when: dns_encrypt == "stubby" when: dns_encrypt == "stubby"
# Commit and handlers # Commit
- name: uci commit firewall - name: uci commit firewall
uci: uci:
@@ -709,30 +661,3 @@
config: network config: network
notify: notify:
- Restart network - 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,6 +3,6 @@
{% if tunnel == "wg" %} {% if tunnel == "wg" %}
ip route add table vpn default dev wg0 ip route add table vpn default dev wg0
{% elif (tunnel == "openvpn") or (tunnel == "singbox") or (tunnel == "tun2socks") %} {% elif (tunnel == "openvpn") or (tunnel == "singbox") or (tunnel == "tun2socks") %}
sleep 5 sleep 10
ip route add table vpn default dev tun0 ip route add table vpn default dev tun0
{% endif %} {% endif %}

2
tests/inventory Normal file
View File

@@ -0,0 +1,2 @@
[openwrt]
192.168.56.23

6
tests/test.yml Normal file
View File

@@ -0,0 +1,6 @@
---
- hosts: openwrt
remote_user: root
roles:
- domain_routing_openwrt