Files
Reims-Go/internal/host/elevate.go
T

78 lines
2.6 KiB
Go

package host
import (
"errors"
"fmt"
"strings"
"unicode/utf8"
)
// The closed set of elevated actions a plugin may ask the host to run. The
// host runs a fixed command for each; plugins never supply command lines.
const (
ElevateHyperVEnable = "hyperv.enable"
ElevateHyperVAddAdminGroup = "hyperv.addAdminGroup"
ElevateSandboxEnable = "sandbox.enable"
)
// ElevationActionSpec describes one whitelisted elevated action and what the
// person has to do afterwards. The host never restarts Windows itself.
type ElevationActionSpec struct {
Action string
NeedsReboot bool
NeedsLogoff bool
}
// ElevationResult is what an elevated action reports back.
type ElevationResult struct {
OK bool `json:"ok"`
Action string `json:"action"`
ExitCode int `json:"exit_code,omitempty"`
RebootRequired bool `json:"reboot_required,omitempty"`
LogoffRequired bool `json:"logoff_required,omitempty"`
Error string `json:"error,omitempty"`
}
var elevationActions = map[string]ElevationActionSpec{
ElevateHyperVEnable: {Action: ElevateHyperVEnable, NeedsReboot: true},
ElevateHyperVAddAdminGroup: {Action: ElevateHyperVAddAdminGroup, NeedsLogoff: true},
ElevateSandboxEnable: {Action: ElevateSandboxEnable, NeedsReboot: true},
}
// LookupElevationAction returns the spec of a whitelisted action.
func LookupElevationAction(action string) (ElevationActionSpec, bool) {
spec, ok := elevationActions[action]
return spec, ok
}
// maxElevationUserLen bounds the account name passed to the group command.
const maxElevationUserLen = 128
// ValidateElevationTargetUser rejects account names that could be read as
// command-line switches or carry shell metacharacters.
func ValidateElevationTargetUser(user string) error {
user = strings.TrimSpace(user)
if user == "" {
return errors.New("the account name is empty")
}
if utf8.RuneCountInString(user) > maxElevationUserLen {
return errors.New("the account name is too long")
}
if strings.HasPrefix(user, "-") || strings.HasPrefix(user, "/") {
return errors.New("the account name must not start with a switch character")
}
for _, r := range user {
if r < 0x20 || r == 0x7f || strings.ContainsRune(";&|<>^\"'`%$()!", r) {
return fmt.Errorf("the account name contains the character %q", r)
}
}
return nil
}
// isNetAlreadyMemberOutput reports whether `net localgroup /add` failed only
// because the account already belongs to the group (system error 1378, which
// every Windows display language prints with the same number).
func isNetAlreadyMemberOutput(output string) bool {
return strings.Contains(output, "1378")
}