Browse Source

Merge pull request #2 from Yamzik/fix-client-state

Fix client state
pull/438/head
Yamzik 4 years ago
committed by GitHub
parent
commit
d6dab6c3b0
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      Application.Deploy.Dockerfile
  2. 8
      data/wg0.conf
  3. 18
      data/wg0.json
  4. 528
      data/www/index.html
  5. 11
      data/www/manifest.json
  6. 2
      docker-compose.deploy.yml
  7. 2
      docker-compose.yml
  8. 73
      src/utils/os.rs
  9. 91
      src/wg_rs/config.rs
  10. 51
      src/wg_rs/wireguard.rs

3
Application.Deploy.Dockerfile

@ -3,7 +3,8 @@ RUN apk add -U --no-cache wireguard-tools dumb-init
FROM alpine_wg AS runtime FROM alpine_wg AS runtime
COPY application/bin/rs-wg /usr/local/cargo/bin/rs-wg COPY application/bin/rs-wg /usr/local/cargo/bin/rs-wg
COPY data/wg /etc/wireguard # COPY data/wireguard /etc/wireguard
CMD [ "mkdir", "/etc/wireguard" ]
COPY data/www /etc/www COPY data/www /etc/www
WORKDIR /etc/wireguard WORKDIR /etc/wireguard
EXPOSE 8080 EXPOSE 8080

8
data/wg0.conf

@ -3,7 +3,7 @@
# Server # Server
[Interface] [Interface]
PrivateKey = aCjYU+CBAkIerzXXFj8hzc4ZmMDLNGrhsxqJjOwtPH0= PrivateKey = 7djcxyZBiUQ6OrB36p1cKLGHl1zg5MqQShN9Udl41Hw=
Address = 10.8.0.1/24 Address = 10.8.0.1/24
ListenPort = 51820 ListenPort = 51820
PreUp = PreUp =
@ -11,3 +11,9 @@ PostUp = iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE; ip
PreDown = PreDown =
PostDown = PostDown =
# Client: 321 (184a9b70-03b3-4bfb-ae89-ce463634f394)
[Peer]
PublicKey = ej10pb+XPRVuotGrkz+423Lku6Jyf5OHqt0ccjx6KU8=
PresharedKey = Y/5LvXKegqRoeugphZZOLS1/Kl+wN+HdJoCdulxzrEs=
AllowedIPs = 10.8.0.2/32

18
data/wg0.json

@ -1,8 +1,20 @@
{ {
"server": { "server": {
"privateKey": "aCjYU+CBAkIerzXXFj8hzc4ZmMDLNGrhsxqJjOwtPH0=", "privateKey": "7djcxyZBiUQ6OrB36p1cKLGHl1zg5MqQShN9Udl41Hw=",
"publicKey": "Gi9QI2VgCJK1ziPaE2gE/jXbiXj+Rx3mUbIq8RcHPEE=", "publicKey": "kAW7Jefvgqs5H6hyuF05a1vSZJJdAiedg3AnVdgjFVk=",
"address": "10.8.0.1" "address": "10.8.0.1"
}, },
"clients": {} "clients": {
"184a9b70-03b3-4bfb-ae89-ce463634f394": {
"uuid": "184a9b70-03b3-4bfb-ae89-ce463634f394",
"name": "321",
"address": "10.8.0.2",
"privateKey": "+K2Bi7AYB1pUCWqIPdRIpqnGFOjG0PE7W8pOBLsatXo=",
"publicKey": "ej10pb+XPRVuotGrkz+423Lku6Jyf5OHqt0ccjx6KU8=",
"preSharedKey": "Y/5LvXKegqRoeugphZZOLS1/Kl+wN+HdJoCdulxzrEs=",
"createdAt": "2022-12-18T15:55:49Z",
"updatedAt": "2022-12-18T15:55:49Z",
"enabled": true
}
}
} }

528
data/www/index.html

@ -1,528 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>WireGuard</title>
<link href="./css/vendor/tailwind.min.css" rel="stylesheet">
<link rel="manifest" href="./manifest.json">
<link rel="icon" type="image/png" href="./img/favicon.png">
<link rel="apple-touch-icon" href="./img/apple-touch -icon.png">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="apple-mobile-web-app-capable" content="yes">
</head>
<style>
[v-cloak] {
display: none;
}
</style>
<body class="bg-gray-50">
<div id="app">
<div v-cloak class="container mx-auto max-w-3xl">
<div v-if="authenticated === true">
<span v-if="requiresPassword"
class="text-sm text-gray-400 mb-10 mr-2 mt-3 cursor-pointer hover:underline float-right" @click="logout">
Logout
<svg class="h-3 inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg>
</span>
<h1 class="text-4xl font-medium mt-10 mb-2">
<img src="./img/logo.png" width="32" class="inline align-middle" />
<span class="align-middle">WireGuard</span>
</h1>
<h2 class="text-sm text-gray-400 mb-10"></h2>
<div v-if="latestRelease" class="bg-red-800 p-4 text-white text-sm font-small mb-10 rounded-md shadow-lg"
:title="`v${currentRelease} → v${latestRelease.version}`">
<div class="container mx-auto flex flex-row flex-auto items-center">
<div class="flex-grow">
<p class="font-bold">There is an update available!</p>
<p>{{latestRelease.changelog}}</p>
</div>
<a href="https://github.com/WeeJeWel/wg-easy#updating" target="_blank"
class="p-3 rounded-md bg-white float-right font-sm font-semibold text-red-800 flex-shrink-0 border-2 border-red-800 hover:border-white hover:text-white hover:bg-red-800 transition-all">
Update →
</a>
</div>
</div>
<div class="shadow-md rounded-lg bg-white overflow-hidden">
<div class="flex flex-row flex-auto items-center p-3 px-5 border border-b-2 border-gray-100">
<div class="flex-grow">
<p class="text-2xl font-medium">Clients</p>
</div>
<div class="flex-shrink-0">
<button @click="clientCreate = true; clientCreateName = '';"
class="hover:bg-red-800 hover:border-red-800 hover:text-white text-gray-700 border-2 border-gray-100 py-2 px-4 rounded inline-flex items-center transition">
<svg class="w-4 mr-2" inline xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
<span class="text-sm">New</span>
</button>
</div>
</div>
<div>
<!-- Client -->
<div v-if="clients && clients.length > 0" v-for="client in clients" :key="client.id"
class="relative overflow-hidden border-b border-gray-100 border-solid">
<!-- Chart -->
<div class="absolute z-0 bottom-0 left-0 right-0" style="width: 100%; height: 20%;">
<!-- Bar -->
<div v-for="(_, index) in client.transferTxHistory" :style="{
display: 'inline-flex',
alignItems: 'flex-end',
width: '2%', // 1/100th of client.transferTxHistory.length
height: '100%',
padding: '0 3px',
boxSizing: 'border-box',
fontSize: 0,
}">
<!-- TX -->
<div :style="{
minHeight: '0px',
minWidth: '2px',
maxWidth: '4px',
width: '50%',
marginRight: '1px',
height: Math.round((client.transferTxHistory[index]/client.transferMax)*100) + '%',
background: client.hoverTx
? '#992922'
: '#F3F4F6',
transition: 'all 0.2s',
borderRadius: '2px 2px 0 0',
}"></div>
<!-- RX -->
<div :style="{
minHeight: '0px',
minWidth: '2px',
maxWidth: '4px',
width: '50%',
height: Math.round((client.transferRxHistory[index]/client.transferMax)*100) + '%',
background: client.hoverRx
? '#992922'
: '#F0F1F3',
transition: 'all 0.2s',
borderRadius: '2px 2px 0 0',
}"></div>
</div>
</div>
<div class="relative p-5 z-10 flex flex-row">
<div class="h-10 w-10 mr-5 rounded-full bg-gray-50 relative">
<svg class="w-6 m-2 text-gray-300" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
fill="currentColor">
<path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
clip-rule="evenodd" />
</svg>
<img v-if="client.avatar" :src="client.avatar" class="w-10 rounded-full absolute top-0 left-0" />
<div
v-if="client.latestHandshakeAt && ((new Date() - new Date(client.latestHandshakeAt) < 1000 * 60 * 10))">
<div class="animate-ping w-4 h-4 p-1 bg-red-100 rounded-full absolute -bottom-1 -right-1"></div>
<div class="w-2 h-2 bg-red-800 rounded-full absolute bottom-0 right-0"></div>
</div>
</div>
<div class="flex-grow">
<!-- Name -->
<div class="text-gray-700 group" :title="'Created on ' + dateTime(new Date(client.createdAt))">
<!-- Show -->
<input v-show="clientEditNameId === client.id" v-model="clientEditName"
v-on:keyup.enter="updateClientName(client, clientEditName); clientEditName = null; clientEditNameId = null;"
v-on:keyup.escape="clientEditName = null; clientEditNameId = null;"
:ref="'client-' + client.id + '-name'"
class="rounded px-1 border-2 border-gray-100 focus:border-gray-200 outline-none w-30" />
<span v-show="clientEditNameId !== client.id"
class="inline-block border-t-2 border-b-2 border-transparent">{{client.name}}</span>
<!-- Edit -->
<span v-show="clientEditNameId !== client.id"
@click="clientEditName = client.name; clientEditNameId = client.id; setTimeout(() => $refs['client-' + client.id + '-name'][0].select(), 1);"
class="cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity">
<svg xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4 inline align-middle opacity-25 hover:opacity-100" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</span>
</div>
<!-- Info -->
<div class="text-gray-400 text-xs">
<!-- Address -->
<span class="group">
<!-- Show -->
<input v-show="clientEditAddressId === client.id" v-model="clientEditAddress"
v-on:keyup.enter="updateClientAddress(client, clientEditAddress); clientEditAddress = null; clientEditAddressId = null;"
v-on:keyup.escape="clientEditAddress = null; clientEditAddressId = null;"
:ref="'client-' + client.id + '-address'"
class="rounded border-2 border-gray-100 focus:border-gray-200 outline-none w-20 text-black" />
<span v-show="clientEditAddressId !== client.id"
class="inline-block border-t-2 border-b-2 border-transparent">{{client.address}}</span>
<!-- Edit -->
<span v-show="clientEditAddressId !== client.id"
@click="clientEditAddress = client.address; clientEditAddressId = client.id; setTimeout(() => $refs['client-' + client.id + '-address'][0].select(), 1);"
class="cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity">
<svg xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4 inline align-middle opacity-25 hover:opacity-100" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</span>
</span>
<!-- Transfer TX -->
<span v-if="client.transferTx" :title="'Total Download: ' + bytes(client.transferTx)"
@mouseover="client.hoverTx = clientsPersist[client.id].hoverTx = true;"
@mouseleave="client.hoverTx = clientsPersist[client.id].hoverTx = false;"
style="cursor: default;">
·
<svg class="align-middle h-3 inline" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
fill="currentColor">
<path fill-rule="evenodd"
d="M16.707 10.293a1 1 0 010 1.414l-6 6a1 1 0 01-1.414 0l-6-6a1 1 0 111.414-1.414L9 14.586V3a1 1 0 012 0v11.586l4.293-4.293a1 1 0 011.414 0z"
clip-rule="evenodd" />
</svg>
{{client.transferTxCurrent | bytes}}/s
</span>
<!-- Transfer RX -->
<span v-if="client.transferRx" :title="'Total Upload: ' + bytes(client.transferRx)"
@mouseover="client.hoverRx = clientsPersist[client.id].hoverRx = true;"
@mouseleave="client.hoverRx = clientsPersist[client.id].hoverRx = false;"
style="cursor: default;">
·
<svg class="align-middle h-3 inline" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
fill="currentColor">
<path fill-rule="evenodd"
d="M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z"
clip-rule="evenodd" />
</svg>
{{client.transferRxCurrent | bytes}}/s
</span>
<!-- Last seen -->
<span v-if="client.latestHandshakeAt"
:title="'Last seen on ' + dateTime(new Date(client.latestHandshakeAt))">
· {{new Date(client.latestHandshakeAt) | timeago}}
</span>
</div>
</div>
<div class="text-right">
<div class="text-gray-400">
<!-- Enable/Disable -->
<div @click="disableClient(client)" v-if="client.enabled === true" title="Disable Client"
class="inline-block align-middle rounded-full w-10 h-6 mr-1 bg-red-800 cursor-pointer hover:bg-red-700 transition-all">
<div class="rounded-full w-4 h-4 m-1 ml-5 bg-white"></div>
</div>
<div @click="enableClient(client)" v-if="client.enabled === false" title="Enable Client"
class="inline-block align-middle rounded-full w-10 h-6 mr-1 bg-gray-200 cursor-pointer hover:bg-gray-300 transition-all">
<div class="rounded-full w-4 h-4 m-1 bg-white"></div>
</div>
<!-- Show QR-->
<button class="align-middle bg-gray-100 hover:bg-red-800 hover:text-white p-2 rounded transition"
title="Show QR Code" @click="qrcode = `./api/wireguard/client/${client.id}/qrcode.svg`">
<svg class="w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z" />
</svg>
</button>
<!-- Download Config -->
<a :href="'./api/wireguard/client/' + client.id + '/configuration'" download
class="align-middle inline-block bg-gray-100 hover:bg-red-800 hover:text-white p-2 rounded transition"
title="Download Configuration">
<svg class="w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</a>
<!-- Delete -->
<button class="align-middle bg-gray-100 hover:bg-red-800 hover:text-white p-2 rounded transition"
title="Delete Client" @click="clientDelete = client">
<svg class="w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
clip-rule="evenodd" />
</svg>
</button>
</div>
</div>
</div>
</div>
<div v-if="clients && clients.length === 0">
<p class="text-center m-10 text-gray-400 text-sm">There are no clients yet.<br /><br />
<button @click="clientCreate = true; clientCreateName = '';"
class="bg-red-800 text-white hover:bg-red-700 border-2 border-none py-2 px-4 rounded inline-flex items-center transition">
<svg class="w-4 mr-2" inline xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
<span class="text-sm">New Client</span>
</button>
</p>
</div>
<div v-if="clients === null" class="text-gray-200 p-5">
<svg class="w-5 animate-spin mx-auto" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
fill="currentColor">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
</div>
</div>
</div>
<!-- QR Code-->
<div v-if="qrcode">
<div class="bg-black bg-opacity-50 fixed top-0 right-0 left-0 bottom-0 flex items-center justify-center z-20">
<div class="bg-white rounded-md shadow-lg relative p-8">
<button @click="qrcode = null" class="absolute right-4 top-4 text-gray-600 hover:text-gray-800">
<svg class="w-8" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<img :src="qrcode" />
</div>
</div>
</div>
<!-- Create Dialog -->
<div v-if="clientCreate" class="fixed z-10 inset-0 overflow-y-auto">
<div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<!--
Background overlay, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0"
To: "opacity-100"
Leaving: "ease-in duration-200"
From: "opacity-100"
To: "opacity-0"
-->
<div class="fixed inset-0 transition-opacity" aria-hidden="true">
<div class="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
<!-- This element is to trick the browser into centering the modal contents. -->
<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
<!--
Modal panel, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
To: "opacity-100 translate-y-0 sm:scale-100"
Leaving: "ease-in duration-200"
From: "opacity-100 translate-y-0 sm:scale-100"
To: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
-->
<div
class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
role="dialog" aria-modal="true" aria-labelledby="modal-headline">
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="sm:flex sm:items-start">
<div
class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-800 sm:mx-0 sm:h-10 sm:w-10">
<svg class="h-6 w-6 text-white" inline xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</div>
<div class="flex-grow mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-headline">
New Client
</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
<input class="rounded p-2 border-2 border-gray-100 focus:border-gray-200 outline-none w-full"
type="text" v-model.trim="clientCreateName" placeholder="Name" />
</p>
</div>
</div>
</div>
</div>
<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button v-if="clientCreateName.length" type="button" @click="createClient(); clientCreate = null"
class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-800 text-base font-medium text-white hover:bg-red-700 focus:outline-none sm:ml-3 sm:w-auto sm:text-sm">
Create
</button>
<button v-else type="button"
class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-200 text-base font-medium text-white sm:ml-3 sm:w-auto sm:text-sm cursor-not-allowed">
Create
</button>
<button type="button" @click="clientCreate = null"
class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
Cancel
</button>
</div>
</div>
</div>
</div>
<!-- Delete Dialog -->
<div v-if="clientDelete" class="fixed z-10 inset-0 overflow-y-auto">
<div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<!--
Background overlay, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0"
To: "opacity-100"
Leaving: "ease-in duration-200"
From: "opacity-100"
To: "opacity-0"
-->
<div class="fixed inset-0 transition-opacity" aria-hidden="true">
<div class="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
<!-- This element is to trick the browser into centering the modal contents. -->
<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
<!--
Modal panel, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
To: "opacity-100 translate-y-0 sm:scale-100"
Leaving: "ease-in duration-200"
From: "opacity-100 translate-y-0 sm:scale-100"
To: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
-->
<div
class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
role="dialog" aria-modal="true" aria-labelledby="modal-headline">
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="sm:flex sm:items-start">
<div
class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
<!-- Heroicon name: outline/exclamation -->
<svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke="currentColor" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
</div>
<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-headline">
Delete Client
</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
Are you sure you want to delete <strong>{{clientDelete.name}}</strong>?
This action cannot be undone.
</p>
</div>
</div>
</div>
</div>
<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button type="button" @click="deleteClient(clientDelete); clientDelete = null"
class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
Delete
</button>
<button type="button" @click="clientDelete = null"
class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
<div v-if="authenticated === false">
<h1 class="text-4xl font-medium my-16 text-gray-700 text-center">WireGuard</h1>
<form @submit="login" class="shadow rounded-md bg-white mx-auto w-64 p-5 overflow-hidden mt-10">
<!-- Avatar -->
<div class="h-20 w-20 mb-10 mt-5 mx-auto rounded-full bg-red-800 relative overflow-hidden">
<svg class="w-10 h-10 m-5 text-white" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
fill="currentColor">
<path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
</svg>
</div>
<input type="password" name="password" placeholder="Password" v-model="password"
class="px-3 py-2 text-sm text-gray-500 mb-5 border-2 border-gray-100 rounded-lg w-full focus:border-red-800 outline-none" />
<button v-if="authenticating"
class="bg-red-800 w-full rounded shadow py-2 text-sm text-white cursor-not-allowed">
<svg class="w-5 animate-spin mx-auto" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
fill="currentColor">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
</button>
<input v-if="!authenticating && password" type="submit"
class="bg-red-800 w-full rounded shadow py-2 text-sm text-white hover:bg-red-700 transition cursor-pointer"
value="Sign In">
<input v-if="!authenticating && !password" type="submit"
class="bg-gray-200 w-full rounded shadow py-2 text-sm text-white cursor-not-allowed" value="Sign In">
</form>
</div>
<div v-if="authenticated === null" class="text-gray-300 pt-24 pb-12">
<svg class="w-5 animate-spin mx-auto" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
fill="currentColor">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
</div>
</div>
<p v-cloak class="text-center m-10 text-gray-300 text-xs">Made by <a target="_blank" class="hover:underline"
href="https://emilenijssen.nl/?ref=wg-easy">Emile Nijssen</a> · <a class="hover:underline"
href="https://github.com/sponsors/WeeJeWel" target="_blank">Donate</a> · <a class="hover:underline"
href="https://github.com/weejewel/wg-easy" target="_blank">GitHub</a></p>
</div>
<script src="./js/vendor/vue.min.js"></script>
<script src="./js/vendor/md5.min.js"></script>
<script src="./js/vendor/timeago.min.js"></script>
<script src="./js/api.js"></script>
<script src="./js/app.js"></script>
</body>
</html>

11
data/www/manifest.json

@ -1,11 +0,0 @@
{
"name": "WireGuard",
"display": "standalone",
"background_color": "#fff",
"icons": [
{
"src": "img/favicon.png",
"type": "image/png"
}
]
}

2
docker-compose.deploy.yml

@ -5,7 +5,7 @@ services:
container_name: rs-wg container_name: rs-wg
environment: environment:
- WIREGUARD_SETTINGS=/etc/wireguard/settings.json - WIREGUARD_SETTINGS=/etc/wireguard/settings.json
- WIREGUARD_PATH=/etc/wireguard/ - WIREGUARD_PATH=/etc/wireguard
- STATIC_DIR=/etc/www/ - STATIC_DIR=/etc/www/
- RUST_LOG=actix_web=warn,debug - RUST_LOG=actix_web=warn,debug

2
docker-compose.yml

@ -5,7 +5,7 @@ services:
container_name: rs-wg container_name: rs-wg
environment: environment:
- WIREGUARD_SETTINGS=/etc/wireguard/settings.json - WIREGUARD_SETTINGS=/etc/wireguard/settings.json
- WIREGUARD_PATH=/etc/wireguard/ - WIREGUARD_PATH=/etc/wireguard
- STATIC_DIR=/etc/wireguard/www - STATIC_DIR=/etc/wireguard/www
- RUST_LOG=actix_web=warn,debug - RUST_LOG=actix_web=warn,debug

73
src/utils/os.rs

@ -1,8 +1,27 @@
use std::{ffi::OsStr, string::FromUtf8Error}; use std::{error::Error, string::FromUtf8Error};
use futures_util::TryFutureExt;
use log::{info, warn}; use log::{info, warn};
use serde::Serialize; use serde::Serialize;
use tokio::{fs::File, io::AsyncReadExt, process::Command}; use tokio::{
fs::File,
io::{AsyncReadExt, AsyncWriteExt},
process::Command,
};
// pub struct Error<T: ToString> {
// error: T,
// }
// impl<T: ToString> Error<T> {
// pub fn new(error: T) -> Self {
// Self { error }
// }
// }
// impl<T: ToString> ToString for Error<T> {
// fn to_string(&self) -> String {
// self.error.to_string()
// }
// }
#[derive(Serialize)] #[derive(Serialize)]
pub struct StdResult { pub struct StdResult {
@ -21,26 +40,38 @@ impl StdResult {
} }
} }
pub async fn load_file<S: Into<String>>(path: S) -> Result<File, std::io::Error> { pub async fn write_file<P: Into<String>, D: Into<String>>(
path: P,
data: D,
) -> Result<(), std::io::Error> {
tokio::fs::OpenOptions::new() tokio::fs::OpenOptions::new()
.append(false)
.read(true)
.write(true)
.create(true) .create(true)
.write(true)
.truncate(true)
.open(path.into()) .open(path.into())
.and_then(|mut file| async move { file.write(data.into().as_bytes()).await.map(|_| file) })
.and_then(|mut file| async move { file.flush().await })
.await .await
} }
pub async fn read_file(mut file: File) -> Result<String, std::io::Error> { pub async fn read_file<S: Into<String>>(path: S) -> Result<String, std::io::Error> {
let mut dst = String::new(); tokio::fs::OpenOptions::new()
file.read_to_string(&mut dst).await.map(|_| dst) .create(true)
.write(true)
.read(true)
.open(path.into())
.and_then(|mut file| async move {
let mut dst = String::new();
file.read_to_string(&mut dst).await.map(|_| dst)
})
.await
} }
pub async fn load_file_unhandled(path: &str) -> File { pub async fn load_file_unhandled(path: &str) -> File {
match tokio::fs::OpenOptions::new() match tokio::fs::OpenOptions::new()
.append(false)
.read(true) .read(true)
.write(true) .write(true)
.truncate(true)
.create(true) .create(true)
.open(path) .open(path)
.await .await
@ -65,27 +96,23 @@ pub async fn load_and_read_file_unhandled(path: &str) -> (File, String) {
} }
} }
pub async fn exec_sh<S: Into<String>>(command: S) -> Result<StdResult, String> { pub async fn exec_sh<S: ToString>(command: &S) -> Result<StdResult, Box<dyn Error>> {
let command = command.into(); let command = command.to_string();
info!("$ {}", command.clone()); info!("$ {}", command.clone());
let res = match Command::new("sh").arg("-c").arg(command).output().await { let res = match Command::new("sh").arg("-c").arg(command).output().await {
Ok(val) => val, Ok(val) => val,
Err(err) => return Err(err.to_string()), Err(err) => return Err(Box::new(err)),
}; };
let stdout_b = &res.stdout.to_vec(); let stdout_b = &res.stdout.to_vec();
let stderr_b = &res.stderr.to_vec(); let stderr_b = &res.stderr.to_vec();
let stdout = match remove_escape(stdout_b) { match remove_escape(stdout_b)
Ok(val) => val, .and_then(|stdout| remove_escape(stderr_b).map(|stderr| (stdout, stderr)))
Err(err) => return Err(err.to_string()), {
}; Ok((stdout, stderr)) => Ok(StdResult { stdout, stderr }),
let stderr = match remove_escape(stderr_b) { Err(err) => return Err(Box::new(err)),
Ok(val) => val, }
Err(err) => return Err(err.to_string()),
};
Ok(StdResult { stdout, stderr })
} }
pub fn remove_escape(bytes: &Vec<u8>) -> Result<String, FromUtf8Error> { pub fn remove_escape(bytes: &Vec<u8>) -> Result<String, FromUtf8Error> {

91
src/wg_rs/config.rs

@ -1,11 +1,12 @@
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, error::Error, sync::Arc};
use chrono::{SecondsFormat, SubsecRound, Utc}; use chrono::{SecondsFormat, SubsecRound, Utc};
use futures_util::TryFutureExt; use futures_util::TryFutureExt;
use log::error;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::{io::AsyncWriteExt, join}; use tokio::join;
use uuid::Uuid; use uuid::Uuid;
use crate::utils::{misc, os}; use crate::utils::{misc, os};
@ -127,38 +128,45 @@ pub struct Accessor {
} }
impl Accessor { impl Accessor {
pub async fn new(memento_path: String, config_path: String, settings: Arc<Settings>) -> Self { pub async fn build(
let memento_str = os::load_file(memento_path.clone()) memento_path: String,
.and_then(|file| os::read_file(file)) config_path: String,
settings: Arc<Settings>,
) -> Result<Self, Box<dyn Error>> {
let memento_str = os::read_file(memento_path.clone())
.await .await
.expect("Could not read memento"); .expect("Could not read memento");
let memento = if memento_str.is_empty() { if memento_str.is_empty() {
log::info!("Creating new WireGuard configuration..."); log::info!("Creating new WireGuard configuration...");
let private_key = os::exec_sh("wg genkey").await.expect("error genkey").stdout; os::exec_sh(&"wg genkey")
let public_key = os::exec_sh(format!("echo {} | wg pubkey", private_key)) .and_then(|res_public| async move {
os::exec_sh(&format!("echo {} | wg pubkey", &res_public.stdout))
.await
.map(|res_private| (res_public.stdout, res_private.stdout))
})
.await .await
.expect("error pubkey") .and_then(|(public_key, private_key)| {
.stdout; let address = settings.default_address.clone();
let memento = Memento::new(Server {
let address = settings.default_address.clone(); private_key,
let memento = Memento::new(Server { public_key,
private_key, address,
public_key, });
address, log::info!("WireGuard configuration generated...");
}); Ok(memento)
log::info!("WireGuard configuration generated..."); })
memento
} else { } else {
serde_json::from_str(&memento_str).expect("Could not serialize memento") Ok(serde_json::from_str(&memento_str).expect("Could not serialize memento"))
};
Self {
config_path,
memento_path,
memento,
settings,
} }
.and_then(|memento| {
Ok(Self {
config_path,
memento_path,
memento,
settings,
})
})
} }
pub async fn set(&mut self, memento: Memento) { pub async fn set(&mut self, memento: Memento) {
@ -169,25 +177,20 @@ impl Accessor {
ser_memento.push('\n'); ser_memento.push('\n');
ser_config.push('\n'); ser_config.push('\n');
_ = join!( let (memento_wr, config_wr) = join!(
async { os::write_file(self.memento_path.clone(), ser_memento),
let mut file = os::load_file(self.memento_path.clone()) os::write_file(self.config_path.clone(), ser_config)
.await
.expect("Could not load memento");
file.write(ser_memento.as_bytes())
.await
.expect("Could not write memento");
},
async {
let mut file = os::load_file(self.config_path.clone())
.await
.expect("Could not load config");
file.write(ser_config.as_bytes())
.await
.expect("Could not write config");
}
); );
memento_wr.unwrap_or_else(|err| {
error!("Could not write memento: {}", err);
panic!()
});
config_wr.unwrap_or_else(|err| {
error!("Could not write config: {}", err);
panic!()
});
self.memento = memento; self.memento = memento;
} }

51
src/wg_rs/wireguard.rs

@ -2,6 +2,7 @@ use std::sync::Arc;
use chrono::{SecondsFormat, SubsecRound, Utc}; use chrono::{SecondsFormat, SubsecRound, Utc};
use log::error;
use uuid::Uuid; use uuid::Uuid;
use crate::utils::{misc, os}; use crate::utils::{misc, os};
@ -17,7 +18,7 @@ pub struct WireGuard {
impl WireGuard { impl WireGuard {
pub async fn new(name: &str, wg_path: String, settings: Settings) -> Self { pub async fn new(name: &str, wg_path: String, settings: Settings) -> Self {
let path = format!("{}{}", wg_path, name); let path = format!("{}/{}", wg_path, name);
let config_path = format!("{}.conf", path); let config_path = format!("{}.conf", path);
let memento_path = format!("{}.json", path); let memento_path = format!("{}.json", path);
let name = format!("{}", name); let name = format!("{}", name);
@ -27,32 +28,46 @@ impl WireGuard {
Self { Self {
name, name,
settings: counter.clone(), settings: counter.clone(),
memento_accessor: Accessor::new(memento_path, config_path, counter).await, memento_accessor: Accessor::build(memento_path, config_path, counter)
.await
.unwrap_or_else(|err| {
error!("Error initializing Wireguard: {}", err);
panic!()
}),
} }
} }
pub async fn quick_up(&self) { pub async fn quick_up(&self) {
let result = os::exec_sh(format!("wg-quick up {}", &self.name)) os::exec_sh(&format!("wg-quick up {}", &self.name))
.await .await
.expect("Error"); .unwrap_or_else(|err| {
result.log(); error!("Error quick_up: {}", err);
panic!()
})
.log();
} }
pub async fn quick_down(&self) { pub async fn quick_down(&self) {
let result = os::exec_sh(format!("wg-quick down {}", &self.name)) os::exec_sh(&format!("wg-quick down {}", &self.name))
.await .await
.expect("Error"); .unwrap_or_else(|err| {
result.log(); error!("Error quick_down: {}", err);
panic!()
})
.log();
} }
pub async fn sync_config(&self) { pub async fn sync_config(&self) {
let result = os::exec_sh(format!( os::exec_sh(&format!(
"wg syncconf {} <(wg-quick strip {})", "wg syncconf {} <(wg-quick strip {})",
self.name, self.name self.name, self.name
)) ))
.await .await
.expect("Error syncing"); .unwrap_or_else(|err| {
result.log(); error!("Error syncing: {}", err);
panic!()
})
.log();
} }
pub async fn start(&mut self) { pub async fn start(&mut self) {
@ -64,12 +79,18 @@ impl WireGuard {
} }
pub async fn create_client(&mut self, name: String) -> Client { pub async fn create_client(&mut self, name: String) -> Client {
let private_key = os::exec_sh("wg genkey").await.expect("error genkey").stdout; let private_key = os::exec_sh(&"wg genkey")
.await
.expect("error genkey")
.stdout;
let pub_cmd = format!("echo {} | wg pubkey", private_key); let pub_cmd = format!("echo {} | wg pubkey", private_key);
let public_key = os::exec_sh(pub_cmd).await.expect("error pubkey").stdout; let public_key = os::exec_sh(&pub_cmd).await.expect("error pubkey").stdout;
let pre_shared_key = os::exec_sh("wg genpsk").await.expect("error genpsk").stdout; let pre_shared_key = os::exec_sh(&"wg genpsk")
.await
.expect("error genpsk")
.stdout;
let mut memento = self.memento_accessor.get(); let mut memento = self.memento_accessor.get();
@ -122,7 +143,7 @@ impl WireGuard {
} }
pub async fn get_clients(&self) -> Vec<WebClient> { pub async fn get_clients(&self) -> Vec<WebClient> {
let res = os::exec_sh("wg show wg0 dump").await.unwrap(); let res = os::exec_sh(&"wg show wg0 dump").await.unwrap();
let lines: Vec<Vec<String>> = res let lines: Vec<Vec<String>> = res
.stdout .stdout

Loading…
Cancel
Save