0
0
mirror of https://github.com/vx3r/wg-gen-web.git synced 2024-11-04 17:31:17 +00:00
wg-gen-web/repository/repository.go

413 lines
8.5 KiB
Go
Raw Normal View History

2020-01-30 06:45:49 +00:00
package repository
import (
"encoding/json"
"errors"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
2020-02-03 07:19:24 +00:00
"github.com/skip2/go-qrcode"
2020-01-30 06:45:49 +00:00
"gitlab.127-0-0-1.fr/vx3r/wg-gen-web/model"
"gitlab.127-0-0-1.fr/vx3r/wg-gen-web/util"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
2020-02-03 07:19:24 +00:00
"gopkg.in/gomail.v2"
2020-01-30 06:45:49 +00:00
"io/ioutil"
"os"
"path/filepath"
"sort"
2020-02-03 07:19:24 +00:00
"strconv"
2020-01-30 06:45:49 +00:00
"strings"
"time"
)
2020-01-30 07:21:45 +00:00
// CreateClient client with all necessary data
2020-01-30 06:45:49 +00:00
func CreateClient(client *model.Client) (*model.Client, error) {
u := uuid.NewV4()
client.Id = u.String()
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
return nil, err
}
client.PrivateKey = key.String()
client.PublicKey = key.PublicKey().String()
// find available IP address from selected networks
clients, err := ReadClients()
if err != nil {
return nil, err
}
reserverIps := make([]string, 0)
for _, client := range clients {
ips := strings.Split(client.Address, ",")
for i := range ips {
2020-01-30 07:12:26 +00:00
if util.IsIPv6(ips[i]) {
ips[i] = strings.ReplaceAll(strings.TrimSpace(ips[i]), "/128", "")
2020-01-30 06:45:49 +00:00
} else {
2020-01-30 07:12:26 +00:00
ips[i] = strings.ReplaceAll(strings.TrimSpace(ips[i]), "/32", "")
2020-01-30 06:45:49 +00:00
}
}
reserverIps = append(reserverIps, ips...)
}
networks := strings.Split(client.Address, ",")
for i := range networks {
networks[i] = strings.TrimSpace(networks[i])
}
ips := make([]string, 0)
for _, network := range networks {
ip, err := util.GetAvailableIp(network, reserverIps)
if err != nil {
return nil, err
}
2020-01-30 07:12:26 +00:00
if util.IsIPv6(ip) {
2020-01-30 06:45:49 +00:00
ip = ip + "/128"
} else {
ip = ip + "/32"
}
ips = append(ips, ip)
}
client.Address = strings.Join(ips, ",")
2020-01-30 07:12:26 +00:00
2020-01-30 06:45:49 +00:00
client.Created = time.Now().UTC()
client.Updated = client.Created
err = serialize(client.Id, client)
if err != nil {
return nil, err
}
v, err := deserialize(client.Id)
if err != nil {
return nil, err
}
client = v.(*model.Client)
return client, nil
}
2020-01-30 07:21:45 +00:00
// ReadClient client by id
2020-01-30 06:45:49 +00:00
func ReadClient(id string) (*model.Client, error) {
v, err := deserialize(id)
if err != nil {
return nil, err
}
client := v.(*model.Client)
return client, nil
}
2020-01-30 07:21:45 +00:00
// ReadClientConfig in wg format
2020-01-30 06:45:49 +00:00
func ReadClientConfig(id string) ([]byte, error) {
client, err := ReadClient(id)
if err != nil {
return nil, err
}
server, err := ReadServer()
if err != nil {
return nil, err
}
configDataWg, err := util.DumpClient(client, server)
if err != nil {
return nil, err
}
return configDataWg.Bytes(), nil
}
2020-01-30 07:21:45 +00:00
// UpdateClient preserve keys
2020-01-30 06:45:49 +00:00
func UpdateClient(Id string, client *model.Client) (*model.Client, error) {
v, err := deserialize(Id)
if err != nil {
return nil, err
}
current := v.(*model.Client)
if current.Id != client.Id {
return nil, errors.New("records Id mismatch")
}
// keep keys
client.PrivateKey = current.PrivateKey
client.PublicKey = current.PublicKey
client.Updated = time.Now().UTC()
err = serialize(client.Id, client)
if err != nil {
return nil, err
}
v, err = deserialize(Id)
if err != nil {
return nil, err
}
client = v.(*model.Client)
return client, nil
}
2020-01-30 07:21:45 +00:00
// DeleteClient from disk
2020-01-30 06:45:49 +00:00
func DeleteClient(id string) error {
path := filepath.Join(os.Getenv("WG_CONF_DIR"), id)
err := os.Remove(path)
if err != nil {
return err
}
// data modified, dump new config
return generateWgConfig()
}
2020-02-03 07:19:24 +00:00
// SendEmail to client
func EmailClient(id string) error {
client, err := ReadClient(id)
if err != nil {
return err
}
configData, err := ReadClientConfig(id)
if err != nil {
return err
}
// conf as .conf file
tmpfileCfg, err := ioutil.TempFile("", "wireguard-vpn-*.conf")
if err != nil {
return err
}
if _, err := tmpfileCfg.Write(configData); err != nil {
return err
}
if err := tmpfileCfg.Close(); err != nil {
return err
}
defer os.Remove(tmpfileCfg.Name()) // clean up
// conf as png image
png, err := qrcode.Encode(string(configData), qrcode.Medium, 280)
if err != nil {
return err
}
tmpfilePng, err := ioutil.TempFile("", "qrcode-*.png")
if err != nil {
return err
}
if _, err := tmpfilePng.Write(png); err != nil {
return err
}
if err := tmpfilePng.Close(); err != nil {
return err
}
defer os.Remove(tmpfilePng.Name()) // clean up
// get email body
emailBody, err := util.DumpEmail(client, filepath.Base(tmpfilePng.Name()))
if err != nil {
return err
}
// port to int
port, err := strconv.Atoi(os.Getenv("SMTP_PORT"))
if err != nil {
return err
}
d := gomail.NewDialer(os.Getenv("SMTP_HOST"), port, os.Getenv("SMTP_USERNAME"), os.Getenv("SMTP_PASSWORD"))
s, err := d.Dial()
if err != nil {
return err
}
m := gomail.NewMessage()
m.SetHeader("From", os.Getenv("SMTP_FROM"))
m.SetAddressHeader("To", client.Email, client.Name)
m.SetHeader("Subject", "WireGuard VPN Configuration")
m.SetBody("text/html", emailBody.String())
m.Attach(tmpfileCfg.Name())
m.Embed(tmpfilePng.Name())
err = gomail.Send(s, m)
if err != nil {
return err
}
return nil
}
2020-01-30 07:21:45 +00:00
// ReadClients all clients
2020-01-30 06:45:49 +00:00
func ReadClients() ([]*model.Client, error) {
clients := make([]*model.Client, 0)
files, err := ioutil.ReadDir(filepath.Join(os.Getenv("WG_CONF_DIR")))
if err != nil {
return nil, err
}
for _, f := range files {
// clients file name is an uuid
_, err := uuid.FromString(f.Name())
if err == nil {
c, err := deserialize(f.Name())
if err != nil {
log.WithFields(log.Fields{
"err": err,
"path": f.Name(),
}).Error("failed to deserialize client")
} else {
clients = append(clients, c.(*model.Client))
}
}
}
sort.Slice(clients, func(i, j int) bool {
return clients[i].Created.After(clients[j].Created)
})
return clients, nil
}
2020-01-30 07:21:45 +00:00
// ReadServer object, create default one
2020-01-30 06:45:49 +00:00
func ReadServer() (*model.Server, error) {
if !util.FileExists(filepath.Join(os.Getenv("WG_CONF_DIR"), "server.json")) {
server := &model.Server{}
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
return nil, err
}
server.PrivateKey = key.String()
server.PublicKey = key.PublicKey().String()
presharedKey, err := wgtypes.GenerateKey()
if err != nil {
return nil, err
}
server.PresharedKey = presharedKey.String()
server.Name = "Created with default values"
server.Endpoint = "wireguard.example.com:123"
server.ListenPort = 51820
server.Address = "fd9f:6666::10:6:6:1/112, 10.6.6.1/24"
server.Dns = "fd9f::10:0:0:2, 10.0.0.2"
server.PersistentKeepalive = 16
server.Created = time.Now().UTC()
server.Updated = server.Created
err = serialize("server.json", server)
if err != nil {
return nil, err
}
}
c, err := deserialize("server.json")
if err != nil {
return nil, err
}
return c.(*model.Server), nil
}
2020-01-30 07:21:45 +00:00
// UpdateServer keep private values from existing one
2020-01-30 06:45:49 +00:00
func UpdateServer(server *model.Server) (*model.Server, error) {
current, err := deserialize("server.json")
if err != nil {
return nil, err
}
server.PrivateKey = current.(*model.Server).PrivateKey
server.PublicKey = current.(*model.Server).PublicKey
server.PresharedKey = current.(*model.Server).PresharedKey
server.Updated = time.Now().UTC()
err = serialize("server.json", server)
if err != nil {
return nil, err
}
v, err := deserialize("server.json")
if err != nil {
return nil, err
}
server = v.(*model.Server)
return server, nil
}
2020-01-30 07:12:26 +00:00
2020-01-30 07:21:45 +00:00
// Write object to disk
2020-01-30 06:45:49 +00:00
func serialize(id string, c interface{}) error {
2020-02-01 07:08:37 +00:00
b, err := json.MarshalIndent(c, "", " ")
2020-01-30 06:45:49 +00:00
if err != nil {
return err
}
err = util.WriteFile(filepath.Join(os.Getenv("WG_CONF_DIR"), id), b)
if err != nil {
return err
}
// data modified, dump new config
return generateWgConfig()
}
2020-01-30 07:12:26 +00:00
2020-01-30 07:21:45 +00:00
// Read client from disc
2020-01-30 06:45:49 +00:00
func deserializeClient(data []byte) (*model.Client, error) {
var c *model.Client
err := json.Unmarshal(data, &c)
if err != nil {
return nil, err
}
return c, nil
}
2020-01-30 07:12:26 +00:00
2020-01-30 07:21:45 +00:00
// Read server from disc
2020-01-30 06:45:49 +00:00
func deserializeServer(data []byte) (*model.Server, error) {
var c *model.Server
err := json.Unmarshal(data, &c)
if err != nil {
return nil, err
}
return c, nil
}
func deserialize(id string) (interface{}, error) {
path := filepath.Join(os.Getenv("WG_CONF_DIR"), id)
b, err := util.ReadFile(path)
if err != nil {
return nil, err
}
if id == "server.json" {
return deserializeServer(b)
}
return deserializeClient(b)
}
2020-01-30 07:12:26 +00:00
2020-01-30 07:21:45 +00:00
// Generate Wireguard interface configuration
2020-01-30 06:45:49 +00:00
func generateWgConfig() error {
clients, err := ReadClients()
if err != nil {
return err
}
server, err := ReadServer()
if err != nil {
return err
}
configDataWg, err := util.DumpServerWg(clients, server)
if err != nil {
return err
}
err = util.WriteFile(filepath.Join(os.Getenv("WG_CONF_DIR"), os.Getenv("WG_INTERFACE_NAME")), configDataWg.Bytes())
if err != nil {
return err
}
return nil
2020-01-30 07:12:26 +00:00
}