Configure automatic password reception for VPN on Mikrotik

Background


In connection with the introduction in our country of blocking some resources (we will not point fingers), I needed to implement access to them through a VPN. By the way, I do not use these resources so often, but I use them. And it would seem that easier. Today there are a whole bunch of different services providing VPN access.

However, to pay for the service a few tens of dollars and use it several times a month, I thought it was impractical. Then my choice fell on free VPNs. One of these is the vpnbook service .. For my requirements, there is plenty of it, but the problem is that the password for accessing the VPN via PPTP periodically changes. And with each change, go to the site to copy it and configure the connection on the router - to be honest laziness. And they say that "laziness is the engine of progress." In my case, it is. We need to do something ...

I thought, why not parsing the password from the page and automatically update the connection settings on my Mikrotik. Why only a password? Well, on vpnbook the addresses of the servers are quite constant and I use the same one and the login is always the same - vpnbook. So let's get started.

Part about PHP - a simple parser


To begin with, I decided to write a simple parser of the page in PHP. Honestly, I don’t particularly program in my work, so all the code that I will provide here can certainly be done better and I hope in the comments I will be pointed out to errors, mistakes and shortcomings.

When parsing, I used the PHP Simple HTML DOM Parser library. It can be downloaded from the link . And for starters, we certainly need to connect it:

include "simple_html_dom.php";

Next, in order to get the contents of the page vpnbook.com/freevpn we will use cURL. I took an example of how to use it from the php.net website and wrapped it in a function:

function url_get_html($url){
    // инициализируем cURL
    $ch = curl_init();
    // устанавливаем url с которого будем получать данные
    curl_setopt($ch, CURLOPT_URL, $url);
    // устанавливаем опцию чтобы содержимое вернулось нам в string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // выполняем запрос
    $output = curl_exec($ch);
    // закрываем cURL
    curl_close($ch);
    // возвращаем содержимое
    return $output;
}

Further, using the capabilities of the PHP Simple HTML DOM Parser library, we need to extract the password from the contents of the page. After looking at the source code of the page, you can see that the password is in the last element of the list in the strong tag.

A piece of page source code
...

PPTP (point to point tunneling) is widely used since it is supported across all Microsoft Windows, Linux, Apple, Mobile and PS3 platforms. It is however easier to block and might not work if your ISP or government blocks the protocol. In that case you need to use OpenVPN, which is impossible to detect or block.

  • euro217.vpnbook.com
  • euro214.vpnbook.com
  • us1.vpnbook.com...
  • us2.vpnbook.com...
  • ca1.vpnbook.com...
  • de233.vpnbook.com...
  • Username: vpnbook
  • Password: qedE3ha
More servers coming. Please Donate.
...


Why not get all the strong tags from the first list on the page and not get the password from the last? We do:

// URL с которого будем парсить пароль
$url = "http://www.vpnbook.com/freevpn";
// получаем DOM
$html = str_get_html(url_get_html($url));
// находим необходимые элементы к первом списке с классом "disc"
$items = $html->find(".disc", 0)->find("strong");
// пароль находится в последнем
$pswd = end($items);
// выводим пароль
echo $pswd->innertext;

So the parser is ready. It remains to put it on the server.

Code completely without comment

include "simple_html_dom.php";
function url_get_html($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
$url = "http://www.vpnbook.com/freevpn";
$html = str_get_html(url_get_html($url));
$items = $html->find(".disc", 0)->find("strong");
$pswd = end($items);
echo $pswd->innertext;


Part about Mikrotik - a script for creating a VPN connection


The parser is ready and imagine that it is available at vpn.pswd.tk . Now we need to write a script on Mikrotik (I have hap lite) that will access our parser, receive a password from it and recreate the VPN connection. Rummaging through the Mikrotik documentation, I found the functionality I needed, namely using / tool fetch you can make a request by URL and put the contents into a text file, and then read its contents into a variable. Here is the full script code:

/tool fetch url="http://vpn.pswd.tk/" mode=http dst-path="vpn_pswd.txt";
:delay 2s
:local password [/file get vpn_pswd.txt contents]
/file remove vpn_pswd.txt;
/interface pptp-client remove [/interface pptp-client find name=pptp-out1]
/interface pptp-client add name=pptp-out1 user=vpnbook password=$password connect-to=us1.vpnbook.com disabled=no

Let’s take a look at what is what. The first line we make a request to our parser and write the response in the form of a password in the file vpn_pswd.txt. Further, as you might guess, we have a delay of 2 seconds. For what? The fact is that the router takes some time to complete the request and create the file, and if you do not delay it, the next command may simply not consider the value from the file as a variable (since it is not there at that time). Further, after writing the value to the variable, we delete the created file - we no longer need it. Then we delete the created VPN connection and create a new one.

It remains only to add to the scheduler the launch of this script after any (of your choice) time interval. This is done in the System / Scheduler section. If we assume our script is called “through_vpn_list”, then with this command we will create a task to run the script every 6 hours:

/system scheduler add name=schedule1 interval=6h on-event="/system  script  run  through_vpn_list"

Summary


We got the opportunity to automatically create a VPN connection using the password from a free service. How to use this connection is your decision. For example, you can configure policy-based routing so that a VPN connection is used only for a specific list of sites and resources. So for example, I have implemented it. I am enclosing a link to the documentation on which this can be done.

Of course, this solution is probably not the best. And here you can improve a lot. For example, what if the layout changes? The parser will no longer work. Therefore, you need to think about a more universal approach to obtaining a password. But the goal was achieved and such a bunch works great.

PSPlease write comments on what is wrong that can be improved. As it is written: “Without a confidential conversation, plans will be upset, and with many advisers there will be success.”

Also popular now: