Post

tuto-se-connecter-a-son-openvpn-depuis-son-lan-et-wan-malgre-routeur-pas-compatible-hairpinning

tuto-se-connecter-a-son-openvpn-depuis-son-lan-et-wan-malgre-routeur-pas-compatible-hairpinning

URL: https://linuxfr.org/wiki/tuto-se-connecter-a-son-openvpn-depuis-son-lan-et-wan-malgre-routeur-pas-compatible-hairpinning Title: [Tuto] Se connecter à son OpenVPN depuis son LAN et WAN malgré routeur pas compatible hairpinning Authors: TutoMaker Date: 2017-09-26T19:51:18+02:00 License: CC by-sa Tags: réseau, tutoriel, ubuntu, debian, hairpinning, hack et openvpn Score: 0

Introduction

Pour une raison suspicieuse, les box des Fournisseurs d’Accès Internet (FAI) sont régulièrement incompatible avec le hairpinning. Pour outrepasser ce problème, nous allons simplement dupliquer le fichier de conf (.ovpn) afin qu’un soit compatible avec le LAN et un avec internet (WAN). Ensuite nous lancerons un script au démarrage de la machine qui décidera quel fichier de conf (.ovpn) il faut lancer en fonction de si votre serveur est sur le même réseau ou non. Ce script est compatible avec les tunnels SSH (au choix en local ou en wan ou même les deux ou aucun).

Mise en place sur le client

Note : pour ce tuto je pars du principe que votre OpenVPN est déjà installé et le port ouvert sur le routeur du réseau du serveur (par défaut 1194).

  1. Copiez le fichier de configuration de votre client OpenVPN, nous allons ajouter _LAN dans le titre du nouveau fichier
1
sudo cp /etc/openvpn/monUser.ovpn cp /etc/openvpn/monUser_LAN.ovpn 
  1. Éditez la copie qui nous servira pour le LAN
1
sudo nano /etc/openvpn/monUser_LAN.ovpn
  • A la ligne commençant par “remote”, rajoutez _LAN dans le nom de domaine (ou remplacez le nom de domaine par l’IP LAN statique de votre serveur OpenVPN).
1
remote www.server_LAN.com 1194
  1. Ensuite éditez votre fichier /etc/hosts afin d’y indiquer la correspondance entre notre nouveau nom de domaine dédié au LAN et l’adresse IP du serveur OpenVPN.
1
sudo nano /etc/hosts
  • Ajoutez une ligne du style
1
192.168.1.42       www.server_LAN.com
  1. Créez le script de lancement /opt/scripts/vpnSwitcher.bash (CTRL+X pour sauver & quitter)
1
sudo nano /opt/scripts/vpnSwitcher.bash
  1. Puis collez le script suivant et adaptez le à votre config

Note : source du script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/bin/bash
# -- vpnSwitcher --
#  -> WTFPL - infos script : https://www.0rion.netlib.re/forum4/viewtopic.php?f=9&t=646&p=1460#p1460
# -> code by voxdemonix <-
# -> V1.11 (2017/09/11) <-
# uncomment next line for debug
#set -x

if [ ! "$SUDO_USER" ]; then
echo "!!! i need root !!!"
exit 0
fi

    #SCRIPTS OPTIONS
LANG="fr" # notification service ; accept : fr, usa (default)
notificationType="notify" # accept : echo; notify, nothing. Notify not work with root user.

    # NETWORK OPTIONS
INTERFACE="tun"
hostnameVpnLAN="192.168.1.69" # (VPN1 hostname) l'adresse IP locale (LAN) de votre serveur OpenVPN
MacVpnLocal="69:69:69:69:69:69" #l'adresse mac de votre serveur OpenVPN (tapez ifconfig dans un terminal sur votre server)

    # VPN OPTIONS
fichierOvpnLAN="/etc/openvpn/myUser_LAN.ovpn" # (VPN1) le PATH de votre fichier de conf .ovpn en LAN
fichierOvpnNotLAN="/etc/openvpn/myUser.ovpn" # (VPN2) le PATH de votre fichier de conf .ovpn pour les connnexions WAN/SSH
openVpn1Param=" " # add options (ex: --route-nopull) for openvpn connexion to server 1 (lan)
openVpn2Param=" " # add options (ex: --route-nopull) for openvpn connexion to server 2 (ssh/tor/wan)

    # SSH OPTIONS
hosnameVpnNotLAN="blablablablablabla.onion" # (VPN2 hostname)
UserLocalForSshTunneling="daenerys" # l'user a utiliser sur votre ordinateur pour le montage du tunnel (celui qui a exporté sa clés)
UserRemoteForSshTunneling="proxy-ssh" # l'user a utiliser côté server ( /!\ n'utilisez jamais root !)
portEntree="1194" # le port sur le pc local, par défaut 1194 (tcp)
portSortie="1194" # le port sur le serveur, par défaut 1194 (tcp)
sshLanEnable=0  # 0 for disable ; 1 for enable : enable or disable the ssh tunneling in LAN
sshNotLanEnable=0 # 0 for disable ; 1 for enable : enable or disable the ssh tunneling in Wan | Tor



            # NOTIFICATION SYSTEM
function vpnNotification {
        # $1 = message ID (watch switch/case);
        # $2 = hostnameVPN
    message=""
    #hostnameVPN=$(cat "$2" | grep "remote " | sed 's/remote //g' | sed 's/ [[:digit:]]\+//g')
    hostnameVPN=$2

    case $LANG in
        fr )
                case $1 in
                    VpnDisabled )
                            message="Connexion VPN fermée ($hostnameVPN)"
                        ;;
                    VpnConnecting )
                            message="Connexion VPN en cours ($hostnameVPN)"
                        ;;
                    VpnEnabled )
                            message="VPN Connecté ! ($hostnameVPN)"
                        ;;
                    SshStop )
                            message="Tunnel SSH STOP ($hostnameVPN)"
                        ;;
                    SshStart )
                            message="Tunnel SSH START ($hostnameVPN)"
                        ;;
                    * )
                            message="message inconnu"
                        ;;
                esac
            ;;
        usa | *)
                case $1 in
                    VpnDisabled )
                            message="VPN Connection Close ($hostnameVPN)"
                        ;;
                    VpnConnecting )
                            message="VPN Connection in progress ($hostnameVPN)"
                        ;;
                    VpnEnabled )
                            message="VPN Connected ! ($hostnameVPN)"
                        ;;
                    SshStop )
                            message="SSH Tunneling STOP ($hostnameVPN)"
                        ;;
                    SshStart )
                            message="SSH Tunneling START ($hostnameVPN)"
                        ;;
                    * )
                            message="unknow message"
                        ;;
                esac
            ;;
    esac


    case $notificationType in
        echo)
                echo "$message"
            ;;
        notify)
                notify-send "$message"
            ;;
        nothing | *)
            ;;
    esac
}

function quitOpenVPN {
        # $1 = ovpn ( $fichierOvpnLAN, $fichierOvpnNotLAN)
        # $2 = hostnameVPN ( $hostnameVpnLAN, $hosnameVpnNotLAN)
        ovpn=$1
        hostVPN=$2
            #stop VPN
        if [ $(pkill -c -f $ovpn) -gt 0 ]; then
		hostnameVPN=$(cat $ovpn | grep "remote " | sed 's/remote //g' | sed 's/ [[:digit:]]\+//g')
		vpnNotification "VpnDisabled" $hostnameVPN
        fi
            #stop ssh
#        if ps -aux | grep "[a]utossh" | grep "$hostVPN"  | grep -v "grep" >> /dev/null 2>&1; then
#            for pid in `ps -ef | grep "[a]utossh" | grep "$hostVPN"  | grep -v "grep" | awk '{print $2}'` ; do kill $pid ; done
		if [ $(pkill -c -f "autossh.*$UserRemoteForSshTunneling@$hostVPN") -gt 0 ]; then
            vpnNotification "SshStop" $hostVPN
        fi
        sleep 1
}

function startOpenVPN {
        # $1 = hostname VPN ($hostnameVpnLAN, $hosnameVpnNotLAN)
        # $2 = ovpn ($fichierOvpnLAN, $fichierOvpnNotLAN)
        # $3 = ssh enable (1) or not (0) ($sshLanEnable, $sshNotLanEnable)
        # $4 = OpenVpn Param ($openVpn1Param, $openVpn2Param)

        hostVPN=$1
        ovpn=$2
        sshChoice=$3
        openvpnParam=$4

                # SSH TUNNELING
            if [ $sshChoice == 1 ]; then
                    # kill oprevious ssh tunneling
                for pid in `ps -ef | grep "[a]utossh" | grep "$hostVPN" | awk '{print $2}'` ; do kill $pid ; done
                    # creat new ssh tunneling
                su $UserLocalForSshTunneling -c "autossh -M 0 -q -N -o 'ServerAliveInterval 60' -o 'ServerAliveCountMax 3' -L $portEntree:127.0.0.1:$portSortie $UserRemoteForSshTunneling@$hostVPN -f"
		        if ps -aux | grep "[a]utossh" | grep "$hostVPN"  | grep -v "grep" >> /dev/null 2>&1; then
		            vpnNotification "SshStart" $hostVPN
		        fi
            fi

                # START OpenVPN
            openvpn --daemon $openvpnParam --config $ovpn

                # NOTIFICATIONS
            hostnameVPN=$(cat $ovpn | grep "remote " | sed 's/remote //g' | sed 's/ [[:digit:]]\+//g')
            vpnNotification "VpnConnecting" $hostnameVPN

                # boucle qui permet de verifier si le VPN se connecte bien
        stop=0
        while [ $stop -lt 10 ]
        do       # temps d'attente entre chaque tentative
            if ifconfig | grep -iq $INTERFACE; then
                    vpnNotification "VpnEnabled" $hostnameVPN
                    stop=10
                    exit
            fi
                sleep 5
               stop=$((stop+1))
        done

}



        # boucle qui permet d'attendre que le réseau soit connecté
stop="0"
while [ $stop -lt 1 ]
do
	sleep 3       # temps d'attente entre chaque tentative

	_IP=$(hostname -I) || true
	if [ "$_IP" ]; then
	        stop=1
	fi
done

if ps -aux | grep "[o]penvpn" >> /dev/null 2>&1; then
    #Connexion VPN active

            # vpn server 1
        quitOpenVPN $fichierOvpnLAN $hostnameVpnLAN
            # vpn server 2
        quitOpenVPN $fichierOvpnNotLAN $hosnameVpnNotLAN


else

        ping $hostnameVpnLAN -c 2 >> /dev/null 2>&1
        macRecover=$(arp -n | grep -i -o $MacVpnLocal)

        if [ "$macRecover" == "$MacVpnLocal" ]; then
        #        echo "local/LAN/First VPN"
            startOpenVPN $hostnameVpnLAN $fichierOvpnLAN $sshLanEnable $openVpn1Param

        else
        #        echo "tor/wan/second VPN"
            startOpenVPN $hosnameVpnNotLAN $fichierOvpnNotLAN $sshNotLanEnable $openVpn2Param

        fi

fi
  • Éditez les valeurs suivantes

    • hostnameVpnLAN=”192.168.1.69” => (VPN1 hostname) l’adresse IP locale (LAN) de votre serveur OpenVPN
    • MacVpnLocal=”69:69:69:69:69:69” => l’adresse mac de votre serveur OpenVPN (tapez ifconfig dans un terminal sur votre server)
    • fichierOvpnLAN=”/etc/openvpn/myUser_LAN.ovpn” => (VPN1) le PATH de votre fichier de conf .ovpn en LAN
    • fichierOvpnNotLAN=”/etc/openvpn/myUser.ovpn” => (VPN2) le PATH de votre fichier de conf .ovpn pour les connnexions WAN/SSH
  1. Sauvez et quittez avec CTRL+X, puis rendez votre fichier exécutable
1
sudo chmod +x /opt/scripts/vpnSwitcher.bash
  1. Lancez ensuite le script afin de le tester
1
sudo /opt/scripts/vpnSwitcher.bash

S’il fonctionne correctement, ajoutez le au démarrage du client soit via /etc/rc.local soit via cron

1
sudo crontab -e
  1. Ajoutez enfin la ligne suivante (CTRL+X pour sauver et quitter)
1
@reboot		/opt/scripts/vpnSwitcher.bash

Farm Link

Cet article est sous licence CC BY 4.0 par l'auteur.