[Win32utils-devel] Checking for elevated privileges on Windows XP

Daniel Berger djberg96 at gmail.com
Fri Jan 4 17:12:28 UTC 2013


Hi,

I was trying to come up with an implementation of the
elevated_security? method for Windows XP. I saw a version posted on
the doc page for the CheckTokenMembership function.

http://msdn.microsoft.com/en-us/library/aa376389%28VS.85%29.aspx

However, I can't get it to work. One line in particular confuses me:

SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;

That doesn't look like legal struct assignment to me, so I'm not sure
what it does. Anyway, I've pasted what I tried below. Suggestions
appreciated.

Regards,

Dan

# admin_test.rb
require 'ffi'

class Windows
  extend FFI::Library

  ffi_lib :advapi32

  SECURITY_NT_AUTHORITY = 5
  SECURITY_BUILTIN_DOMAIN_RID = 32
  DOMAIN_ALIAS_RID_ADMINS = 544

  class SID_IDENTIFIER_AUTHORITY < FFI::Struct
    layout(:Value, [:char, 6])
  end

  attach_function :CheckTokenMembership, [:ulong, :pointer, :pointer], :bool
  attach_function :AllocateAndInitializeSid,
    [SID_IDENTIFIER_AUTHORITY, :int, :ulong, :ulong, :ulong, :ulong,
:ulong, :ulong, :ulong, :ulong, :pointer],
    :bool

  def self.admin?
    sid     = FFI::MemoryPointer.new(:uchar, 1024)
    nt_auth = SID_IDENTIFIER_AUTHORITY.new

    nt_auth[:Value][0] = SECURITY_NT_AUTHORITY

    bool = AllocateAndInitializeSid(
      nt_auth,
      2,
      SECURITY_BUILTIN_DOMAIN_RID,
      DOMAIN_ALIAS_RID_ADMINS,
      0, 0, 0, 0, 0, 0,
      sid
    )

    unless bool
      raise SystemCallError.new("AllocateAndInitializeSid", FFI.errno)
    end

    pbool = FFI::MemoryPointer.new(:bool)

    unless CheckTokenMembership(0, sid, pbool)
      raise SystemCallError.new("CheckTokenMembership", FFI.errno)
    end

    pbool.read_int != 0
  end
end

p Windows.admin?


More information about the win32utils-devel mailing list