Skip to content

Commit

Permalink
feat: add elevate check
Browse files Browse the repository at this point in the history
  • Loading branch information
wencaiwulue committed Feb 18, 2024
1 parent 5142b61 commit 93e86c4
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
5 changes: 5 additions & 0 deletions cmd/sshvpn/cmds/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/wencaiwulue/tlstunnel/pkg/client"
"github.com/wencaiwulue/tlstunnel/pkg/config"
pkgutil "github.com/wencaiwulue/tlstunnel/pkg/util"
)

func CmdClient() *cobra.Command {
Expand All @@ -25,6 +26,10 @@ func CmdClient() *cobra.Command {
Short: "client to connect server",
Long: `client to connect server`,
PreRun: func(cmd *cobra.Command, args []string) {
if !pkgutil.IsAdmin() {
pkgutil.RunWithElevated()
os.Exit(0)
}
if util.IsWindows() {
driver.InstallWireGuardTunDriver()
}
Expand Down
36 changes: 36 additions & 0 deletions pkg/util/elevatecheck_others.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//go:build !windows

package util

import (
"os"
"os/exec"
"os/signal"
"syscall"

log "github.com/sirupsen/logrus"
)

func RunWithElevated() {
cmd := exec.Command("sudo", append([]string{"--preserve-env"}, os.Args...)...)
log.Debug(cmd.Args)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Env = os.Environ()
// while send single CTRL+C, command will quit immediately, but output will cut off and print util quit final
// so, mute single CTRL+C, let inner command handle single only
go func() {
signals := make(chan os.Signal)
signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGSTOP)
<-signals
}()
err := cmd.Run()
if err != nil {
log.Warn(err)
}
}

func IsAdmin() bool {
return os.Getuid() == 0
}
42 changes: 42 additions & 0 deletions pkg/util/elevatecheck_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//go:build windows

package util

import (
"os"
"strings"
"syscall"

"github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
)

// ref https://stackoverflow.com/questions/31558066/how-to-ask-for-administer-privileges-on-windows-with-go
func RunWithElevated() {
verb := "runas"
exe, _ := os.Executable()
cwd, _ := os.Getwd()
args := strings.Join(os.Args[1:], " ")

verbPtr, _ := windows.UTF16PtrFromString(verb)
exePtr, _ := syscall.UTF16PtrFromString(exe)
cwdPtr, _ := syscall.UTF16PtrFromString(cwd)
argPtr, _ := syscall.UTF16PtrFromString(args)

var showCmd int32 = 1 //SW_NORMAL

err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd)
if err != nil {
logrus.Warn(err)
}
}

// fmt.Printf("admin %v\n", elevated)
// return elevated
func IsAdmin() bool {
_, err := os.Open("\\\\.\\PHYSICALDRIVE0")
if err != nil {
return false
}
return true
}

0 comments on commit 93e86c4

Please sign in to comment.