Страница 1 из 1

Парсер wireguard конфига в формат MikroTik

Добавлено: 07 июн 2024, 18:03
ya
обязательно должен быть предварительно созданный адрес-лист в микротике allow-local-all с созданными локальными адресами

wg-0.2.1-reliz.cpp

Код: Выделить всё

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>

struct WireGuardConfig {
    std::string publicKey;
    std::string privateKey;
    std::string presharedKey;
    std::string address;
    std::string dns;
    std::string mtu;
    std::string endpoint;
    std::string endport;
};


int main(int argc, char* argv[]) {
     if (argc < 2 ) exit (1);
    std::map<std::string, std::string> config;
    
    std::ifstream configFile(argv[1]);
    if (!configFile.is_open()) {
        std::cerr << "Error opening config file" << std::endl;
        return 1;
    }
    std::vector<WireGuardConfig> configs;
    WireGuardConfig currentConfig;
    std::string line;
    while (std::getline(configFile, line)) {
        
        if (line.empty() || line[0] == '#') {
            continue; // skip empty lines and lines starting with #
        }
        
        std::string key, value;
        size_t pos = line.find('=');
        if (pos != std::string::npos) 
        {
            key = line.substr(0, pos);
            value = line.substr(pos + 1);
            // Remove leading and trailing whitespaces
            key.erase(0, key.find_first_not_of(" \t\r"));
            key.erase(key.find_last_not_of(" \t\r") + 1);
            value.erase(0, value.find_first_not_of(" \t\r"));
            value.erase(value.find_last_not_of(" \t\r") + 1);
            
            config[key] = value;
        
   
            
            if (key == "PublicKey") {
            currentConfig.publicKey = value;
        } else if (key == "PrivateKey") {
            currentConfig.privateKey = value;
        } else if (key == "Address") {
            currentConfig.address = value;
        } else if (key == "DNS") {
            currentConfig.dns = value;
        } else if (key == "MTU") {
            currentConfig.mtu= value;
        } else if (key == "PresharedKey") {
            currentConfig.presharedKey = value;
        } else if (key == "Endpoint") {
            currentConfig.endpoint = value.substr(0,value.find(":"));
            currentConfig.endport = value.substr(value.find(":")+1);            
        } else if (key == "}") {
            configs.push_back(currentConfig);
            currentConfig = WireGuardConfig();
        }
            
            
        }
        
        
        
        
    }
    
    
    configFile.close();
    
    std::string wireguard_port;
    std::string wireguard_local_address;
    std::cout << "Enter port WireGuard: ";
    std::getline(std::cin, wireguard_port);
    std::cout << "Enter local address WireGuard: ";
    std::getline(std::cin, wireguard_local_address);
    std::cout << std::endl;
    std::cout << std::endl;
    
    
    //Создание интерфейса
    std::cout << "# Interface wireguard" << std::endl;
    std::cout << "/interface wireguard add";
    std::cout <<  " listen-port=" << wireguard_port;
    if(std::size(currentConfig.mtu) ) 
        std::cout << " mtu=" << currentConfig.mtu;
    std::cout << " name=wg-" << currentConfig.endpoint;
    std::cout << " private-key=\""<<  currentConfig.privateKey << "\"";
    std::cout << std::endl;
    
    //Создание пира
    std::cout << "# WireGuard peer" << std::endl;
    std::cout << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    std::cout << " endpoint-address=" << currentConfig.endpoint;
    std::cout << " endpoint-port=" << currentConfig.endport;
    std::cout << " interface=wg-" << currentConfig.endpoint;
    std::cout << " persistent-keepalive=25s";
    std::cout << " public-key=\"" << currentConfig.publicKey << "\"";
    if(std::size(currentConfig.presharedKey) )
        std::cout <<" preshared-key\""<< currentConfig.presharedKey << "\"";
    std::cout << " comment=wg-" << currentConfig.endpoint;
    std::cout << std::endl;
    
    //Создание локального адреса интерфейса
    std::cout << "# Local ip address WireGuard" << std::endl;
    std::cout << "/ip address add";
    std::cout << " address=" << currentConfig.address;
    std::cout << " interface=wg-" << currentConfig.endpoint;
    std::cout << std::endl;
    
    //Создание NAT правила
     std::cout << "# Firewall nat WireGuard" << std::endl;
     std::cout << "/ip firewall nat add action=masquerade chain=srcnat";
     std::cout << " out-interface=wg-" << currentConfig.endpoint;
     std::cout << " comment=wg-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание таблицы маршрута
     std::cout << "# Routing table WireGuard" << std::endl;
     std::cout << "/routing table add disabled=no fib";
     std::cout <<  " name=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание маршрута
     std::cout << "# Ip route WireGuard" << std::endl;
     std::cout << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     std::cout << " gateway=wg-"<< currentConfig.endpoint;
     std::cout << " pref-src=\"\"";
     std::cout << " routing-table=vpn-"<< currentConfig.endpoint; 
     std::cout << " suppress-hw-offload=no";
     std::cout << " comment=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание мангала
     std::cout << "# Firewall mangle WireGuard" << std::endl;
     std::cout << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     std::cout << " src-address=" << wireguard_local_address;
     std::cout << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     std::cout << " new-routing-mark=vpn-" << currentConfig.endpoint; 
     std::cout << " passthrough=yes"; 
     std::cout << " comment=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     std::cout << "# Enter to exit" << std::endl;
     std::getline(std::cin, wireguard_local_address);
     std::cout << std::endl;
        
  
    return 0;
}
Откомпилировать:

Код: Выделить всё

g++ -std=c++17 -o wg.a wg-0.2.1-reliz.cpp
Откомпилировать для винды:

Код: Выделить всё

i686-w64-mingw32-g++ -o wg.exe wg-0.2.1-reliz.cpp
Запуск под Linux:

Код: Выделить всё

./wg.a wireguard.conf
Запуск под Win:

Код: Выделить всё

wg.exe wireguard.conf

Re: Парсер wireguard конфига в формат MikroTik

Добавлено: 08 июн 2024, 21:50
ya
wg-0.2.2-reliz.cpp

Код: Выделить всё

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>

struct WireGuardConfig {
    std::string publicKey;
    std::string privateKey;
    std::string presharedKey;
    std::string address;
    std::string dns;
    std::string mtu;
    std::string endpoint;
    std::string endport;
};


int main(int argc, char* argv[]) {
     if (argc < 2 ) exit (1);
    std::map<std::string, std::string> config;
    
    std::ifstream configFile(argv[1]);
    if (!configFile.is_open()) {
        std::cerr << "Error opening config file" << std::endl;
        return 1;
    }
    std::vector<WireGuardConfig> configs;
    WireGuardConfig currentConfig;
    std::string line;
    while (std::getline(configFile, line)) {
        
        if (line.empty() || line[0] == '#') {
            continue; // skip empty lines and lines starting with #
        }
        
        std::string key, value;
        size_t pos = line.find('=');
        if (pos != std::string::npos) 
        {
            key = line.substr(0, pos);
            value = line.substr(pos + 1);
            // Remove leading and trailing whitespaces
            key.erase(0, key.find_first_not_of(" \t\r"));
            key.erase(key.find_last_not_of(" \t\r") + 1);
            value.erase(0, value.find_first_not_of(" \t\r"));
            value.erase(value.find_last_not_of(" \t\r") + 1);
            
            config[key] = value;
            
            if (key == "PublicKey") {
				currentConfig.publicKey = value;
			} else if (key == "PrivateKey") {
				currentConfig.privateKey = value;
			} else if (key == "Address") {
				currentConfig.address = value;
			} else if (key == "DNS") {
				currentConfig.dns = value;
			} else if (key == "MTU") {
				currentConfig.mtu= value;
			} else if (key == "PresharedKey") {
				currentConfig.presharedKey = value;
			} else if (key == "Endpoint") {
				currentConfig.endpoint = value.substr(0,value.find(":"));
				currentConfig.endport = value.substr(value.find(":")+1);            
			} else if (key == "}") {
				configs.push_back(currentConfig);
				currentConfig = WireGuardConfig();
			}
        }
    }
    
    
    configFile.close();
    
    std::string wireguard_port;
    std::string wireguard_local_address;
    std::cout << "Enter port WireGuard: ";
    std::getline(std::cin, wireguard_port);
    std::cout << "Enter local address WireGuard: ";
    std::getline(std::cin, wireguard_local_address);
    std::cout << std::endl;
    std::cout << std::endl;
    
    
    //Создание интерфейса
    std::cout << "# Interface wireguard" << std::endl;
    std::cout << "/interface wireguard add";
    std::cout <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        std::cout << " mtu=" << currentConfig.mtu;
    std::cout << " name=wg-" << currentConfig.endpoint;
    std::cout << " private-key=\""<<  currentConfig.privateKey << "\"";
    std::cout << std::endl;
    
    //Создание пира
    std::cout << "# WireGuard peer" << std::endl;
    std::cout << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    std::cout << " endpoint-address=" << currentConfig.endpoint;
    std::cout << " endpoint-port=" << currentConfig.endport;
    std::cout << " interface=wg-" << currentConfig.endpoint;
    std::cout << " persistent-keepalive=25s";
    std::cout << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        std::cout <<" preshared-key\""<< currentConfig.presharedKey << "\"";
    std::cout << " comment=wg-" << currentConfig.endpoint;
    std::cout << std::endl;
    
    //Создание локального адреса интерфейса
    std::cout << "# Local ip address WireGuard" << std::endl;
    std::cout << "/ip address add";
    std::cout << " address=" << currentConfig.address;
    std::cout << " interface=wg-" << currentConfig.endpoint;
    std::cout << std::endl;
    
    //Создание NAT правила
     std::cout << "# Firewall nat WireGuard" << std::endl;
     std::cout << "/ip firewall nat add action=masquerade chain=srcnat";
     std::cout << " out-interface=wg-" << currentConfig.endpoint;
     std::cout << " comment=wg-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание таблицы маршрута
     std::cout << "# Routing table WireGuard" << std::endl;
     std::cout << "/routing table add disabled=no fib";
     std::cout <<  " name=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание маршрута
     std::cout << "# Ip route WireGuard" << std::endl;
     std::cout << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     std::cout << " gateway=wg-"<< currentConfig.endpoint;
     std::cout << " pref-src=\"\"";
     std::cout << " routing-table=vpn-"<< currentConfig.endpoint; 
     std::cout << " suppress-hw-offload=no";
     std::cout << " comment=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание мангала
     std::cout << "# Firewall mangle WireGuard" << std::endl;
     std::cout << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     std::cout << " src-address=" << wireguard_local_address;
     std::cout << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     std::cout << " new-routing-mark=vpn-" << currentConfig.endpoint; 
     std::cout << " passthrough=yes"; 
     std::cout << " comment=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     std::cout << std::endl;
     std::cout << std::endl;
     
     std::cout << "# Enter to exit" << std::endl;
     std::getline(std::cin, wireguard_local_address);
     std::cout << std::endl;
        
  
    return 0;
}
откомпилировать:
g++ -std=c++11 -o wg.a wg-0.2.2-reliz.cpp
i686-w64-mingw32-g++ -o wg.exe wg-0.2.2-reliz.cpp

Re: Парсер wireguard конфига в формат MikroTik

Добавлено: 09 июн 2024, 00:26
ya
wg-0.3.1.cpp

Код: Выделить всё


#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <ctime>

struct WireGuardConfig {
    std::string publicKey;
    std::string privateKey;
    std::string presharedKey;
    std::string address;
    std::string dns;
    std::string mtu;
    std::string endpoint;
    std::string endport;
};


int main(int argc, char* argv[]) {
     if (argc < 2 ) exit (1);
    std::map<std::string, std::string> config;
    
    std::ifstream configFile(argv[1]);
    if (!configFile.is_open()) {
        std::cerr << "Error opening config file" << std::endl;
        return 1;
    }
    std::vector<WireGuardConfig> configs;
    WireGuardConfig currentConfig;
    std::string line;
    while (std::getline(configFile, line)) {
        
        if (line.empty() || line[0] == '#') {
            continue; // skip empty lines and lines starting with #
        }
        
        std::string key, value;
        size_t pos = line.find('=');
        if (pos != std::string::npos) 
        {
            key = line.substr(0, pos);
            value = line.substr(pos + 1);
            // Remove leading and trailing whitespaces
            key.erase(0, key.find_first_not_of(" \t\r"));
            key.erase(key.find_last_not_of(" \t\r") + 1);
            value.erase(0, value.find_first_not_of(" \t\r"));
            value.erase(value.find_last_not_of(" \t\r") + 1);
            
            config[key] = value;
            
            if (key == "PublicKey") {
				currentConfig.publicKey = value;
			} else if (key == "PrivateKey") {
				currentConfig.privateKey = value;
			} else if (key == "Address") {
				currentConfig.address = value;
			} else if (key == "DNS") {
				currentConfig.dns = value;
			} else if (key == "MTU") {
				currentConfig.mtu= value;
			} else if (key == "PresharedKey") {
				currentConfig.presharedKey = value;
			} else if (key == "Endpoint") {
				currentConfig.endpoint = value.substr(0,value.find(":"));
				currentConfig.endport = value.substr(value.find(":")+1);            
			} else if (key == "}") {
				configs.push_back(currentConfig);
				currentConfig = WireGuardConfig();
			}
        }
    }
    
    
    configFile.close();
    
    
    std::string wireguard_port;
    std::string wireguard_local_address;
    std::cout << "Enter port WireGuard: ";
    std::getline(std::cin, wireguard_port);
    std::cout << "Enter local address WireGuard: ";
    std::getline(std::cin, wireguard_local_address);
    std::cout << std::endl;
    std::cout << std::endl;    
    
    /****************************************************************************/
    
    // Получаем текущую дату и время
    time_t now = time(0);
    struct tm *timeinfo;
    char buffer[80];
    timeinfo = localtime(&now);
    strftime(buffer, 80, "%Y-%m-%d_%H-%M-%S", timeinfo);

    // Создаем имя файла
    std::stringstream filename;
    filename << "mikrotik_" << buffer << ".txt";

    // Создаем файл
    std::ofstream file(filename.str());
    if (file.is_open()) {


      //  file << "This file was created at: " << buffer << std::endl;
        
        
    
    
    //Создание интерфейса
    file << "# Interface wireguard" << std::endl;
    file << "/interface wireguard add";
    file <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        file << " mtu=" << currentConfig.mtu;
    file << " name=wg-" << currentConfig.endpoint;
    file << " private-key=\""<<  currentConfig.privateKey << "\"";
    file << std::endl;
    
    //Создание пира
    file << "# WireGuard peer" << std::endl;
    file << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    file << " endpoint-address=" << currentConfig.endpoint;
    file << " endpoint-port=" << currentConfig.endport;
    file << " interface=wg-" << currentConfig.endpoint;
    file << " persistent-keepalive=25s";
    file << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        file <<" preshared-key=\""<< currentConfig.presharedKey << "\"";
    file << " comment=wg-" << currentConfig.endpoint;
    file << std::endl;
    
    //Создание локального адреса интерфейса
    file << "# Local ip address WireGuard" << std::endl;
    file << "/ip address add";
    file << " address=" << currentConfig.address;
    file << " interface=wg-" << currentConfig.endpoint;
    file << std::endl;
    
    //Создание NAT правила
     file << "# Firewall nat WireGuard" << std::endl;
     file << "/ip firewall nat add action=masquerade chain=srcnat";
     file << " out-interface=wg-" << currentConfig.endpoint;
     file << " comment=wg-" << currentConfig.endpoint;
     file << std::endl;
     
     //Создание таблицы маршрута
     file << "# Routing table WireGuard" << std::endl;
     file << "/routing table add disabled=no fib";
     file <<  " name=vpn-" << currentConfig.endpoint;
     file << std::endl;
     
     //Создание маршрута
     file << "# Ip route WireGuard" << std::endl;
     file << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     file << " gateway=wg-"<< currentConfig.endpoint;
     file << " pref-src=\"\"";
     file << " routing-table=vpn-"<< currentConfig.endpoint; 
     file << " suppress-hw-offload=no";
     file << " comment=vpn-" << currentConfig.endpoint;
     file << std::endl;
     
     //Создание мангала
     file << "# Firewall mangle WireGuard" << std::endl;
     file << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     file << " src-address=" << wireguard_local_address;
     file << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     file << " new-routing-mark=vpn-" << currentConfig.endpoint; 
     file << " passthrough=yes"; 
     file << " comment=vpn-" << currentConfig.endpoint;
     file << std::endl;
     
     file << std::endl;
     file << std::endl;        
        





        file.close();
//        std::cout << "File created successfully: " << filename.str() << std::endl;
    } else {
        std::cerr << "Error creating file" << std::endl;
    }    
    
    
    /****************************************************************************/
    
    

    
    
    //Создание интерфейса
    std::cout << "# Interface wireguard" << std::endl;
    std::cout << "/interface wireguard add";
    std::cout <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        std::cout << " mtu=" << currentConfig.mtu;
    std::cout << " name=wg-" << currentConfig.endpoint;
    std::cout << " private-key=\""<<  currentConfig.privateKey << "\"";
    std::cout << std::endl;
    
    //Создание пира
    std::cout << "# WireGuard peer" << std::endl;
    std::cout << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    std::cout << " endpoint-address=" << currentConfig.endpoint;
    std::cout << " endpoint-port=" << currentConfig.endport;
    std::cout << " interface=wg-" << currentConfig.endpoint;
    std::cout << " persistent-keepalive=25s";
    std::cout << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        std::cout <<" preshared-key=\""<< currentConfig.presharedKey << "\"";
    std::cout << " comment=wg-" << currentConfig.endpoint;
    std::cout << std::endl;
    
    //Создание локального адреса интерфейса
    std::cout << "# Local ip address WireGuard" << std::endl;
    std::cout << "/ip address add";
    std::cout << " address=" << currentConfig.address;
    std::cout << " interface=wg-" << currentConfig.endpoint;
    std::cout << std::endl;
    
    //Создание NAT правила
     std::cout << "# Firewall nat WireGuard" << std::endl;
     std::cout << "/ip firewall nat add action=masquerade chain=srcnat";
     std::cout << " out-interface=wg-" << currentConfig.endpoint;
     std::cout << " comment=wg-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание таблицы маршрута
     std::cout << "# Routing table WireGuard" << std::endl;
     std::cout << "/routing table add disabled=no fib";
     std::cout <<  " name=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание маршрута
     std::cout << "# Ip route WireGuard" << std::endl;
     std::cout << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     std::cout << " gateway=wg-"<< currentConfig.endpoint;
     std::cout << " pref-src=\"\"";
     std::cout << " routing-table=vpn-"<< currentConfig.endpoint; 
     std::cout << " suppress-hw-offload=no";
     std::cout << " comment=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     //Создание мангала
     std::cout << "# Firewall mangle WireGuard" << std::endl;
     std::cout << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     std::cout << " src-address=" << wireguard_local_address;
     std::cout << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     std::cout << " new-routing-mark=vpn-" << currentConfig.endpoint; 
     std::cout << " passthrough=yes"; 
     std::cout << " comment=vpn-" << currentConfig.endpoint;
     std::cout << std::endl;
     
     std::cout << std::endl;
     std::cout << std::endl;
     
//     std::cout << "# Enter to exit" << std::endl;
//     std::getline(std::cin, wireguard_local_address);
//     std::cout << std::endl;
        
  
    return 0;
}



Re: Парсер wireguard конфига в формат MikroTik

Добавлено: 09 июн 2024, 01:25
ya
wg-0.3.2.cpp

Код: Выделить всё


#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <ctime>

struct WireGuardConfig {
    std::string publicKey;
    std::string privateKey;
    std::string presharedKey;
    std::string address;
    std::string dns;
    std::string mtu;
    std::string endpoint;
    std::string endport;
};


int main(int argc, char* argv[]) {
     if (argc < 2 ) exit (1);
    std::map<std::string, std::string> config;
    
    std::ifstream configFile(argv[1]);
    if (!configFile.is_open()) {
        std::cerr << "Error opening config file" << std::endl;
        return 1;
    }
    std::vector<WireGuardConfig> configs;
    WireGuardConfig currentConfig;
    std::string line;
    while (std::getline(configFile, line)) {
        
        if (line.empty() || line[0] == '#') {
            continue; // skip empty lines and lines starting with #
        }
        
        std::string key, value;
        size_t pos = line.find('=');
        if (pos != std::string::npos) 
        {
            key = line.substr(0, pos);
            value = line.substr(pos + 1);
            // Remove leading and trailing whitespaces
            key.erase(0, key.find_first_not_of(" \t\r"));
            key.erase(key.find_last_not_of(" \t\r") + 1);
            value.erase(0, value.find_first_not_of(" \t\r"));
            value.erase(value.find_last_not_of(" \t\r") + 1);
            
            config[key] = value;
            
            if (key == "PublicKey") {
				currentConfig.publicKey = value;
			} else if (key == "PrivateKey") {
				currentConfig.privateKey = value;
			} else if (key == "Address") {
				currentConfig.address = value;
			} else if (key == "DNS") {
				currentConfig.dns = value;
			} else if (key == "MTU") {
				currentConfig.mtu= value;
			} else if (key == "PresharedKey") {
				currentConfig.presharedKey = value;
			} else if (key == "Endpoint") {
				currentConfig.endpoint = value.substr(0,value.find(":"));
				currentConfig.endport = value.substr(value.find(":")+1);            
			} else if (key == "}") {
				configs.push_back(currentConfig);
				currentConfig = WireGuardConfig();
			}
        }
    }
    
    
    configFile.close();
    
    
    if((currentConfig.privateKey.size() == 0 ) || (currentConfig.publicKey.size() == 0 )) exit(0);
    
    
    std::string wireguard_port;
    std::string wireguard_local_address;
    std::cout << "Enter port WireGuard: ";
    std::getline(std::cin, wireguard_port);
    std::cout << "Enter local address WireGuard: ";
    std::getline(std::cin, wireguard_local_address);
    std::cout << std::endl;
    std::cout << std::endl;    
    
    /****************************************************************************/
    
    // Получаем текущую дату и время
    time_t now = time(0);
    struct tm *timeinfo;
    char buffer[80];
    timeinfo = localtime(&now);
    strftime(buffer, 80, "%Y-%m-%d_%H-%M-%S", timeinfo);

    // Создаем имя файла
    std::stringstream filename;
    filename << "mikrotik_" << buffer << ".txt";

    // Создаем файл
    std::ofstream file(filename.str());
    if (file.is_open()) {


      //  file << "This file was created at: " << buffer << std::endl;
        
        
    
    
    //Создание интерфейса
    file << "# Interface wireguard" << std::endl;
    file << "/interface wireguard add";
    file <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        file << " mtu=" << currentConfig.mtu;
    file << " name=wg-" << currentConfig.endpoint << "-" << buffer;
    file << " private-key=\""<<  currentConfig.privateKey << "\"";
    file << std::endl;
    
    //Создание пира
    file << "# WireGuard peer" << std::endl;
    file << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    file << " endpoint-address=" << currentConfig.endpoint;
    file << " endpoint-port=" << currentConfig.endport;
    file << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    file << " persistent-keepalive=25s";
    file << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        file <<" preshared-key=\""<< currentConfig.presharedKey << "\"";
    file << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
    file << std::endl;
    
    //Создание локального адреса интерфейса
    file << "# Local ip address WireGuard" << std::endl;
    file << "/ip address add";
    file << " address=" << currentConfig.address;
    file << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    file << std::endl;
    
    //Создание NAT правила
     file << "# Firewall nat WireGuard" << std::endl;
     file << "/ip firewall nat add action=masquerade chain=srcnat";
     file << " out-interface=wg-" << currentConfig.endpoint << "-" << buffer;
     file << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     //Создание таблицы маршрута
     file << "# Routing table WireGuard" << std::endl;
     file << "/routing table add disabled=no fib";
     file <<  " name=vpn-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     //Создание маршрута
     file << "# Ip route WireGuard" << std::endl;
     file << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     file << " gateway=wg-"<< currentConfig.endpoint << "-" << buffer;
     file << " pref-src=\"\"";
     file << " routing-table=vpn-"<< currentConfig.endpoint << "-" << buffer; 
     file << " suppress-hw-offload=no";
     file << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     //Создание мангала
     file << "# Firewall mangle WireGuard" << std::endl;
     file << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     file << " src-address=" << wireguard_local_address;
     file << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     file << " new-routing-mark=vpn-" << currentConfig.endpoint << "-" << buffer; 
     file << " passthrough=yes"; 
     file << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     file << std::endl;
     file << std::endl;        
        





        file.close();
//        std::cout << "File created successfully: " << filename.str() << std::endl;
    } else {
        std::cerr << "Error creating file" << std::endl;
    }    
    
    
    /****************************************************************************/
    
    

    
    
    //Создание интерфейса
    std::cout << "# Interface wireguard" << std::endl;
    std::cout << "/interface wireguard add";
    std::cout <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        std::cout << " mtu=" << currentConfig.mtu;
    std::cout << " name=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << " private-key=\""<<  currentConfig.privateKey << "\"";
    std::cout << std::endl;
    
    //Создание пира
    std::cout << "# WireGuard peer" << std::endl;
    std::cout << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    std::cout << " endpoint-address=" << currentConfig.endpoint;
    std::cout << " endpoint-port=" << currentConfig.endport;
    std::cout << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << " persistent-keepalive=25s";
    std::cout << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        std::cout <<" preshared-key=\""<< currentConfig.presharedKey << "\"";
    std::cout << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << std::endl;
    
    //Создание локального адреса интерфейса
    std::cout << "# Local ip address WireGuard" << std::endl;
    std::cout << "/ip address add";
    std::cout << " address=" << currentConfig.address;
    std::cout << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << std::endl;
    
    //Создание NAT правила
     std::cout << "# Firewall nat WireGuard" << std::endl;
     std::cout << "/ip firewall nat add action=masquerade chain=srcnat";
     std::cout << " out-interface=wg-" << currentConfig.endpoint << "-" << buffer;
     std::cout << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     //Создание таблицы маршрута
     std::cout << "# Routing table WireGuard" << std::endl;
     std::cout << "/routing table add disabled=no fib";
     std::cout <<  " name=vpn-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     //Создание маршрута
     std::cout << "# Ip route WireGuard" << std::endl;
     std::cout << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     std::cout << " gateway=wg-"<< currentConfig.endpoint << "-" << buffer;
     std::cout << " pref-src=\"\"";
     std::cout << " routing-table=vpn-"<< currentConfig.endpoint << "-" << buffer; 
     std::cout << " suppress-hw-offload=no";
     std::cout << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     //Создание мангала
     std::cout << "# Firewall mangle WireGuard" << std::endl;
     std::cout << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     std::cout << " src-address=" << wireguard_local_address;
     std::cout << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     std::cout << " new-routing-mark=vpn-" << currentConfig.endpoint << "-" << buffer; 
     std::cout << " passthrough=yes"; 
     std::cout << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     std::cout << std::endl;
     std::cout << std::endl;
     
//     std::cout << "# Enter to exit" << std::endl;
//     std::getline(std::cin, wireguard_local_address);
//     std::cout << std::endl;
        
  
    return 0;
}


Компиляция для win
g++ -std=c++11 -o wg-0.3.2.exe wg-0.3.2.cpp

Re: Парсер wireguard конфига в формат MikroTik

Добавлено: 09 июн 2024, 19:48
ya
Данная программа в качестве входного параметра использует локальный адрес конфига ваергарда (где локально лежит этот конфиг), либо можно просто перетащить мышью конфиг на саму программу. Затем она запросит свободный порт локалхоста, на котором должен подняться ваергард в микроте, а так же запросит айпишник в локальной сети, на который нужно направить трафик с него. Если эти параметры введены не верно, их можно потом поправить в получившимся текстовом файле после работы программы

Самое главное: не должно быть пересечения порта и адреса (уже имеющихся в микроте), в качестве вводимых параметров в самой программе.
По-умолчанию порт назначен 51818, и ип-адрес по-умолчанию 192.168.0.23 Если эти параметры устраивают, то при их запросе программой нажать Enter

Команды для микрота после отработавшей программы появятся в файле mikrotik-дата-время.txt в том каталоге, где находится конфиг ваергарда (в качестве входного параметра). Их надо будет скопировать и вставить в коммандную строку микрота

Проверить свободен ли порт в микроте для ваергарда, можно в микроте коммандой до запуска программы:

Код: Выделить всё

/interface wireguard print where listen-port="номер порта"
Из коммандной строки запускать вот так:

Код: Выделить всё

wg-0.3.3.exe "/адрес до файла/конфиг.ваерград"
при неуказании программе конфига в качестве входного параметра или неверного файла в качестве конфига, программа закрывается.

wg-0.3.3.cpp

Код: Выделить всё


#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <ctime>

struct WireGuardConfig {
    std::string publicKey;
    std::string privateKey;
    std::string presharedKey;
    std::string address;
    std::string dns;
    std::string mtu;
    std::string endpoint;
    std::string endport;
};


int main(int argc, char* argv[]) {
     if (argc < 2 ) exit (1);
    std::map<std::string, std::string> config;
    
    std::ifstream configFile(argv[1]);
    if (!configFile.is_open()) {
        std::cerr << "Error opening config file" << std::endl;
        return 1;
    }
    std::vector<WireGuardConfig> configs;
    WireGuardConfig currentConfig;
    std::string line;
    while (std::getline(configFile, line)) {
        
        if (line.empty() || line[0] == '#') {
            continue; // skip empty lines and lines starting with #
        }
        
        std::string key, value;
        size_t pos = line.find('=');
        if (pos != std::string::npos) 
        {
            key = line.substr(0, pos);
            value = line.substr(pos + 1);
            // Remove leading and trailing whitespaces
            key.erase(0, key.find_first_not_of(" \t\r"));
            key.erase(key.find_last_not_of(" \t\r") + 1);
            value.erase(0, value.find_first_not_of(" \t\r"));
            value.erase(value.find_last_not_of(" \t\r") + 1);
            
            config[key] = value;
            
            if (key == "PublicKey") {
				currentConfig.publicKey = value;
			} else if (key == "PrivateKey") {
				currentConfig.privateKey = value;
			} else if (key == "Address") {
				currentConfig.address = value;
			} else if (key == "DNS") {
				currentConfig.dns = value;
			} else if (key == "MTU") {
				currentConfig.mtu= value;
			} else if (key == "PresharedKey") {
				currentConfig.presharedKey = value;
			} else if (key == "Endpoint") {
				currentConfig.endpoint = value.substr(0,value.find(":"));
				currentConfig.endport = value.substr(value.find(":")+1);            
			} else if (key == "}") {
				configs.push_back(currentConfig);
				currentConfig = WireGuardConfig();
			}
        }
    }
    
    
    configFile.close();
    
    
    if((currentConfig.privateKey.size() == 0 ) || (currentConfig.publicKey.size() == 0 )) exit(0);
 
 
    /****************************************************************************/
    
    // Получаем текущую дату и время
    time_t now = time(0);
    struct tm *timeinfo;
    char buffer[80];
    timeinfo = localtime(&now);
    strftime(buffer, 80, "%Y-%m-%d_%H-%M-%S", timeinfo);

    // Создаем имя файла
    std::stringstream filename;
    filename << "mikrotik_" << buffer << ".txt";
 
    /****************************************************************************/
 
    

    std::cout << std::endl;  
    std::cout << "**********************************"<< std::endl;  
    std::cout << " Export WireGuard conf -> MikroTik"<< std::endl;  
    std::cout << "**********************************"<< std::endl;  
    std::cout << ""<< std::endl;  
    std::cout << argv[1] << " -> " << filename.str() << std::endl; 
	std::cout << std::endl;   
    std::cout << std::endl;
     
    std::string wireguard_port;
    std::string wireguard_local_address;
    std::cout << "Mikrotik port Wireguard? Example: 51818" << std::endl; 
    std::getline(std::cin, wireguard_port);
    
    if(wireguard_port.size() == 0 ) wireguard_port="51818";
    
//    std::cout << std::endl;
//	std::cout << std::endl;  
    
    std::cout << "Check port MikroTik: " << std::endl;
    std::cout << std::endl;

    std::cout << std::endl;
    std::cout << "##################################"<< std::endl;  
    std::cout << std::endl;  
    std::cout << std::endl;  

     
    std::cout << "/interface wireguard print where listen-port=" << wireguard_port << std::endl;

    std::cout << std::endl;  
    std::cout << std::endl;  
    std::cout << "##################################"<< std::endl;  


    std::cout << std::endl;
	    
    std::cout << std::endl;
//    std::cout << std::endl;  
    
    std::cout << "Lockal address? Example 192.168.0.23, to exit: Ctrl^c: " << std::endl;
    std::getline(std::cin, wireguard_local_address);
    if(wireguard_local_address.size() == 0 ) wireguard_local_address="192.168.0.23";
    std::cout << std::endl;
    std::cout << std::endl;    
    

    /****************************************************************************/


    // Создаем файл
    std::ofstream file(filename.str());
    if (file.is_open()) {


      //  file << "This file was created at: " << buffer << std::endl;
        
        
    //Создание резервной копии
    file << "# Create backup" << std::endl; 
    file << "/system backup save name=backup-" << buffer;
    file << std::endl;
    
    //Создание интерфейса
    file << "# Interface wireguard" << std::endl;
    file << "/interface wireguard add";
    file <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        file << " mtu=" << currentConfig.mtu;
    file << " name=wg-" << currentConfig.endpoint << "-" << buffer;
    file << " private-key=\""<<  currentConfig.privateKey << "\"";
    file << std::endl;
    
    //Создание пира
    file << "# WireGuard peer" << std::endl;
    file << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    file << " endpoint-address=" << currentConfig.endpoint;
    file << " endpoint-port=" << currentConfig.endport;
    file << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    file << " persistent-keepalive=25s";
    file << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        file <<" preshared-key=\""<< currentConfig.presharedKey << "\"";
    file << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
    file << std::endl;
    
    //Создание локального адреса интерфейса
    file << "# Local ip address WireGuard" << std::endl;
    file << "/ip address add";
    file << " address=" << currentConfig.address;
    file << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    file << std::endl;
    
    //Создание NAT правила
     file << "# Firewall nat WireGuard" << std::endl;
     file << "/ip firewall nat add action=masquerade chain=srcnat";
     file << " out-interface=wg-" << currentConfig.endpoint << "-" << buffer;
     file << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     //Создание таблицы маршрута
     file << "# Routing table WireGuard" << std::endl;
     file << "/routing table add disabled=no fib";
     file <<  " name=vpn-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     //Создание маршрута
     file << "# Ip route WireGuard" << std::endl;
     file << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     file << " gateway=wg-"<< currentConfig.endpoint << "-" << buffer;
     file << " pref-src=\"\"";
     file << " routing-table=vpn-"<< currentConfig.endpoint << "-" << buffer; 
     file << " suppress-hw-offload=no";
     file << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     //Создание мангала
     file << "# Firewall mangle WireGuard" << std::endl;
     file << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     file << " src-address=" << wireguard_local_address;
     file << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     file << " new-routing-mark=vpn-" << currentConfig.endpoint << "-" << buffer; 
     file << " passthrough=yes"; 
     file << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     file << std::endl;
     
     file << std::endl;
     file << std::endl;        
        





        file.close();
//        std::cout << "File created successfully: " << filename.str() << std::endl;
    } else {
        std::cerr << "Error creating file" << std::endl;
    }    
    
    
    /****************************************************************************/
    
    

     //Создание резервной копии
    std::cout << "# Create backup" << std::endl; 
    std::cout << "/system backup save name=backup-" << buffer;
    std::cout << std::endl;   
    
    //Создание интерфейса
    std::cout << "# Interface wireguard" << std::endl;
    std::cout << "/interface wireguard add";
    std::cout <<  " listen-port=" << wireguard_port;
    if(currentConfig.mtu.size() != 0 ) 
        std::cout << " mtu=" << currentConfig.mtu;
    std::cout << " name=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << " private-key=\""<<  currentConfig.privateKey << "\"";
    std::cout << std::endl;
    
    //Создание пира
    std::cout << "# WireGuard peer" << std::endl;
    std::cout << "/interface wireguard peers add allowed-address=0.0.0.0/0";
    std::cout << " endpoint-address=" << currentConfig.endpoint;
    std::cout << " endpoint-port=" << currentConfig.endport;
    std::cout << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << " persistent-keepalive=25s";
    std::cout << " public-key=\"" << currentConfig.publicKey << "\"";
    if(currentConfig.presharedKey.size() != 0 )
        std::cout <<" preshared-key=\""<< currentConfig.presharedKey << "\"";
    std::cout << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << std::endl;
    
    //Создание локального адреса интерфейса
    std::cout << "# Local ip address WireGuard" << std::endl;
    std::cout << "/ip address add";
    std::cout << " address=" << currentConfig.address;
    std::cout << " interface=wg-" << currentConfig.endpoint << "-" << buffer;
    std::cout << std::endl;
    
    //Создание NAT правила
     std::cout << "# Firewall nat WireGuard" << std::endl;
     std::cout << "/ip firewall nat add action=masquerade chain=srcnat";
     std::cout << " out-interface=wg-" << currentConfig.endpoint << "-" << buffer;
     std::cout << " comment=wg-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     //Создание таблицы маршрута
     std::cout << "# Routing table WireGuard" << std::endl;
     std::cout << "/routing table add disabled=no fib";
     std::cout <<  " name=vpn-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     //Создание маршрута
     std::cout << "# Ip route WireGuard" << std::endl;
     std::cout << "/ip route add disabled=no distance=1 dst-address=0.0.0.0/0";
     std::cout << " gateway=wg-"<< currentConfig.endpoint << "-" << buffer;
     std::cout << " pref-src=\"\"";
     std::cout << " routing-table=vpn-"<< currentConfig.endpoint << "-" << buffer; 
     std::cout << " suppress-hw-offload=no";
     std::cout << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     //Создание мангала
     std::cout << "# Firewall mangle WireGuard" << std::endl;
     std::cout << "/ip firewall mangle add action=mark-routing chain=prerouting disabled=no";
     std::cout << " src-address=" << wireguard_local_address;
     std::cout << " dst-address-list=!allow-local-all protocol=tcp dst-port=443";
     std::cout << " new-routing-mark=vpn-" << currentConfig.endpoint << "-" << buffer; 
     std::cout << " passthrough=yes"; 
     std::cout << " comment=vpn-" << currentConfig.endpoint << "-" << buffer;
     std::cout << std::endl;
     
     std::cout << std::endl;
     std::cout << std::endl;
     
//     std::cout << "# Enter to exit" << std::endl;
//     std::getline(std::cin, wireguard_local_address);
//     std::cout << std::endl;
        
  
    return 0;
}


g++ -std=c++11 -o wg-0.3.3.exe wg-0.3.3.cpp