Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stdlib/os: add isAdmin #17012

Merged
merged 9 commits into from
Mar 7, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ provided by the operating system.
arguments passed to it, so `initOptParser` has been changed to raise
`ValueError` when the real command line is not available. `parseopt` was
previously excluded from `prelude` for JS, as it could not be imported.
- Added `os.isAdmin` to tell whether the caller's process is a member of the
rominf marked this conversation as resolved.
Show resolved Hide resolved
Administrators local group (on Windows) or a root (on POSIX).

## Language changes

Expand Down
30 changes: 30 additions & 0 deletions lib/pure/os.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1648,6 +1648,36 @@ proc setFilePermissions*(filename: string, permissions: set[FilePermission],
var res2 = setFileAttributesA(filename, res)
if res2 == - 1'i32: raiseOSError(osLastError(), $(filename, permissions))

proc isAdmin*: bool {.noWeirdTarget.} =
## Returns whether the caller's process is a member of the Administrators local
## group (on Windows) or a root (on POSIX), via `geteuid() == 0`.
when defined(windows):
# Rewrite of the example from Microsoft Docs:
# https://docs.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-checktokenmembership#examples
# and corresponding PostgreSQL function:
# https://doxygen.postgresql.org/win32security_8c.html#ae6b61e106fa5d6c5d077a9d14ee80569
var ntAuthority = SID_IDENTIFIER_AUTHORITY(Value: SECURITY_NT_AUTHORITY)
var administratorsGroup: PSID
if not isSuccess(allocateAndInitializeSid(addr ntAuthority,
BYTE(2),
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
addr administratorsGroup)):
raiseOSError(osLastError(), "could not get SID for Administrators group")

defer:
if freeSid(administratorsGroup) != nil:
raiseOSError(osLastError(), "failed to free SID for Administrators group")

var b: WINBOOL
if not isSuccess(checkTokenMembership(0, administratorsGroup, addr b)):
raiseOSError(osLastError(), "could not check access token membership")
rominf marked this conversation as resolved.
Show resolved Hide resolved

return isSuccess(b)
else:
return geteuid() == 0

proc createSymlink*(src, dest: string) {.noWeirdTarget.} =
## Create a symbolic link at `dest` which points to the item specified
## by `src`. On most operating systems, will fail if a link already exists.
Expand Down
40 changes: 40 additions & 0 deletions lib/windows/winlean.nim
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ when useWinUnicode:
else:
type WinChar* = char

# See https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types
type
Handle* = int
LONG* = int32
Expand All @@ -33,13 +34,15 @@ type
WINBOOL* = int32
## `WINBOOL` uses opposite convention as posix, !=0 meaning success.
# xxx this should be distinct int32, distinct would make code less error prone
PBOOL* = ptr WINBOOL
rominf marked this conversation as resolved.
Show resolved Hide resolved
DWORD* = int32
PDWORD* = ptr DWORD
LPINT* = ptr int32
ULONG_PTR* = uint
PULONG_PTR* = ptr uint
HDC* = Handle
HGLRC* = Handle
BYTE* = cuchar
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok for now, but we should address nim-lang/RFCs#344 before next release and move it to wintypes


SECURITY_ATTRIBUTES* {.final, pure.} = object
nLength*: int32
Expand Down Expand Up @@ -136,6 +139,7 @@ const

HANDLE_FLAG_INHERIT* = 0x00000001'i32

proc isSuccess*(a: WINBOOL): bool {.inline.} = a != 0
rominf marked this conversation as resolved.
Show resolved Hide resolved
proc getVersionExW*(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "GetVersionExW", sideEffect.}
proc getVersionExA*(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {.
Expand Down Expand Up @@ -1129,5 +1133,41 @@ proc setFileTime*(hFile: Handle, lpCreationTime: LPFILETIME,
lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL
{.stdcall, dynlib: "kernel32", importc: "SetFileTime".}

type
SID_IDENTIFIER_AUTHORITY* {.importc, header: "windows.h".} = object
Value*: array[6, BYTE]
rominf marked this conversation as resolved.
Show resolved Hide resolved
PSID_IDENTIFIER_AUTHORITY* {.importc, header: "windows.h".} = ptr SID_IDENTIFIER_AUTHORITY
rominf marked this conversation as resolved.
Show resolved Hide resolved
SID* {.importc, header: "windows.h".} = object
rominf marked this conversation as resolved.
Show resolved Hide resolved
Revision: BYTE
rominf marked this conversation as resolved.
Show resolved Hide resolved
SubAuthorityCount: BYTE
IdentifierAuthority: SID_IDENTIFIER_AUTHORITY
SubAuthority: ptr ptr DWORD
PSID* {.importc, header: "windows.h".} = ptr SID
rominf marked this conversation as resolved.
Show resolved Hide resolved

const
# https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-components
# https://github.com/mirror/mingw-w64/blob/84c950bdab7c999ace49fe8383856be77f88c4a8/mingw-w64-headers/include/winnt.h#L2994
SECURITY_NT_AUTHORITY* = [BYTE(0), BYTE(0), BYTE(0), BYTE(0), BYTE(0), BYTE(5)]
SECURITY_BUILTIN_DOMAIN_RID* = 32
DOMAIN_ALIAS_RID_ADMINS* = 544

proc allocateAndInitializeSid*(pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY,
nSubAuthorityCount: BYTE,
nSubAuthority0: DWORD,
nSubAuthority1: DWORD,
nSubAuthority2: DWORD,
nSubAuthority3: DWORD,
nSubAuthority4: DWORD,
nSubAuthority5: DWORD,
nSubAuthority6: DWORD,
nSubAuthority7: DWORD,
pSid: ptr PSID): WINBOOL
{.stdcall, dynlib: "Advapi32", importc: "AllocateAndInitializeSid".}
proc checkTokenMembership*(tokenHandle: Handle, sidToCheck: PSID,
isMember: PBOOL): WINBOOL
{.stdcall, dynlib: "Advapi32", importc: "CheckTokenMembership".}
proc freeSid*(pSid: PSID): PSID
{.stdcall, dynlib: "Advapi32", importc: "FreeSid".}

when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}
4 changes: 4 additions & 0 deletions tests/stdlib/tos.nim
Original file line number Diff line number Diff line change
Expand Up @@ -651,3 +651,7 @@ block: # normalizeExe
doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
when defined(windows):
doAssert "foo".dup(normalizeExe) == "foo"

block: # isAdmin
let isAzure = defined(windows) and existsEnv("TF_BUILD") # xxx factor with testament.specs.isAzure
if isAzure: doAssert isAdmin()
rominf marked this conversation as resolved.
Show resolved Hide resolved