Joris Vanhecke

Toggle OPNsense VPN through API

This windows batch script adds or removes the IP of the local machine to the VPN_HOSTS alias in OPNsense.

This works with my OPNsense/WireGuard set-up notes.

To use, edit the first 3 variables and make sure curl and jq is in PATH.

@echo off


set key= _KEY_
set secret= _SECRET_
set opnsense= _IP_OF_OPNSENSE_

rem -----------------------------------------
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=14 delims= " %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
    set client_ip=%%f
    goto :bar
)

:bar

curl -s ipinfo.io | jq -r > .public_ip_data
jq -r .ip .public_ip_data>.public_ip
set /p public_ip=<.public_ip
jq -r .region .public_ip_data>.public_ip_region
set /p public_ip_region=<.public_ip_region


echo ------------------------------------------------------------------
echo CURRENT internal IP Address is: %client_ip%
echo CURRENT external IP Address is: %public_ip% (%public_ip_region%)
echo ------------------------------------------------------------------

curl -s -k -u "%key%":"%secret%" https://%opnsense%/api/firewall/alias_util/list/VPN_HOSTS | jq "any(.rows[].ip == \"%client_ip%\"; .)" > is_active
set /p is_active=<is_active
del is_active

IF "%is_active%"=="true" (
    ECHO VPN is currently ACTIVE for this machine. Script will now DISABLE VPN..
    pause
    curl -s -XPOST -d "{\"address\":\"%client_ip%\"}" -H "Content-Type: application/json" -k -u "%key%":"%secret%" https://%opnsense%/api/firewall/alias_util/delete/VPN_HOSTS > .opn_response
)

IF "%is_active%"=="false" (
    ECHO VPN is NOT ACTIVE for this machine. Script will now ENABLE VPN..
    pause
    curl -s -XPOST -d "{\"address\":\"%client_ip%\"}" -H "Content-Type: application/json" -k -u "%key%":"%secret%" https://%opnsense%/api/firewall/alias_util/add/VPN_HOSTS > .opn_response
)

:END
echo ------------------------------------------------------------------

curl -s ipinfo.io | jq -r > .public_ip_data
jq -r .ip .public_ip_data>.public_ip
set /p public_ip=<.public_ip
jq -r .region .public_ip_data>.public_ip_region
set /p public_ip_region=<.public_ip_region

echo CURRENT external IP Address is now: %public_ip% (%public_ip_region%)
echo ------------------------------------------------------------------
pause

#opnsense #vpn #wireguard