Skip to content
Open
71 changes: 68 additions & 3 deletions vpn-notifications/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,72 @@
The set of scripts in this directory will poll the USG's VPN connection list every minute and report any VPN connectivity changes.

# Installation
- Modify the settings at the top of both `config-vpn-notifications.sh` and `notify-on-vpn-state-change.sh`
- Create a file parameter.env with the following content
```
# This script goes in /config/scripts/post-config.d

# Variables you'll need to change config-vpn-notifications.sh
HostName='myroutershostname.somedomain.local' # Hostname of your USG
RouterUser='admin' # Default username for your USG
MailServer='smtp.gmail.com' # SMTP Server
MailPort='587' # SMTP Server Port
EmailAddress='example.user@gmail.com' # E-mail address to send as
AuthUser='example.user' # SMTP Username
Password='SomeP@ssword12345' # SMTP Password


# Variables you'll need to change for notify-on-vpn-state-change.sh
IPSegment='10.0' # The IP address segment your VPN is located on (i.e. '10.0.' or '192.168.1.')
DestinationEmail='user@example.com' # Where to send e-mails to
ClientsName='StringToDifferenciatNetworks'
```

- To start the scripts two options:

## Option1: Prefered which remain active when new provision occurs: In CloudKey
- Push the scripts to your USG via `scp`, replacing the username and ip address with your own:
```
scp parameter.env admin@192.168.0.1:/config/scripts/post-config.d/
scp config-vpn-notifications.sh admin@192.168.0.1:/config/scripts/post-config.d/
scp notify-on-vpn-state-change.sh admin@192.168.0.1:/config/scripts/post-config.d/
```

Follow to find where the gateway.json is in your CloudKey https://help.ubnt.com/hc/en-us/articles/215458888-UniFi-How-to-further-customize-USG-configuration-with-config-gateway-json
with the following content added to your gateway.json
```{
"system": {
"task-scheduler": {
"task": {
"check-vpn-connections": {
"executable": {
"path": "/config/scripts/post-config.d/notify-on-vpn-state-change.sh"
},
"interval": "1m"
}
}
}
}
}
```
Log into USG and render scripts executable.

## Option 2: By "hand"
- Push the scripts to your USG via `scp`, replacing the username and ip address with your own:
```
scp parameter.env admin@192.168.0.1:/config/scripts/post-config.d/
scp config-vpn-notifications.sh admin@192.168.0.1:/config/scripts/post-config.d/
scp notify-on-vpn-state-change.sh admin@192.168.0.1:/config/scripts/post-config.d/
scp config-vpn-notifications.sh admin@192.168.0.1:/config/scripts/post-config.d/
```
- To start the scripts, you'll need to log in via SSH, change the scripts to executable, and execute `config-vpn-notifications.sh` for the first time via `sudo`. After that, the script will be set up as a scheduled task, and will persist after reboots. On upgrades, both scripts will be executed once the upgrade is complete, re-establishing the scheduled task:
Then you'll need to log in via SSH, change the scripts to executable, and execute `config-vpn-notifications.sh` for the first time via `sudo`. After that, the script will be set up as a scheduled task, and will persist after reboots. On upgrades, both scripts will be executed once the upgrade is complete, re-establishing the scheduled task:
```
cd /config/scripts/post-config.d
chmod a+x config-vpn-notifications.sh
chmod a+x notify-on-vpn-state-change.sh
sudo ./config-vpn-notifications.sh
```

# Removal
# Removal For option 2
- Connect to the USG via SSH, and run the following commands:
```
configure
Expand Down Expand Up @@ -48,12 +99,17 @@ Subject: VPN activity detected
VPN connection activity was detected on your network:

Active remote access VPN sessions:
---- Current active connection ----

User Time Proto Iface Remote IP TX pkt/byte RX pkt/byte
---------- --------- ----- ----- --------------- ------ ------ ------ ------
some.user 00h00m12s L2TP l2tp0 10.0.0.1 56 11.6K 70 8.3K

Total sessions: 1

---- Previous status 1 min ago ----

No active remote access VPN sessions
```

When the last user has disconnected:
Expand All @@ -65,5 +121,14 @@ Subject: VPN activity detected

VPN connection activity was detected on your network:

---- Current active connection ----

No active remote access VPN sessions

---- Previous status 1 min ago ----

User Time Proto Iface Remote IP TX pkt/byte RX pkt/byte
---------- --------- ----- ----- --------------- ------ ------ ------ ------
some.user 01h00m12s L2TP l2tp0 10.0.0.1 156 11.6G 90 8.3M

```
53 changes: 2 additions & 51 deletions vpn-notifications/config-vpn-notifications.sh
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
#!/bin/vbash
# This script goes in /config/scripts/post-config.d

# Variables you'll need to change
HostName='myroutershostname.somedomain.local' # Hostname of your USG
RouterUser='admin' # Default username for your USG
MailServer='smtp.gmail.com' # SMTP Server
MailPort='587' # SMTP Server Port
EmailAddress='example.user@gmail.com' # E-mail address to send as
AuthUser='example.user' # SMTP Username
Password='SomeP@ssword12345' # SMTP Password

# Variables you'll need to change are in parameter.env
source /config/scripts/post-config.d/parameter.env

#################################################################################
### Don't change anything beyond this point unless you know what you're doing ###
Expand All @@ -19,48 +12,6 @@ Password='SomeP@ssword12345' # SMTP Password
source /opt/vyatta/etc/functions/script-template
readonly logFile="/var/log/config-smtp.log"

# Write aliases config
cat > /etc/ssmtp/revaliases <<EOF
# sSMTP aliases
#
# Format: local_account:outgoing_address:mailhub
#
# Example: root:your_login@your.domain:mailhub.your.domain[:port]
# where [:port] is an optional port number that defaults to 25.
root:$EmailAddress:$MailServer:$MailPort
$RouterUser:$EmailAddress:$MailServer:$MailPort
www-data:$EmailAddress:$MailServer:$MailPort
EOF

# Write SMTP config
cat > /etc/ssmtp/ssmtp.conf <<EOF
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=$EmailAddress

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=$MailServer:$MailPort

AuthUser=$AuthUser
AuthPass=$Password
UseSTARTTLS=YES

# Where will the mail seem to come from?
rewriteDomain=

# The full hostname
hostname=$HostName

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
EOF

# Add a scheduled task to send the e-mails every minute
configure
set system task-scheduler task check-vpn-connections executable path "/config/scripts/post-config.d/notify-on-vpn-state-change.sh"
Expand Down
86 changes: 77 additions & 9 deletions vpn-notifications/notify-on-vpn-state-change.sh
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
#!/bin/vbash
# This script goes in /config/scripts/post-config.d

# Variables you'll need to change
IPSegment='10.0.' # The IP address segment your VPN is located on (i.e. '10.0.' or '192.168.1.')
DestinationEmail='user@example.com' # Where to send e-mails to

# Variables you'll need to change are in parameter.env
source /config/scripts/post-config.d/parameter.env

#################################################################################
### Don't change anything beyond this point unless you know what you're doing ###
Expand All @@ -14,35 +12,105 @@ DestinationEmail='user@example.com' # Where to send e-mails to
source /opt/vyatta/etc/functions/script-template
run=/opt/vyatta/bin/vyatta-op-cmd-wrapper


# Verify and prepare SSMTP configuration if necessary
rev_search=$(grep ":$MailServer:$MailPort" "/etc/ssmtp/revaliases")
if [ -z "$rev_search" ];
then
# Write aliases config as config does not include what is expected
cat > /etc/ssmtp/revaliases <<EOF
# sSMTP aliases
#
# Format: local_account:outgoing_address:mailhub
#
# Example: root:your_login@your.domain:mailhub.your.domain[:port]
# where [:port] is an optional port number that defaults to 25.
root:$EmailAddress:$MailServer:$MailPort
$RouterUser:$EmailAddress:$MailServer:$MailPort
www-data:$EmailAddress:$MailServer:$MailPort
EOF

fi

ssmtp_search:=$(grep "mailhub=$MailServer:$MailPort" "/etc/ssmtp/ssmtp.conf")
if [ -z "$ssmtp_search" ];
then
# Write SMTP config as ssmtp not configured
cat > /etc/ssmtp/ssmtp.conf <<EOF
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=$EmailAddress

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=$MailServer:$MailPort

AuthUser=$AuthUser
AuthPass=$Password
UseSTARTTLS=YES

# Where will the mail seem to come from?
rewriteDomain=

# The full hostname
hostname=$HostName

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
EOF

fi

# Init the temp files
touch /tmp/temp.vpnconnections
touch /tmp/temp.vpnconnections2

touch /tmp/temp.vpnfulllist
touch /tmp/temp.vpnfulllist2

# Grab the full list of VPN connections
$run show vpn remote-access > /tmp/temp.vpnfulllist

# Parse out just the user and ip address
cat /tmp/temp.vpnfulllist|grep $IPSegment|awk -F' ' '{printf "%s %s\n", $1, $5}' > /tmp/temp.vpnconnections
grep "$IPSegment" /tmp/temp.vpnfulllist | awk -F' ' '{printf "%s %s\n", $1, $5}' > /tmp/temp.vpnconnections

# Check if they differ from the last time we checked
if ! cmp -s /tmp/temp.vpnconnections /tmp/temp.vpnconnections2
then
echo "VPN Activity detected! Sending e-mail..."

# Someone connected to/disconnected from the VPN! Send an e-mail notification
connInfo=$(</tmp/temp.vpnfulllist)
connInfo="$(</tmp/temp.vpnfulllist)"
connInfo2="$(</tmp/temp.vpnfulllist2)"

echo "Subject: VPN activity detected
echo "Subject: VPN activity detected on $ClientsName's network!

VPN connection activity was detected on your network:
---- Current active connection ----

$connInfo

---- Previous status 1 min ago ----

$connInfo2

" > /tmp/temp.vpnemail

/usr/sbin/ssmtp $DestinationEmail < /tmp/temp.vpnemail
/usr/sbin/ssmtp "$DestinationEmail" < /tmp/temp.vpnemail

echo "Done!"

# Back up this run so we can compare later
cp /tmp/temp.vpnconnections /tmp/temp.vpnconnections2
fi
fi
# Back up this run to use it later for stat
cp /tmp/temp.vpnfulllist /tmp/temp.vpnfulllist2

# Call bad login
source /config/scripts/post-config.d/search-login-trial.sh

14 changes: 14 additions & 0 deletions vpn-notifications/parameter.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Variables you'll need to change config-vpn-notifications.sh
HostName='myroutershostname.somedomain.local' # Hostname of your USG
RouterUser='admin' # Default username for your USG
MailServer='smtp.gmail.com' # SMTP Server
MailPort='587' # SMTP Server Port
EmailAddress='example.user@gmail.com' # E-mail address to send as
AuthUser='example.user' # SMTP Username
Password='SomeP@ssword12345' # SMTP Password


# Variables you'll need to change for notify-on-vpn-state-change.sh
IPSegment='10.0' # The IP address segment your VPN is located on (i.e. '10.0.' or '192.168.1.')
DestinationEmail='user@example.com' # Where to send e-mails to
ClientsName='StringToDifferenciatNetworks'
57 changes: 57 additions & 0 deletions vpn-notifications/search-login-trial.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/bin/vbash
# This script goes in /config/scripts/post-config.d

# Variables you'll need to change are in parameter.env
source /config/scripts/post-config.d/parameter.env

#################################################################################
### Don't change anything beyond this point unless you know what you're doing ###
#################################################################################

# Include some of the vyatta commands we'll need
source /opt/vyatta/etc/functions/script-template
run=/opt/vyatta/bin/vyatta-op-cmd-wrapper

# Init the temp files
touch /tmp/temp.vpnpeer
touch /tmp/temp.vpnpeer2

# Grab the list of vpn login trial without success of VPN connections
# Limit to 1000 line to ensure not flood /tmp filesystem
# Remove /var/log/messages?? in order to avoid change when log rotate occurs :) and notif again
# Filter only today trial to avoid notification several day later. Prefer notif sooner.
# Note: There is a short time window of a trials of login 1 min before 00:00 where it will not be
# reported. The risk is very small as not lot of user/log cannot be tested during this time frame.
# FIXME: A notification will occurs when log will disapear. This is better than not being notified
today_filter="$(date | cut -d " " -f2-4)"
grep Peer /var/log/messages* | head -n 1000 | cut -d':' -f2- | grep "$($today_filter)"> /tmp/temp.vpnpeer

# Check if they differ from the last time we checked
if ! cmp -s /tmp/temp.vpnpeer /tmp/temp.vpnpeer2
then
#Filter empty file (no more connection found) and so avoid false notif (mitigate above FIXME).
if [ -s /tmp/temp.vpnpeer ];
then

echo "WARNING: VPN Activity detected! Sending e-mail..."

# Someone try to connect without success
connInfo="$(</tmp/temp.vpnpeer)"

echo "Subject: WARNING VPN activity login without success detected on $ClientsName's network!

VPN connection trial without sucess was detected on your network:

$connInfo

" > /tmp/temp.vpnpeeremail

/usr/sbin/ssmtp "$DestinationEmail" < /tmp/temp.vpnpeeremail

echo "Done!"

fi
# Back up this run so we can compare later
cp /tmp/temp.vpnpeer /tmp/temp.vpnpeer2
fi