Skip to content

Commit

Permalink
Fix permissions checks on windows
Browse files Browse the repository at this point in the history
Signed-off-by: Brad Davidson <[email protected]>
  • Loading branch information
brandond committed Feb 6, 2025
1 parent 267a2ec commit 41f0c6a
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 2 deletions.
6 changes: 4 additions & 2 deletions pkg/cli/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ func run(app *cli.Context, cfg *cmds.Server, leaderControllers server.CustomCont
return err
}

if !cfg.DisableAgent && os.Getuid() != 0 && !cfg.Rootless {
return fmt.Errorf("server must run as root, or with --rootless and/or --disable-agent")
if !cfg.DisableAgent && !cfg.Rootless {
if err := checkPermissions(); err != nil {
return err
}
}

if cfg.Rootless {
Expand Down
18 changes: 18 additions & 0 deletions pkg/cli/server/server_others.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//go:build !windows
// +build !windows

package server

import (
"fmt"
"os"
)

// checkPermissions checks to see if the process is running as root
// Ref: https://github.com/kubernetes/kubernetes/pull/96616
func checkPermissions() error {
if os.Getuid() != 0 {
return fmt.Errorf("server must run as root, or with --rootless and/or --disable-agent")
}
return nil
}
47 changes: 47 additions & 0 deletions pkg/cli/server/server_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//go:build windows
// +build windows

package server

import (
"fmt"

"github.com/pkg/errors"
"golang.org/x/sys/windows"
)

// checkPermissions checks to see if the process is running with correct membership.
// Ref: https://github.com/kubernetes/kubernetes/pull/96616
func checkPermissions() error {
var sid *windows.SID

// Although this looks scary, it is directly copied from the
// official windows documentation. The Go API for this is a
// direct wrap around the official C++ API.
// Ref: https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-checktokenmembership
err := windows.AllocateAndInitializeSid(
&windows.SECURITY_NT_AUTHORITY,
2,
windows.SECURITY_BUILTIN_DOMAIN_RID,
windows.DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&sid)
if err != nil {
return errors.Wrap(err, "failed to create Windows SID")
}
defer windows.FreeSid(sid)

// Ref: https://github.com/golang/go/issues/28804#issuecomment-438838144
token := windows.Token(0)

member, err := token.IsMember(sid)
if err != nil {
return errors.Wrap(err, "token membership error")
}

if !member || !token.IsElevated() {
return fmt.Errorf("server must run as member of Administrators group with elevated privilege, or with --disable-agent")
}

return nil
}

0 comments on commit 41f0c6a

Please sign in to comment.