txn2/kubefwd

View on GitHub
pkg/utils/root_windows.go

Summary

Maintainability
A
0 mins
Test Coverage
// +build windows

/*
Copyright 2018 Craig Johnston <cjimti@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils

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

// CheckRoot determines if we have administrative privileges.
// Ref: https://coolaj86.com/articles/golang-and-windows-and-admins-oh-my/
func CheckRoot() (bool, 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.
    // See 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 false, errors.Errorf("sid error: %s", err)
    }

    // This appears to cast a null pointer so I'm not sure why this
    // works, but this guy says it does and it Works for Me™:
    // https://github.com/golang/go/issues/28804#issuecomment-438838144
    token := windows.Token(0)

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

    return member, nil
}