Pptp client linux route

RussianProxy.ru

Для работы Ubuntu Server в качестве PPTP-клиента необходимо установить пакет pptp-linux:

sudo apt-get install pptp-linux

Основные настройки пакета, применяемые ко всем PPTP соедниненям по умолчанию хранятся в /etc/ppp/options.pptp, в большинстве случаев менять их нет необходимости, однако вы можете добавить какие-то свои опции, общие для всех соединений.

Для настройки подключения создадим в /etc/ppp/peers файл настроек с его именем:

sudo touch /etc/ppp/peers/test-vpn

Откроем его и внесем следующее содержимое:

pty "pptp pptp-l2tp-vpn-russia-1.atomintersoft.com --nolaunchpppd" #тип и адрес сервера , как пример pptp-l2tp-vpn-russia-1.atomintersoft.com
name vpnuser #логин
remotename TEST #имя соединения
require-mppe-128 #включаем поддержку MPPE
defaultroute #создавать маршрут по умолчанию
replacedefaultroute #принудительно изменять маршрут по умолчанию
unit 12 #номер ppp интерфейса
persist #переподключаться при обрыве
maxfail 10 #количество попыток переподключения
holdoff 15 #интервал между подключениями
file /etc/ppp/options.pptp
ipparam $TUNNEL

Номер ppp интрефейса создает для подключения всегда один и тот же сетевой интерфейс, в нашем случае это будет ppp12.

Отдельно стоит остановиться на наборе опций для автоматического переподключения. Мы настоятельно советуем ограничить количество попыток (0 — неограничено) разумным числом и не ставить слишком маленький промежуток времени. Это позволит ограничить нагрузку на VPN-сервер в случае проблем с подключением (например нет денег на балансе или изменились учетные данные).

Теперь укажем авторизационные данные для нашего пользователя, для этого в файл /etc/ppp/chap-secrets добавим следующую строку:

которая предусматривает использование указанных учетных данных, где vpnpassword -пароль соединения, для удаленного соеднинения TEST (это имя мы указали в опции remotename).
Теперь самое время проверить наше соединение. Первый раз лучше запустить его в интерактивном режиме, тогда все сообщения об ошибках и ходе подключения вы будете видеть прямо в консоли:

В дальнейшем управлять соединением можно при помощи команд pon и poff (подключить и отключить соответственно).

Чтобы автоматически поднимать соединение при запуске системы в файл /etc/network/interfaces добавим секцию:

auto tunnel
iface tunnel inet ppp
provider test-vpn

Для доступа в корпоративную сеть может понадобиться добавление статических маршрутов, это тоже можно делать автоматически, для этого в конец созданой секции добавим строку:

up route add -net 192.168.0.0 netmask 255.255.255.0 gw 192.168.0.222

Мы привели реальный маршрут используемый в нашем случае, вы должны указать здесь свои данные, если они не известны — уточните их у системного администратора.

Перезапустим сеть и убедимся что все работает правильно:

sudo /etc/init.d/networking restart

Для получения списка маршрутов воспользуйтесь командой route, также можно пропинговать какой-нибудь внутренний хост.

При подключении к сети интернет через PPTP бывают ситуации, когда, несмотря на указанные опции, нулевой маршрут через туннель не устанавливается. В этом случае можно в конец соответсвующей секции в /etc/network/interfaces добавить:

up route del default
up route add default dev ppp12

где ppp12 — имя вашего ppp интерфейса.

Читайте также:  Terminating processes in linux

© 1996-2023 RussianProxy.ru — Outline ShadowSocks / PPTP / L2TP / OpenVPN TCP / OpenVPN UDP VPN сервис, русский выделенный IP, безлимитные тарифы.

Источник

PPTP Client

pptpclient is a program implementing the Microsoft PPTP protocol. As such, it can be used to connect to a Microsoft VPN network (or any PPTP-based VPN) provided by a school or workplace.

Warning: The PPTP protocol is inherently insecure. See http://poptop.sourceforge.net/dox/protocol-security.phtml for details.

Installation

Configure

To configure pptpclient you will need to collect the following information from your network administrator:

  • The IP address or hostname of the VPN server.
  • The username you will use to connect.
  • The password you will use to connect.
  • The authentication (Windows) domain name. This is not necessary for certain networks.

You must also decide what to name the tunnel.

Configure using pptpsetup

You can configure and delete tunnels by running the pptpsetup tool as root. For example:

pptpsetup --create my_tunnel --server vpn.example.com --username alice --password foo --encrypt pptpsetup --delete my_tunnel

You can #Connect after a tunnel has been configured.

Configure by hand

You can also edit all necessary configuration files by hand, rather than relying on pptpsetup.

Edit The options File

The /etc/ppp/options file sets security options for your VPN client. If you have trouble connecting to your network, you may need to relax the options. At a minimum, this file should contain the options lock , noauth , nobsdcomp and nodeflate .

# Lock the port lock # We don't need the tunnel server to authenticate itself noauth # Turn off compression protocols we know won't be used nobsdcomp nodeflate # We won't do PAP, EAP, CHAP, or MSCHAP, but we will accept MSCHAP-V2 # (you may need to remove these refusals if the server is not using MPPE) refuse-pap refuse-eap refuse-chap refuse-mschap

Edit The chap-secrets File

The /etc/ppp/chap-secrets file contains credentials for authenticating a tunnel. Make sure no one except root can read this file, as it contains sensitive information.

chmod 0600 /etc/ppp/chap-secrets

Edit the file. It has the following format:

Replace each bracketed term with an appropriate value. Omit \\ if your connection does not require a domain.

Note: Place your password in double quotation marks ( » ) if it contains special characters such as $ .

Name Your Tunnel

The /etc/ppp/peers/ file contains tunnel-specific configuration options. is the name you wish to use for your VPN connection. The file should look like this:

pty «pptp —nolaunchpppd» name \\ remotename PPTP require-mppe-128 file /etc/ppp/options ipparam

Again, omit \\ if your connection does not require a domain. is the remote address of the VPN server, is the domain your user belongs to, is the name you will use to connect to the server, and is the name of the connection.

Note: If you do not need MPPE support, you should remove the require-mppe-128 option from this file and from /etc/ppp/options

Connect

To make sure that everything is configured properly, as root execute:

# pon debug dump logfd 2 nodetach

If everything has been configured correctly, the pon command should not terminate. Once you are satisfied that it has connected successfully, you can terminate the command.

Читайте также:  Check ldap on linux

Note: As an additional verification you can run ip addr show and ensure that a new device, ppp0 , is available.

To connect to your VPN normally, simply execute:

Where is the name of the tunnel you established earlier. Note that this command should be run as root.

Routing

Once you have connected to your VPN, you should be able to interact with anything available on the VPN server. To access anything on the remote network, you need to add a new route to your routing table.

Note: Depending on your configuration, you may need to re-add the routing information every time you connect to your VPN.

For more information on how to add routes, you can read this article which has many more examples: PPTP Routing Howto

Split Tunneling

Packets with a destination of your VPN’s network should be routed through the VPN interface (usually ppp0 ). To do this, you create the route:

# ip route add 192.168.10.0/24 dev ppp0

This will route all the traffic with a destination of 192.168.10.* through your VPN’s interface, ( ppp0 ).

Route All Traffic

It may be desirable to route all traffic through your VPN connection. You can do this by running:

# ip route add default dev ppp0

Note: Routing all traffic through the VPN may result in slower over all connection speed because your traffic will be routed through the remote VPN before being routed normally.

Route All Traffic by /etc/ppp/ip-up.d

#!/bin/bash # This script is called with the following arguments: # Arg Name # $1 Interface name # $2 The tty # $3 The link speed # $4 Local IP number # $5 Peer IP number # $6 Optional ``ipparam'' value foo ip route add default via $4

Make sure the script is executable.

Split Tunneling based on port by /etc/ppp/ip-up.d

/etc/ppp/ip-up.d/01-routebyport.sh
#!/bin/bash # This script is called with the following arguments: # Arg Name # $1 Interface name # $2 The tty # $3 The link speed # $4 Local IP number # $5 Peer IP number # $6 Optional ``ipparam'' value foo echo 0 > /proc/sys/net/ipv4/conf/$1/rp_filter echo 1 > /proc/sys/net/ipv4/ip_forward echo 1 > /proc/sys/net/ipv4/ip_dynaddr ip route flush table vpn ip route add default via $5 dev $1 table vpn # forward only IRC ports over VPN iptables -t mangle -A OUTPUT -p tcp -m multiport --dports 6667,6697 -j MARK --set-mark 0x1 iptables -t nat -A POSTROUTING -o $1 -j MASQUERADE ip rule add fwmark 0x1 pri 100 lookup vpn ip rule add from $4 pri 200 table vpn ip route flush cache

Make sure the script is executable and that the vpn table is added to /etc/iproute2/rt_tables

Disconnect

Execute the following to disconnect from a VPN:

is the name of your tunnel.

Читайте также:  Teams linux share screen

Making A VPN Daemon and Connecting On Boot

This article or section is out of date.

You can create a simple daemon for your VPN connection by creating an appropriate /etc/rc.d/* script:

Note: As always, is the name of your tunnel. is the command you use to add the appropriate route to the routing table.

Note: The stop functionality of this script will not work if the updetach and persist arguments are passed to /usr/bin/pon when pon is started. The reason for this is that the /usr/bin/poff script contains a bug when determining the PID of the specified pppd process if arguments were passed to pon .

To resolve this issue, you can patch your /usr/bin/poff file by making the following changes on line 93:

-PID=`ps axw | grep "[ /]pppd call $1 *\$" | awk ''` +PID=`ps axw | grep "[ /]pppd call $1" | awk ''`
#!/bin/bash . /etc/rc.conf . /etc/rc.d/functions DAEMON=-vpn ARGS= [ -r /etc/conf.d/$DAEMON ] && . /etc/conf.d/$DAEMON case "$1" in start) stat_busy "Starting $DAEMON" pon updetach persist &>/dev/null && &>/dev/null if [ $? = 0 ]; then add_daemon $DAEMON stat_done else stat_fail exit 1 fi ;; stop) stat_busy "Stopping $DAEMON" poff &>/dev/null if [ $? = 0 ]; then rm_daemon $DAEMON stat_done else stat_fail exit 1 fi ;; restart) $0 stop sleep 1 $0 start ;; *) echo "usage: $0 " esac

Note: We call pon in the script with two additional arguments: updetach and persist . The argument updetach makes pon block until the connection has been established. The other argument, persist , makes the network automatically reconnect in the event of a failure. To connect at boot add @-vpn to the end of your DAEMONS array in /etc/rc.conf .

Troubleshooting

If client connections keep timing out with «LCP: timeout sending Config-Requests», make sure that GRE is allowed through the client firewall. For iptables, the necessary command is:

iptables -A INPUT -p 47 -j ACCEPT

Alternatively, if you only want to allow PPTP traffic that corresponds to a connection request coming from your local machine, you can use the conntrack PPTP helper:

iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT iptables -t raw -A OUTPUT -p tcp --dport 1723 -j CT --helper pptp

The second line should autoload the nf_conntrack_pptp and nf_conntrack_proto_gre kernel modules, which are needed for this.

If you get “EAP: unknown authentication type 26; Naking”, open /etc/ppp/options.pptp and commented out the lines refuse-chap and refuse-mschap and add the options file entry to the tunnel file like this:

# written by pptpsetup pty "pptp vpn.foo.com --nolaunchpppd" lock noauth nobsdcomp nodeflate name USERNAME remotename vpn file /etc/ppp/options.pptp ipparam vpn require-mppe-128

Remarks

You can find more information about configuring pptpclient at their website: pptpclient website. The contents of this article were adapted from their Ubuntu How-To which also provides some hints on how to do things such as connecting on boot. These examples should be easy to adapt into daemons or other scripts to help automate your configuration.

Источник

Оцените статью
Adblock
detector