cleanup, typos, ...

This commit is contained in:
Christoph Haas 2021-02-08 22:56:02 +01:00
parent dd47f84c3d
commit 53814dbc27
13 changed files with 69 additions and 78 deletions

View File

@ -5,6 +5,7 @@
![GitHub last commit](https://img.shields.io/github/last-commit/h44z/wg-portal)
![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/h44z/wg-portal)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/h44z/wg-portal)
[![Docker Pulls](https://img.shields.io/docker/pulls/h44z/wg-portal.svg)](https://hub.docker.com/r/h44z/wg-portal/)
A simple web base configuration portal for [WireGuard](https://wireguard.com).
The portal uses the WireGuard [wgctrl](https://github.com/WireGuard/wgctrl-go) library to manage the VPN

View File

@ -54,7 +54,7 @@
<h3>Client's global configuration</h3>
<div class="form-row">
<div class="form-group required col-md-12">
<label for="inputPublicEndpoint">Public Enpoint for Clients</label>
<label for="inputPublicEndpoint">Public Endpoint for Clients</label>
<input type="text" name="endpoint" class="form-control" id="inputPublicEndpoint" placeholder="vpn.company.com:51820" value="{{.Device.Endpoint}}">
</div>
</div>

View File

@ -1,5 +1,5 @@
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#topNavbar" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#topNavbar" aria-controls="topNavbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

View File

@ -6,11 +6,10 @@ import (
"reflect"
"runtime"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/h44z/wg-portal/internal/ldap"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/kelseyhightower/envconfig"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
@ -104,15 +103,15 @@ func NewConfig() *Config {
}
err := loadConfigFile(cfg, cfgFile)
if err != nil {
log.Warnf("unable to load config.yml file: %v, using default configuration...", err)
logrus.Warnf("unable to load config.yml file: %v, using default configuration...", err)
}
err = loadConfigEnv(cfg)
if err != nil {
log.Warnf("unable to load environment config: %v", err)
logrus.Warnf("unable to load environment config: %v", err)
}
if cfg.WG.ManageIPAddresses && runtime.GOOS != "linux" {
log.Warnf("Managing IP addresses only works on linux! Feature disabled.")
logrus.Warnf("Managing IP addresses only works on linux! Feature disabled.")
cfg.WG.ManageIPAddresses = false
}

View File

@ -11,7 +11,7 @@ import (
"time"
"github.com/go-ldap/ldap/v3"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
)
var Fields = []string{"givenName", "sn", "mail", "department", "memberOf", "sAMAccountName", "telephoneNumber",
@ -214,9 +214,9 @@ func NewUserCache(config Config, store UserCacheHolder) *UserCache {
userData: store,
}
log.Infof("Filling user cache...")
logrus.Infof("Filling user cache...")
err := uc.Update(true, true)
log.Infof("User cache filled!")
logrus.Infof("User cache filled!")
uc.LastError = err
return uc
@ -252,7 +252,7 @@ func (u UserCache) close(conn *ldap.Conn) {
// Update updates the user cache in background, minimal locking will happen
func (u *UserCache) Update(filter, withDisabledUsers bool) error {
log.Debugf("Updating ldap cache...")
logrus.Debugf("Updating ldap cache...")
client, err := u.open()
if err != nil {
u.LastError = err
@ -296,7 +296,7 @@ func (u *UserCache) Update(filter, withDisabledUsers bool) error {
}
if entry.DN != dn {
log.Errorf("LDAP inconsistent: '%s' != '%s'", entry.DN, dn)
logrus.Errorf("LDAP inconsistent: '%s' != '%s'", entry.DN, dn)
continue
}
}
@ -320,7 +320,7 @@ func (u *UserCache) Update(filter, withDisabledUsers bool) error {
u.UpdatedAt = time.Now()
u.LastError = nil
log.Debug("Ldap cache updated...")
logrus.Debug("Ldap cache updated...")
return nil
}

View File

@ -11,17 +11,14 @@ import (
"path/filepath"
"time"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
)
const SessionIdentifier = "wgPortalSession"
@ -85,8 +82,8 @@ type Server struct {
func (s *Server) Setup() error {
dir := s.getExecutableDirectory()
rDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
log.Infof("Real working directory: %s", rDir)
log.Infof("Current working directory: %s", dir)
logrus.Infof("Real working directory: %s", rDir)
logrus.Infof("Current working directory: %s", dir)
// Init rand
rand.Seed(time.Now().UnixNano())
@ -99,8 +96,8 @@ func (s *Server) Setup() error {
s.ldapUsers.Init()
s.ldapCacheUpdater = ldap.NewUserCache(s.config.LDAP, s.ldapUsers)
if s.ldapCacheUpdater.LastError != nil {
log.Warnf("LDAP error: %v", s.ldapCacheUpdater.LastError)
log.Warnf("LDAP features disabled!")
logrus.Warnf("LDAP error: %v", s.ldapCacheUpdater.LastError)
logrus.Warnf("LDAP features disabled!")
s.ldapDisabled = true
}
@ -118,7 +115,7 @@ func (s *Server) Setup() error {
return errors.New("unable to initialize user manager")
}
if err := s.RestoreWireGuardInterface(); err != nil {
return errors.New("unable to restore wirguard state")
return errors.New("unable to restore WireGuard state")
}
// Setup mail template
@ -132,14 +129,14 @@ func (s *Server) Setup() error {
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = ioutil.Discard
s.server = gin.New()
s.server.Use(ginlogrus.Logger(log.StandardLogger()), gin.Recovery())
s.server.Use(ginlogrus.Logger(logrus.StandardLogger()), gin.Recovery())
s.server.SetFuncMap(template.FuncMap{
"formatBytes": common.ByteCountSI,
"urlEncode": url.QueryEscape,
})
// Setup templates
log.Infof("Loading templates from: %s", filepath.Join(dir, "/assets/tpl/*.html"))
logrus.Infof("Loading templates from: %s", filepath.Join(dir, "/assets/tpl/*.html"))
s.server.LoadHTMLGlob(filepath.Join(dir, "/assets/tpl/*.html"))
s.server.Use(sessions.Sessions("authsession", memstore.NewStore([]byte("secret")))) // TODO: change key?
@ -152,7 +149,7 @@ func (s *Server) Setup() error {
// Setup all routes
SetupRoutes(s)
log.Infof("Setup of service completed!")
logrus.Infof("Setup of service completed!")
return nil
}
@ -163,9 +160,9 @@ func (s *Server) Run() {
for {
time.Sleep(CacheRefreshDuration)
if err := s.ldapCacheUpdater.Update(true, true); err != nil {
log.Warnf("Failed to update ldap group cache: %v", err)
logrus.Warnf("Failed to update ldap group cache: %v", err)
}
log.Debugf("Refreshed LDAP permissions!")
logrus.Debugf("Refreshed LDAP permissions!")
}
}(s)
}
@ -175,9 +172,9 @@ func (s *Server) Run() {
for {
time.Sleep(CacheRefreshDuration)
if err := s.SyncLdapAttributesWithWireGuard(); err != nil {
log.Warnf("Failed to synchronize ldap attributes: %v", err)
logrus.Warnf("Failed to synchronize ldap attributes: %v", err)
}
log.Debugf("Synced LDAP attributes!")
logrus.Debugf("Synced LDAP attributes!")
}
}(s)
}
@ -185,14 +182,14 @@ func (s *Server) Run() {
// Run web service
err := s.server.Run(s.config.Core.ListeningAddress)
if err != nil {
log.Errorf("Failed to listen and serve on %s: %v", s.config.Core.ListeningAddress, err)
logrus.Errorf("Failed to listen and serve on %s: %v", s.config.Core.ListeningAddress, err)
}
}
func (s *Server) getExecutableDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Errorf("Failed to get executable directory: %v", err)
logrus.Errorf("Failed to get executable directory: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "assets")); os.IsNotExist(err) {
@ -221,7 +218,7 @@ func (s *Server) getSessionData(c *gin.Context) SessionData {
}
session.Set(SessionIdentifier, sessionData)
if err := session.Save(); err != nil {
log.Errorf("Failed to store session: %v", err)
logrus.Errorf("Failed to store session: %v", err)
}
}
@ -232,7 +229,7 @@ func (s *Server) getFlashes(c *gin.Context) []FlashData {
session := sessions.Default(c)
flashes := session.Flashes()
if err := session.Save(); err != nil {
log.Errorf("Failed to store session after setting flash: %v", err)
logrus.Errorf("Failed to store session after setting flash: %v", err)
}
flashData := make([]FlashData, len(flashes))
@ -247,7 +244,7 @@ func (s *Server) updateSessionData(c *gin.Context, data SessionData) error {
session := sessions.Default(c)
session.Set(SessionIdentifier, data)
if err := session.Save(); err != nil {
log.Errorf("Failed to store session: %v", err)
logrus.Errorf("Failed to store session: %v", err)
return err
}
return nil
@ -257,7 +254,7 @@ func (s *Server) destroySessionData(c *gin.Context) error {
session := sessions.Default(c)
session.Delete(SessionIdentifier)
if err := session.Save(); err != nil {
log.Errorf("Failed to destroy session: %v", err)
logrus.Errorf("Failed to destroy session: %v", err)
return err
}
return nil
@ -280,7 +277,7 @@ func (s *Server) setFlashMessage(c *gin.Context, message, typ string) {
Type: typ,
})
if err := session.Save(); err != nil {
log.Errorf("Failed to store session after setting flash: %v", err)
logrus.Errorf("Failed to store session after setting flash: %v", err)
}
}

View File

@ -4,9 +4,8 @@ import (
"net/http"
"strings"
log "github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
func (s *Server) GetLogin(c *gin.Context) {
@ -108,7 +107,7 @@ func (s *Server) PostLogin(c *gin.Context) {
CreatedBy: sessionData.Email,
UpdatedBy: sessionData.Email,
})
log.Errorf("Failed to automatically create vpn peer for %s: %v", sessionData.Email, err)
logrus.Errorf("Failed to automatically create vpn peer for %s: %v", sessionData.Email, err)
}
}

View File

@ -79,7 +79,7 @@ func (s *Server) PostAdminEditInterface(c *gin.Context) {
err = s.WriteWireGuardConfigFile()
if err != nil {
_ = s.updateFormInSession(c, formDevice)
s.setFlashMessage(c, "Failed to update wireguard config-file: "+err.Error(), "danger")
s.setFlashMessage(c, "Failed to update WireGuard config-file: "+err.Error(), "danger")
c.Redirect(http.StatusSeeOther, "/admin/device/edit?formerr=update")
return
}
@ -134,7 +134,7 @@ func (s *Server) GetApplyGlobalConfig(c *gin.Context) {
}
}
s.setFlashMessage(c, "Allowed ip's updated for all clients.", "success")
s.setFlashMessage(c, "Allowed IP's updated for all clients.", "success")
c.Redirect(http.StatusSeeOther, "/admin/device/edit")
return
}

View File

@ -11,7 +11,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
"github.com/tatsushid/go-fastping"
)
@ -204,7 +204,7 @@ func (s *Server) PostAdminCreateLdapPeers(c *gin.Context) {
}
}
log.Infof("creating %d ldap peers", len(emails))
logrus.Infof("creating %d ldap peers", len(emails))
for i := range emails {
if err := s.CreateUserByEmail(emails[i], formData.Identifier, false); err != nil {

View File

@ -9,7 +9,6 @@ import (
"time"
"github.com/h44z/wg-portal/internal/common"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)

View File

@ -4,7 +4,7 @@ import (
"time"
"github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
)
// SyncLdapAttributesWithWireGuard starts to synchronize the "disabled" attribute from ldap.
@ -26,7 +26,7 @@ func (s *Server) SyncLdapAttributesWithWireGuard() error {
now := time.Now()
user.DeactivatedAt = &now
if err := s.UpdateUser(user, now); err != nil {
log.Errorf("Failed to disable user %s: %v", user.Email, err)
logrus.Errorf("Failed to disable user %s: %v", user.Email, err)
}
}
}

View File

@ -16,15 +16,11 @@ import (
"time"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"gorm.io/driver/sqlite"
@ -62,8 +58,8 @@ var ipList validator.Func = func(fl validator.FieldLevel) bool {
func init() {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("cidrlist", cidrList)
v.RegisterValidation("iplist", ipList)
_ = v.RegisterValidation("cidrlist", cidrList)
_ = v.RegisterValidation("iplist", ipList)
}
}
@ -153,7 +149,7 @@ func (u User) GetPeerConfig() wgtypes.PeerConfig {
func (u User) GetQRCode() ([]byte, error) {
png, err := qrcode.Encode(u.Config, qrcode.Medium, 250)
if err != nil {
log.WithFields(log.Fields{
logrus.WithFields(logrus.Fields{
"err": err,
}).Error("failed to create qrcode")
return nil, err
@ -289,19 +285,19 @@ func NewUserManager(dbPath string, wg *wireguard.Manager, ldapUsers *ldap.Synchr
var err error
if _, err = os.Stat(filepath.Dir(dbPath)); os.IsNotExist(err) {
if err = os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil {
log.Errorf("failed to create database directory (%s): %v", filepath.Dir(dbPath), err)
logrus.Errorf("failed to create database directory (%s): %v", filepath.Dir(dbPath), err)
return nil
}
}
um.db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
log.Errorf("failed to open sqlite database (%s): %v", dbPath, err)
logrus.Errorf("failed to open sqlite database (%s): %v", dbPath, err)
return nil
}
err = um.db.AutoMigrate(&User{}, &Device{})
if err != nil {
log.Errorf("failed to migrate sqlite database: %v", err)
logrus.Errorf("failed to migrate sqlite database: %v", err)
return nil
}
@ -311,23 +307,23 @@ func NewUserManager(dbPath string, wg *wireguard.Manager, ldapUsers *ldap.Synchr
func (u *UserManager) InitFromCurrentInterface() error {
peers, err := u.wg.GetPeerList()
if err != nil {
log.Errorf("failed to init user-manager from peers: %v", err)
logrus.Errorf("failed to init user-manager from peers: %v", err)
return err
}
device, err := u.wg.GetDeviceInfo()
if err != nil {
log.Errorf("failed to init user-manager from device: %v", err)
logrus.Errorf("failed to init user-manager from device: %v", err)
return err
}
var ipAddresses []string
var mtu int
if u.wg.Cfg.ManageIPAddresses {
if ipAddresses, err = u.wg.GetIPAddress(); err != nil {
log.Errorf("failed to init user-manager from device: %v", err)
logrus.Errorf("failed to init user-manager from device: %v", err)
return err
}
if mtu, err = u.wg.GetMTU(); err != nil {
log.Errorf("failed to init user-manager from device: %v", err)
logrus.Errorf("failed to init user-manager from device: %v", err)
return err
}
}
@ -370,7 +366,7 @@ func (u *UserManager) validateOrCreateUserForPeer(peer wgtypes.Peer) error {
res := u.db.Create(&user)
if res.Error != nil {
log.Errorf("failed to create autodetected peer: %v", res.Error)
logrus.Errorf("failed to create autodetected peer: %v", res.Error)
return res.Error
}
}
@ -390,14 +386,14 @@ func (u *UserManager) validateOrCreateDevice(dev wgtypes.Device, ipAddresses []s
device.Mtu = 0
device.PersistentKeepalive = 16 // Default
device.IPsStr = strings.Join(ipAddresses, ", ")
if mtu == wireguard.WireGuardDefaultMTU {
if mtu == wireguard.DefaultMTU {
mtu = 0
}
device.Mtu = mtu
res := u.db.Create(&device)
if res.Error != nil {
log.Errorf("failed to create autodetected device: %v", res.Error)
logrus.Errorf("failed to create autodetected device: %v", res.Error)
return res.Error
}
}
@ -603,7 +599,7 @@ func (u *UserManager) CreateUser(user User) error {
res := u.db.Create(&user)
if res.Error != nil {
log.Errorf("failed to create user: %v", res.Error)
logrus.Errorf("failed to create user: %v", res.Error)
return res.Error
}
@ -617,7 +613,7 @@ func (u *UserManager) UpdateUser(user User) error {
res := u.db.Save(&user)
if res.Error != nil {
log.Errorf("failed to update user: %v", res.Error)
logrus.Errorf("failed to update user: %v", res.Error)
return res.Error
}
@ -627,7 +623,7 @@ func (u *UserManager) UpdateUser(user User) error {
func (u *UserManager) DeleteUser(user User) error {
res := u.db.Delete(&user)
if res.Error != nil {
log.Errorf("failed to delete user: %v", res.Error)
logrus.Errorf("failed to delete user: %v", res.Error)
return res.Error
}
@ -642,7 +638,7 @@ func (u *UserManager) UpdateDevice(device Device) error {
res := u.db.Save(&device)
if res.Error != nil {
log.Errorf("failed to update device: %v", res.Error)
logrus.Errorf("failed to update device: %v", res.Error)
return res.Error
}

View File

@ -7,7 +7,7 @@ import (
"github.com/milosgajdos/tenus"
)
const WireGuardDefaultMTU = 1420
const DefaultMTU = 1420
func (m *Manager) GetIPAddress() ([]string, error) {
wgInterface, err := tenus.NewLinkFrom(m.Cfg.DeviceName)
@ -38,7 +38,7 @@ func (m *Manager) GetIPAddress() ([]string, error) {
ip = v.IP
mask = ip.DefaultMask()
}
if ip == nil {
if ip == nil || mask == nil {
continue // something is wrong?
}
@ -72,7 +72,7 @@ func (m *Manager) SetIPAddress(cidrs []string) error {
}
}
// Next set new IP adrresses
// Next set new IP addresses
for _, cidr := range cidrs {
wgIp, wgIpNet, err := net.ParseCIDR(cidr)
if err != nil {
@ -109,7 +109,7 @@ func (m *Manager) SetMTU(mtu int) error {
}
if mtu == 0 {
mtu = WireGuardDefaultMTU
mtu = DefaultMTU
}
if err := wgInterface.SetLinkMTU(mtu); err != nil {