Debian Codegraph @

pkg/os/windows/powershell/powershell_windows.go

raw
1 package powershell
2
3 import (
4 "bytes"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "syscall"
10
11 "github.com/crc-org/crc/v2/pkg/crc/logging"
12 )
13
14 var isAdminCmds = []string{
15 "$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())",
16 "$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",
17 }
18
19 func IsAdmin() bool {
20 cmd := strings.Join(isAdminCmds, ";")
21 stdOut, _, err := Execute(cmd)
22 if err != nil {
23 return false
24 }
25 if strings.TrimSpace(stdOut) == "False" {
26 return false
27 }
28
29 return true
30 }
31
32 func Execute(args ...string) (string, string, error) {
33 logging.Debugf("Running '%s'", strings.Join(args, " "))
34
35 powershell, err := exec.LookPath("powershell.exe")
36 if err != nil {
37 return "", "", err
38 }
39 args = append([]string{"-NoProfile", "-NonInteractive", "-ExecutionPolicy", "RemoteSigned", "-Command", "$ProgressPreference = 'SilentlyContinue';"}, args...)
40 cmd := exec.Command(powershell, args...) // #nosec G204
41 cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
42
43 var stdout bytes.Buffer
44 var stderr bytes.Buffer
45 cmd.Stdout = &stdout
46 cmd.Stderr = &stderr
47
48 err = cmd.Run()
49 if err != nil {
50 logging.Debugf("Command failed: %v", err)
51 logging.Debugf("stdout: %s", stdout.String())
52 logging.Debugf("stderr: %s", stderr.String())
53 }
54 return stdout.String(), stderr.String(), err
55 }
56
57 func ExecuteAsAdmin(reason, cmd string) (string, string, error) {
58 powershell, err := exec.LookPath("powershell.exe")
59 if err != nil {
60 return "", "", err
61 }
62 scriptContent := strings.Join(append(runAsCmds(powershell), cmd), "\n")
63
64 tempDir, err := os.MkdirTemp("", "crcScripts")
65 if err != nil {
66 return "", "", err
67 }
68 defer os.RemoveAll(tempDir)
69
70 // Write a temporary script
71 /* Add UTF-8 BOM at the beginning of the script so that Windows
72 * correctly detects the file encoding
73 */
74 filename := filepath.Join(tempDir, "runAsAdmin.ps1")
75
76 // #nosec G306
77 if err := os.WriteFile(filename, append([]byte{0xef, 0xbb, 0xbf}, []byte(scriptContent)...), 0666); err != nil {
78 return "", "", err
79 }
80
81 logging.Infof("Will run as admin: %s", reason)
82
83 return Execute(filename)
84 }
85
86 func runAsCmds(powershell string) []string {
87 return []string{
88 `$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();`,
89 `$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);`,
90 `$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;`,
91 `if (-Not ($myWindowsPrincipal.IsInRole($adminRole))) {`,
92 ` $procInfo = New-Object System.Diagnostics.ProcessStartInfo;`,
93 ` $procInfo.FileName = "` + powershell + `"`,
94 ` $procInfo.WindowStyle = [Diagnostics.ProcessWindowStyle]::Hidden`,
95 ` $procInfo.Arguments = "-ExecutionPolicy RemoteSigned & '" + $script:MyInvocation.MyCommand.Path + "'"`,
96 ` $procInfo.Verb = "runas";`,
97 ` $p = New-Object System.Diagnostics.Process`,
98 ` $p.StartInfo = $procInfo`,
99 ` $p.Start() | Out-Null`,
100 ` $p.WaitForExit()`,
101 ` if ($p.ExitCode -ne 0) {`,
102 ` throw "Unexpected failure";`,
103 ` }`,
104 ` Exit;`,
105 `}`,
106 }
107 }