valdimirfp
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # WireGuard setup :bulb: ###### tags: `wireguard` `vpn` `PiVPN` `pivpn` [link](https://trashbox.ru/link/how-to-make-own-vpn-for-free) [PiVPN](https://pc-01.tech/wireguard-vpn/) [интересно](https://www.linuxbabe.com/ubuntu/wireguard-vpn-server-ubuntu) # Установка на отдельный сервер ## подготовка :sheep: `apt update && sudo apt upgrade -y` `sed -i 's/\#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g' /etc/sysctl.conf` `sysctl -p` ## установка `apt install wireguard -y` - Сгенерируем пару ключей для сервера. server_privatekey `wg genkey | tee VPNserver_privatekey | wg pubkey > VPNserver_publickey` - Для каждого клиентского устройства также создадим пару ключей `wg genkey | tee client01_privatekey | wg pubkey > client01_publickey` `wg genkey | tee client02_privatekey | wg pubkey > client02_publickey` - Создадим конфигурационный файл: `nano /etc/wireguard/wg0.conf` > Для каждого клиентского устройства надо добавить раздел Peer по подобному принципу, указав IP-адрес, отличающийся четвёртым числом от ранее введённых (например, для второго клиента я введу AllowedIPs = 10.0.0.3/32, для третьего — AllowedIPs = 10.0.0.4/32 и так далее), и добавив его публичный ключ: ``` [Interface] Address = 10.0.0.1/24 ListenPort = 51820 PrivateKey = <PRIV_SERV>= PostUp = iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT PostUp = iptables -A FORWARD -i wg-server -o wg-server -j DROP PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE [Peer] # client01 PublicKey = <PUB_CLIENT> AllowedIPs = 10.0.0.2/32 [Peer] # client02 PublicKey = <PUB_CLIENT> AllowedIPs = 10.0.0.3/32 ``` - Сохраним файл комбинацией клавиш Ctrl+X, нажмем Y и подтвердим клавишей Enter. Запустим сервис: `wg-quick up wg0` - задать права на директорию `chmod 600 /etc/wireguard/ -R` - Сразу добавим его в автозапуск, чтобы VPN автоматически стартовал после перезагрузки сервера: `systemctl enable wg-quick@wg0.service` `systemctl restart wg-quick@wg0` ## Скрипт создания нового опльзователя - bash ``` #!/bin/bash echo "Enter the username: " read username last_ip=$(tail -n 1 /etc/wireguard/wg0.conf | awk '{print $3}') if [ -z "$last_ip" ]; then next_ip="10.0.0.2/32" else last_octet=$(echo $last_ip | awk -F. '{print $4}' | awk -F/ '{print $1}') next_octet=$((last_octet+1)) next_ip="10.0.0.$next_octet/32" fi echo "Generating key pair for $username..." private_key=$(wg genkey) public_key=$(echo $private_key | wg pubkey) # /etc/wireguard/wg0.conf echo "Adding user to the server config..." echo "[Peer]" >> /etc/wireguard/wg0.conf echo "# $username" >> /etc/wireguard/wg0.conf echo "PublicKey = $public_key" >> /etc/wireguard/wg0.conf echo "AllowedIPs = $next_ip" >> /etc/wireguard/wg0.conf # user conf echo "Adding user to the client config..." echo "[Interface]" >> /etc/wireguard/conf/$username.conf echo "Address = $next_ip" >> /etc/wireguard/conf/$username.conf echo "PrivateKey = $private_key" >> /etc/wireguard/conf/$username.conf echo "DNS = 8.8.8.8, 8.8.4.4" >> /etc/wireguard/conf/$username.conf echo "[Peer]" >> /etc/wireguard/conf/$username.conf echo "PublicKey = <PublicKey>=" >> /etc/wireguard/conf/$username.conf echo "PersistentKeepalive = 25" >> /etc/wireguard/conf/$username.conf echo "Endpoint = <YOUR_DOMAIN_OR_IP>:51820" >> /etc/wireguard/conf/$username.conf echo "AllowedIPs = 0.0.0.0/0, ::/0" >> /etc/wireguard/conf/$username.conf echo "Generating QR code for $username..." qrencode -t ansiutf8 < /etc/wireguard/conf/$username.conf > /etc/wireguard/conf/$username.qr # restart service echo "Restarting WireGuard service..." systemctl restart wg-quick@wg0 cat /etc/wireguard/conf/$username.qr echo "User $username created successfully!" echo "Client configuration file and QR code can be found in /etc/wireguard/conf/$username.conf and /etc/wireguard/conf/$username.qr respectively." ``` - python ``` #!/usr/bin/env python3 username = input("Enter the username: ") with open("/etc/wireguard/wg0.conf", "r") as f: lines = f.readlines() last_line = lines[-1] if last_line.startswith("[Peer]"): last_ip = last_line.split("=")[-1].strip() last_octet = int(last_ip.split(".")[-1].split("/")[0]) next_octet = last_octet + 1 next_ip = "10.0.0.{}/32".format(next_octet) else: next_ip = "10.0.0.2/32" import subprocess private_key = subprocess.run(["wg", "genkey"], capture_output=True).stdout.decode("utf-8").strip() public_key = subprocess.run(["wg", "pubkey"], input=private_key.encode("utf-8"), capture_output=True).stdout.decode("utf-8").strip() with open("/etc/wireguard/wg0.conf", "a") as f: f.write("\n[Peer]\n") f.write("# {}\n".format(username)) f.write("PublicKey = {}\n".format(public_key)) f.write("AllowedIPs = {}\n".format(next_ip)) with open("/etc/wireguard/conf/{}.conf".format(username), "w") as f: f.write("[Interface]\n") f.write("Address = {}\n".format(next_ip)) f.write("PrivateKey = {}\n".format(private_key)) f.write("DNS = 8.8.8.8, 8.8.4.4\n") f.write("\n[Peer]\n") f.write("PublicKey = <PublicKEY>\n") f.write("PersistentKeepalive = 25\n") f.write("Endpoint = vpn2.<YOUR_DOMAIN>.ru:51820\n") f.write("AllowedIPs = 0.0.0.0/0, ::/0\n") import os os.system("qrencode -t ansiutf8 < /etc/wireguard/conf/{}.conf > /etc/wireguard/conf/{}.qr".format(username, username)) os.system("systemctl restart wg-quick@wg0") print("User {} created successfully!".format(username)) print("Client configuration file and QR code can be found in /etc/wireguard/conf/{}.conf and /etc/wireguard/conf/{}.qr respectively.".format(username, username)) ``` ## Подключение к VPN :rocket: - для мобильных устройств удобно использавать QR код `apt install qrencode -y` - создадим файлы для клиентов - не забываем менять IP адреса `nano client01.conf` ``` [Interface] Address = 10.0.0.2/32 PrivateKey = <PRIV_CLIENT> DNS = 8.8.8.8, 8.8.4.4 [Peer] PublicKey = <PUB_SERV> Endpoint = <IP>:51820 PersistentKeepalive = 20 AllowedIPs = 0.0.0.0/0, ::/0 ``` `nano client02.conf` ``` [Interface] Address = 10.0.0.3/32 PrivateKey = <PRIV_CLIENT> DNS = 8.8.8.8, 8.8.4.4 [Peer] PublicKey = <PUB_SERV> Endpoint = <IP>:51820 PersistentKeepalive = 20 AllowedIPs = 0.0.0.0/0, ::/0 ``` ### Натсройка для смартфона :iphone: - Сохраним файл комбинацией клавиш Ctrl+X, нажмем Y и подтвердим клавишей Enter. Сгенерируем QR-код: - скачать app [wireguard](https://www.wireguard.com/install/) для смартфона `qrencode -t ansiutf8 < client01.conf` ![](https://i.imgur.com/vvo2c79.png) ### Настройка для ПК :computer: - для ПК можно скопировать или переписать файл конфигурации и подсунуть клиенту # Установка на Mikrotik :fire: ### настройка интерфейса и пира - обновить микрот до 7й версии - создать новый интерфейс wireguard * после нажатия Apply нолучим Private и Public Keys ![](https://i.imgur.com/I8t9YNp.png) - переходим во вкладку IP -> Addresses и задаем адрес и подесть для интерфейса wireguard ![](https://i.imgur.com/mtJukVb.png) - на компьютере идем в клиента wireguard и создаем новый пустой тонель ![](https://i.imgur.com/5W0bxnX.png) - при этом приложение генерит нам публичный и приватный ключи клиента - прописываем конфигурацию ![](https://i.imgur.com/PfxywzO.png) `[Interface]` - приватный ключ генерится по умолчанию в приложением - Address пишем адрем который будет у клиента при подключении из диапазона подсети wireguard ограничение маской /32 делаемся для запрета обмена данными меду пирами `[Peer]` - PublicKey - копируем с интерфейса WireGuard на mikrotik - Endpoint - адрес и порт куда подключаемся ``` [Interface] PrivateKey = cG************+M0Q= Address = 10.0.0.3/32 DNS = 8.8.8.8, 8.8.4.4 [Peer] PublicKey = qP0***************jE= AllowedIPs = 0.0.0.0/0 Endpoint = external_ip:13231 ``` - сохраняем настройки - возвращаемся к настройкам wireguard, переходим во вкладку Peers и создаем новый Peer - вносим Allowed Address из диапазона адресов wiregaurd с маской /32 ![](https://i.imgur.com/X9aW1yQ.png) ### настройка сетевого взаимодействия что бы у клиента работала сеть нужно настроить разрешающее правило и NAT - разрешим входящие на WAN порт из интернета на UDP 13231 > возможно надо изменить WAN интерфейс на свой куда приходит интернет ``` /ip firewall filter add action=accept chain=input comment=WireGuard dst-port=13231 in-interface=ether1 protocol=udp ``` - настроим правило NAT ``` ip firewall/nat/ add action=masquerade chain=srcnat out-interface=ether1 src-address=10.0.0.0/24 ``` - если мы не хотим пускать пользователей VPN во веутреннюю сеть, то надо сделать запрещиющее правило на все возможные внутренние адреса - зададим все внутренние адреса ``` /ip firewall address-list add address=0.0.0.0/8 comment=RFC6890 list=not_in_internet add address=172.16.0.0/12 comment=RFC6890 list=not_in_internet add address=192.168.0.0/16 comment=RFC6890 list=not_in_internet add address=10.0.0.0/8 comment=RFC6890 list=not_in_internet add address=169.254.0.0/16 comment=RFC6890 list=not_in_internet add address=127.0.0.0/8 comment=RFC6890 list=not_in_internet add address=224.0.0.0/4 comment=Multicast list=not_in_internet add address=198.18.0.0/15 comment=RFC6890 list=not_in_internet add address=192.0.0.0/24 comment=RFC6890 list=not_in_internet add address=192.0.2.0/24 comment=RFC6890 list=not_in_internet add address=198.51.100.0/24 comment=RFC6890 list=not_in_internet add address=203.0.113.0/24 comment=RFC6890 list=not_in_internet add address=100.64.0.0/10 comment=RFC6890 list=not_in_internet add address=240.0.0.0/4 comment=RFC6890 list=not_in_internet ``` - настроим блокирующее праавило ``` /ip firewall filter add action=reject chain=forward comment="VLAN Reject" dst-address-list=not_in_internet log=yes reject-with=icmp-net-prohibited src-address=10.0.0.0/24 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully