Docfxit

Read in registry value

8 posts in this topic

I'm trying to read in a registry entry into $aRegKey.  AutoIt is not reading the entry.  I'd like to find out why.

#RequireAdmin
#include <file.au3>
#include "ExtMsgBox.au3"
#include "RegistryEx.au3"
#include <Array.au3>

Local $sRegKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Enum\PCI\VEN_8086&DEV_9cbA&SUBSYS_222317AA&REV_03", $aRegKey
Local $sRegKeyPath2 = "HKLM\SYSTEM\ControlSet002\Enum\PCI\VEN_8086&DEV_9cbA&SUBSYS_222317AA&REV_03", $aRegKey
Local $MyArrayVariable, $MsgBoxText, $x, $count, $subKey[30]

$aRegKey = _WinAPI_RegEnumKeyEx(Null, $sRegKeyPath)

Running in Win7

Thank you,

Docfxit

Share this post


Link to post
Share on other sites



Use AutoIt defaults funtions for registry read/write/enum.

 

Saludos

Share this post


Link to post
Share on other sites

I would like to know what is wrong with what I have.

Thanks,

Docfxit

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

AutoIt does not have a _WinAPI_RegEnumKeyEx.  It has _WinAPI_RegEnumKey.  

 

Adam

 

Edited by AdamUL

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

Even though I have been running with _WinAPI_RegEnumKeyEx for a long time, I changed it to _WinAPI_RegEnumKey.

It's still not reading anything into $aRegKey.

I added the code from the help file for _WinAPI_RegEnumKey and it's giving me more errors:

#RequireAdmin
#include <file.au3>
#include "ExtMsgBox.au3"
#include "RegistryEx.au3"
#include <Array.au3>
#include <APIRegConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIDiag.au3>
#include <WinAPIReg.au3>


Local $sRegKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Enum\PCI\VEN_8086&DEV_9cbA&SUBSYS_222317AA&REV_03", $aRegKey
Local $sRegKeyPath2 = "HKLM\SYSTEM\ControlSet002\Enum\PCI\VEN_8086&DEV_9cbA&SUBSYS_222317AA&REV_03", $aRegKey
Local $MyArrayVariable, $MsgBoxText, $x, $count, $subKey[30]

$aRegKey = _WinAPI_RegEnumKey(Null, $sRegKeyPath)
If Not @error Then
    _ArrayDisplay($aRegKey)
Else
    MsgBox(BitOR($MB_ICONERROR, $MB_SYSTEMMODAL), @extended, _WinAPI_GetErrorMessage(@extended))
EndIf

"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(69,45) : error: $HKEY_CLASSES_ROOT previously declared as a 'Const'.
Global Const $HKEY_CLASSES_ROOT = 0x80000000
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(70,47) : error: $HKEY_CURRENT_CONFIG previously declared as a 'Const'.
Global Const $HKEY_CURRENT_CONFIG = 0x80000005
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(71,45) : error: $HKEY_CURRENT_USER previously declared as a 'Const'.
Global Const $HKEY_CURRENT_USER = 0x80000001
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(72,46) : error: $HKEY_LOCAL_MACHINE previously declared as a 'Const'.
Global Const $HKEY_LOCAL_MACHINE = 0x80000002
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(73,49) : error: $HKEY_PERFORMANCE_DATA previously declared as a 'Const'.
Global Const $HKEY_PERFORMANCE_DATA = 0x80000004
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(74,52) : error: $HKEY_PERFORMANCE_NLSTEXT previously declared as a 'Const'.
Global Const $HKEY_PERFORMANCE_NLSTEXT = 0x80000060
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(75,49) : error: $HKEY_PERFORMANCE_TEXT previously declared as a 'Const'.
Global Const $HKEY_PERFORMANCE_TEXT = 0x80000050
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(76,38) : error: $HKEY_USERS previously declared as a 'Const'.
Global Const $HKEY_USERS = 0x80000003
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(84,39) : error: $KEY_WOW64_32KEY previously declared as a 'Const'.
Global Const $KEY_WOW64_32KEY = 0x0200
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(85,39) : error: $KEY_WOW64_64KEY previously declared as a 'Const'.
Global Const $KEY_WOW64_64KEY = 0x0100
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\APIRegConstants.au3"(89,188) : error: $KEY_ALL_ACCESS previously declared as a 'Const'.
Global Const $KEY_ALL_ACCESS = 0x000f003f ; BitOR($STANDARD_RIGHTS_REQUIRED, $KEY_CREATE_LINK, $KEY_CREATE_SUB_KEY, $KEY_ENUMERATE_SUB_KEYS, $KEY_NOTIFY, $KEY_QUERY_VALUE, $KEY_SET_VALUE)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\SecurityConstants.au3"(14,51) : error: $SE_BACKUP_NAME previously declared as a 'Const'.
Global Const $SE_BACKUP_NAME = "SeBackupPrivilege"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\SecurityConstants.au3"(19,77) : error: $SE_CREATE_SYMBOLIC_LINK_NAME previously declared as a 'Const'.
Global Const $SE_CREATE_SYMBOLIC_LINK_NAME = 'SeCreateSymbolicLinkPrivilege'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\SecurityConstants.au3"(21,49) : error: $SE_DEBUG_NAME previously declared as a 'Const'.
Global Const $SE_DEBUG_NAME = "SeDebugPrivilege"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\SecurityConstants.au3"(34,53) : error: $SE_RESTORE_NAME previously declared as a 'Const'.
Global Const $SE_RESTORE_NAME = "SeRestorePrivilege"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\SecurityConstants.au3"(35,55) : error: $SE_SECURITY_NAME previously declared as a 'Const'.
Global Const $SE_SECURITY_NAME = "SeSecurityPrivilege"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\SecurityConstants.au3"(41,66) : error: $SE_TAKE_OWNERSHIP_NAME previously declared as a 'Const'.
Global Const $SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(213,49) : error: _WinAPI_RegCloseKey() already defined.
Func _WinAPI_RegCloseKey($hKey, $bFlush = False)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(268,107) : error: _WinAPI_RegCreateKey() already defined.
Func _WinAPI_RegCreateKey($hKey, $sSubKey = '', $iAccess = $KEY_ALL_ACCESS, $iOptions = 0, $tSecurity = 0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(281,53) : error: _WinAPI_RegDeleteEmptyKey() already defined.
Func _WinAPI_RegDeleteEmptyKey($hKey, $sSubKey = '')
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(293,48) : error: _WinAPI_RegDeleteKey() already defined.
Func _WinAPI_RegDeleteKey($hKey, $sSubKey = '')
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(344,48) : error: _WinAPI_RegDeleteValue() already defined.
Func _WinAPI_RegDeleteValue($hKey, $sValueName)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(391,40) : error: _WinAPI_RegEnumKey() already defined.
Func _WinAPI_RegEnumKey($hKey, $iIndex)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(404,42) : error: _WinAPI_RegEnumValue() already defined.
Func _WinAPI_RegEnumValue($hKey, $iIndex)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(461,69) : error: _WinAPI_RegOpenKey() already defined.
Func _WinAPI_RegOpenKey($hKey, $sSubKey = '', $iAccess = 0x000F003F)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(573,66) : error: _WinAPI_RegQueryValue() already defined.
Func _WinAPI_RegQueryValue($hKey, $sValueName, ByRef $tValueData)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(586,46) : error: _WinAPI_RegRestoreKey() already defined.
Func _WinAPI_RegRestoreKey($hKey, $sFilePath)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Programs\AutoIt3\Include\WinAPIReg.au3"(629,75) : error: _WinAPI_RegSetValue() already defined.
Func _WinAPI_RegSetValue($hKey, $sValueName, $iType, $tValueData, $iBytes)
 

Running AutoIt ver. 3.3.14.2

Thanks,

Docfxit

Edited by Docfxit

Share this post


Link to post
Share on other sites

You are calling the function wrong.  Look at the example in the help file that I linked to in the previous post.  

 

Adam

 

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

I tried this code.  I'm still not getting the registry key.

#RequireAdmin
#include <file.au3>
#include "ExtMsgBox.au3"
#include "RegistryEx.au3"
#include <Array.au3>

$dwIndex = 0
$hKey = _WinAPI_RegOpenKey($HKEY_LOCAL_MACHINE, "ControlSet002\Enum\PCI\VEN_8086&DEV_9cbA&SUBSYS_222317AA&REV_03", $KEY_ALL_ACCESS)
While (Not @error)
    $aRegKey = _WinAPI_RegEnumKey($hKey, $dwIndex)
    $dwIndex += 1
WEnd
_WinAPI_RegCloseKey($hKey)

Does this code look better?

Why wouldn't it read the key?

I discovered this method reads one key in at a time.

Using RegistryEx the way I origionally had it reads in the registry key I supply and all subkeys into an array.

I was told to use RegistryEx by DXRW4E 

On this thread  https://www.autoitscript.com/forum/topic/167474-lists-all-subkeys-in-a-specified-registry-key/

Thanks,

Docfxit

Edited by Docfxit

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Hi Docfxit, use\try\include the PrivilegesEx, to be sure you have (Always) all the Privileges

#include-once
#RequireAdmin
Opt("MustDeclareVars",1)

;;Global $aOle32 = DllCall("ole32.dll", "long", "OleInitialize", "PTR", 0)
If Not IsDeclared("arDllCall") Then Global Static $arDllCall

#Region ;**** Token Privileges ****
Global Const $hKernel32DLL = DllOpen("Kernel32.dll")
Global Const $hAdvapi32Dll = DllOpen("AdvApi32.dll")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;                                                                    ;;
;;               NT Defined Privileges                                ;;
;;                                                                    ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Global Const $SE_CREATE_TOKEN_NAME           = "SeCreateTokenPrivilege"
Global Const $SE_ASSIGNPRIMARYTOKEN_NAME     = "SeAssignPrimaryTokenPrivilege"
Global Const $SE_LOCK_MEMORY_NAME            = "SeLockMemoryPrivilege"
Global Const $SE_INCREASE_QUOTA_NAME         = "SeIncreaseQuotaPrivilege"
Global Const $SE_UNSOLICITED_INPUT_NAME      = "SeUnsolicitedInputPrivilege"
Global Const $SE_MACHINE_ACCOUNT_NAME        = "SeMachineAccountPrivilege"
Global Const $SE_TCB_NAME                    = "SeTcbPrivilege"
Global Const $SE_SECURITY_NAME               = "SeSecurityPrivilege"
Global Const $SE_TAKE_OWNERSHIP_NAME         = "SeTakeOwnershipPrivilege"
Global Const $SE_LOAD_DRIVER_NAME            = "SeLoadDriverPrivilege"
Global Const $SE_SYSTEM_PROFILE_NAME         = "SeSystemProfilePrivilege"
Global Const $SE_SYSTEMTIME_NAME             = "SeSystemtimePrivilege"
Global Const $SE_PROF_SINGLE_PROCESS_NAME    = "SeProfileSingleProcessPrivilege"
Global Const $SE_INC_BASE_PRIORITY_NAME      = "SeIncreaseBasePriorityPrivilege"
Global Const $SE_CREATE_PAGEFILE_NAME        = "SeCreatePagefilePrivilege"
Global Const $SE_CREATE_PERMANENT_NAME       = "SeCreatePermanentPrivilege"
Global Const $SE_BACKUP_NAME                 = "SeBackupPrivilege"
Global Const $SE_RESTORE_NAME                = "SeRestorePrivilege"
Global Const $SE_SHUTDOWN_NAME               = "SeShutdownPrivilege"
Global Const $SE_DEBUG_NAME                  = "SeDebugPrivilege"
Global Const $SE_AUDIT_NAME                  = "SeAuditPrivilege"
Global Const $SE_SYSTEM_ENVIRONMENT_NAME     = "SeSystemEnvironmentPrivilege"
Global Const $SE_CHANGE_NOTIFY_NAME          = "SeChangeNotifyPrivilege"
Global Const $SE_REMOTE_SHUTDOWN_NAME        = "SeRemoteShutdownPrivilege"
Global Const $SE_UNDOCK_NAME                 = "SeUndockPrivilege"
Global Const $SE_SYNC_AGENT_NAME             = "SeSyncAgentPrivilege"
Global Const $SE_ENABLE_DELEGATION_NAME      = "SeEnableDelegationPrivilege"
Global Const $SE_MANAGE_VOLUME_NAME          = "SeManageVolumePrivilege"
Global Const $SE_IMPERSONATE_NAME            = "SeImpersonatePrivilege"
Global Const $SE_CREATE_GLOBAL_NAME          = "SeCreateGlobalPrivilege"
Global Const $SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"
Global Const $SE_RELABEL_NAME                = "SeRelabelPrivilege"
Global Const $SE_INC_WORKING_SET_NAME        = "SeIncreaseWorkingSetPrivilege"
Global Const $SE_TIME_ZONE_NAME              = "SeTimeZonePrivilege"
Global Const $SE_CREATE_SYMBOLIC_LINK_NAME   = "SeCreateSymbolicLinkPrivilege"
;Global Const $SE_ASSIGNPRIMARYTOKEN_NAME     = "SeAssignPrimaryTokenPrivilege"
;; Required to assign the primary token of a process.
;; User Right: Replace a process-level token.
;Global Const $SE_AUDIT_NAME                  = "SeAuditPrivilege"
;; Required to generate audit-log entries. Give this privilege to secure servers.
;; User Right: Generate security audits.
;Global Const $SE_BACKUP_NAME                 = "SeBackupPrivilege"
;; Required to perform backup operations. This privilege causes the system to grant all read access control to any file, regardless
;;  of the access control list (ACL) specified for the file. Any access request other than read is still evaluated with  the ACL.
;;  This privilege is required by the RegSaveKey and RegSaveKeyExfunctions.
;;  The following access rights are granted if this privilege is held:
;;     READ_CONTROL
;;     ACCESS_SYSTEM_SECURITY
;;     FILE_GENERIC_READ
;;     FILE_TRAVERSE
;; User Right: Back up files and directories.
;Global Const $SE_CHANGE_NOTIFY_NAME          = "SeChangeNotifyPrivilege"
;; Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all
;;  traversal access checks. It is enabled by default for all users.
;; User Right: Bypass traverse checking.
;Global Const $SE_CREATE_GLOBAL_NAME          = "SeCreateGlobalPrivilege"
;; Required to create named file mapping objects in the global namespace during Terminal Services sessions. This privilege
;;  is enabled by default for administrators, services, and the local system account.
;; User Right: Create global objects.
;Global Const $SE_CREATE_PAGEFILE_NAME        = "SeCreatePagefilePrivilege"
;; Required to create a paging file.
;; User Right: Create a pagefile.
;Global Const $SE_CREATE_PERMANENT_NAME       = "SeCreatePermanentPrivilege"      ;; Required to create a permanent object.
;; User Right: Create permanent shared objects.
;Global Const $SE_CREATE_SYMBOLIC_LINK_NAME   = "SeCreateSymbolicLinkPrivilege"
;; Required to create a symbolic link.
;; User Right: Create symbolic links.
;Global Const $SE_CREATE_TOKEN_NAME           = "SeCreateTokenPrivilege"
;; Required to create a primary token.
;; User Right: Create a token object.
;;  You cannot add this privilege to a user account with the "Create a token object"  policy. Additionally, you cannot
;;  add this privilege to an owned process using Windows APIs.Windows Server 2003 and Windows XP with SP1 and earlier:
;;  Windows APIs can add this privilege to an owned process.
;Global Const $SE_DEBUG_NAME                  = "SeDebugPrivilege"
;; Required to debug and adjust the memory of a process owned by another account.
;; User Right: Debug programs.
;Global Const $SE_ENABLE_DELEGATION_NAME      = "SeEnableDelegationPrivilege"
;; Required to mark user and computer accounts as trusted for delegation.
;; User Right: Enable computer and user accounts to be trusted for delegation.
;Global Const $SE_IMPERSONATE_NAME            = "SeImpersonatePrivilege"
;; Required to impersonate.
;; User Right: Impersonate a client after authentication.
;Global Const $SE_INC_BASE_PRIORITY_NAME      = "SeIncreaseBasePriorityPrivilege"
;; Required to increase the base priority of a process.
;; User Right: Increase scheduling priority.
;Global Const $SE_INCREASE_QUOTA_NAME         = "SeIncreaseQuotaPrivilege"
;; Required to increase the quota assigned to a process.
;; User Right: Adjust memory quotas for a process.
;Global Const $SE_INC_WORKING_SET_NAME        = "SeIncreaseWorkingSetPrivilege"
;; Required to allocate more memory for applications that run in the context of users.
;; User Right: Increase a process working set.
;Global Const $SE_LOAD_DRIVER_NAME            = "SeLoadDriverPrivilege"
;; Required to load or unload a device driver.
;; User Right: Load and unload device drivers.
;Global Const $SE_LOCK_MEMORY_NAME            = "SeLockMemoryPrivilege"
;; Required to lock physical pages in memory.
;; User Right: Lock pages in memory.
;Global Const $SE_MACHINE_ACCOUNT_NAME        = "SeMachineAccountPrivilege"
;; Required to create a computer account.
;; User Right: Add workstations to domain.
;Global Const $SE_MANAGE_VOLUME_NAME          = "SeManageVolumePrivilege"
;; Required to enable volume management privileges.
;; User Right: Manage the files on a volume.
;Global Const $SE_PROF_SINGLE_PROCESS_NAME    = "SeProfileSingleProcessPrivilege"
;; Required to gather profiling information for a single process.
;; User Right: Profile single process.
;Global Const $SE_RELABEL_NAME                = "SeRelabelPrivilege"
;; Required to modify the mandatory integrity level of an object.
;; User Right: Modify an object label.
;Global Const $SE_REMOTE_SHUTDOWN_NAME        = "SeRemoteShutdownPrivilege"
;; Required to shut down a system using a network request.
;; User Right: Force shutdown from a remote system.
;Global Const $SE_RESTORE_NAME                = "SeRestorePrivilege"
;; Required to perform restore operations. This privilege causes the system to grant all write access control to any file,
;;  regardless of the ACL specified for the file. Any access request other than write is still evaluated with the ACL. Additionally,
;;  this privilege enables you to set any valid user or group SID as the owner of a rights are granted if this privilege is held:
;;      WRITE_DAC
;;      WRITE_OWNER
;;      ACCESS_SYSTEM_SECURITY
;;      FILE_GENERIC_WRITE
;;      FILE_ADD_FILE
;;      FILE_ADD_SUBDIRECTORY
;;      DELETE
;; User Right: Restore files and directories.
;Global Const $SE_SECURITY_NAME               = "SeSecurityPrivilege"
;; Required to perform a number of security-related functions, such as controlling and
;;  viewing audit messages. This privilege identifies its holder as a security operator.
;; User Right: Manage auditing and security log.
;Global Const $SE_SHUTDOWN_NAME               = "SeShutdownPrivilege"
;; Required to shut down a local system.
;; User Right: Shut down the system.
;Global Const $SE_SYNC_AGENT_NAME             = "SeSyncAgentPrivilege"
;; Required for a domain controller to use the Lightweight Directory Access Protocol directory synchronization services.
;;  This privilege enables the holder to read all objects and properties in the directory, regardless of the protection on
;;  and properties. By default, it is assigned to the Administrator and LocalSystem
;;  the objects accounts on domain controllers.
;; User Right: Synchronize directory service data.
;Global Const $SE_SYSTEM_ENVIRONMENT_NAME     = "SeSystemEnvironmentPrivilege"
;; Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information.
;; User Right: Modify firmware environment values.
;Global Const $SE_SYSTEM_PROFILE_NAME         = "SeSystemProfilePrivilege"
;; Required to gather profiling information for the entire system.
;; User Right: Profile system performance.
;Global Const $SE_SYSTEMTIME_NAME             = "SeSystemtimePrivilege"
;; Required to modify the system time.
;; User Right: Change the system time.
;Global Const $SE_TAKE_OWNERSHIP_NAME         = "SeTakeOwnershipPrivilege"
;; Required to take ownership of an object without being granted discretionary access. This privilege allows the owner
;;  value to be set only to those values that the holder may legitimately assign as the owner of an object.
;; User Right: Take ownership of files or other objects.
;Global Const $SE_TCB_NAME                    = "SeTcbPrivilege"
;; This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege.
;; User Right: Act as part of the operating system.
;Global Const $SE_TIME_ZONE_NAME              = "SeTimeZonePrivilege"
;; Required to adjust the time zone associated with the computer's internal clock.
;; User Right: Change the time zone.
;Global Const $SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"
;; Required to access Credential Manager as a trusted caller.
;; User Right: Access Credential Manager as a trusted caller.
;Global Const $SE_UNDOCK_NAME                 = "SeUndockPrivilege"
;; Required to undock a laptop.
;; User Right: Remove computer from docking station.
;Global Const $SE_UNSOLICITED_INPUT_NAME      = "SeUnsolicitedInputPrivilege"
;; Required to read unsolicited input from a terminal device.
;; User Right: Not applicable.
;
;;;;Global Static $aTokenPrivilegesNewState[35][2] = [[$SE_CREATE_TOKEN_NAME,2], [$SE_ASSIGNPRIMARYTOKEN_NAME,2], [$SE_LOCK_MEMORY_NAME,2], [$SE_INCREASE_QUOTA_NAME,2], [$SE_UNSOLICITED_INPUT_NAME,2], [$SE_MACHINE_ACCOUNT_NAME,2], [$SE_TCB_NAME,2], [$SE_SECURITY_NAME,2], [$SE_TAKE_OWNERSHIP_NAME,2], [$SE_LOAD_DRIVER_NAME,2], [$SE_SYSTEM_PROFILE_NAME,2], [$SE_SYSTEMTIME_NAME,2], [$SE_PROF_SINGLE_PROCESS_NAME,2], [$SE_INC_BASE_PRIORITY_NAME,2], [$SE_CREATE_PAGEFILE_NAME,2], [$SE_CREATE_PERMANENT_NAME,2], [$SE_BACKUP_NAME,2], [$SE_RESTORE_NAME,2], [$SE_SHUTDOWN_NAME,2], [$SE_DEBUG_NAME,2], [$SE_AUDIT_NAME,2], [$SE_SYSTEM_ENVIRONMENT_NAME,2], [$SE_CHANGE_NOTIFY_NAME,2], [$SE_REMOTE_SHUTDOWN_NAME,2], [$SE_UNDOCK_NAME,2], [$SE_SYNC_AGENT_NAME,2], [$SE_ENABLE_DELEGATION_NAME,2], [$SE_MANAGE_VOLUME_NAME,2], [$SE_IMPERSONATE_NAME,2], [$SE_CREATE_GLOBAL_NAME,2], [$SE_TRUSTED_CREDMAN_ACCESS_NAME,2], [$SE_RELABEL_NAME,2], [$SE_INC_WORKING_SET_NAME,2], [$SE_TIME_ZONE_NAME,2], [$SE_CREATE_SYMBOLIC_LINK_NAME,2]]
Global Static $aTokenPrivilegesNewState[6][2] = [[$SE_RESTORE_NAME,2],[$SE_BACKUP_NAME,2],[$SE_SECURITY_NAME,2],[$SE_TAKE_OWNERSHIP_NAME,2],[$SE_DEBUG_NAME,2],[$SE_CREATE_SYMBOLIC_LINK_NAME,2]]
Global Static $iTokenPrivilegesState
Global Static $aTokenPrivilegesPreviousState = _WinAPI_SetPrivilegeEx($aTokenPrivilegesNewState)

;;;;Global Const $OWNER_SECURITY_INFORMATION       = 0x00000001
;;;;Global Const $SE_REGISTRY_WOW64_32KEY          = 12 ;Indicates an object for a registry entry under WOW64.
Global Const $PSIDADMIN = _WinAPI_GetWellKnownSidEx("BA")
Global Const $PSIDUSER  = _WinAPI_GetWellKnownSidEx(@UserName)
Global Const $SZSIDUSER = _WinAPI_GetWellKnownSidEx(@UserName, 2)

;;;;Local $asSDDL = StringSplit("DA|DG|DU|ED|DD|DC|BA|BG|BU|LA|LG|AO|BO|PO|SO|AU|PS|CO|CG|SY|PU|WD|RE|IU|NU|SU|RC|WR|AN|SA|CA|RS|EA|PA|RU|LS|NS|RD|NO|MU|LU|IS|CY|OW|ER|RO|CD|AC|RA|ES|MS|UD|HA|CN|AA|RM|AS|SS|AP|LW|ME|MP|HI|SI", "|")
;;;;Local $aWKS = StringSplit("$WinNullSid|$WinWorldSid|$WinLocalSid|$WinCreatorOwnerSid|$WinCreatorGroupSid|$WinCreatorOwnerServerSid|$WinCreatorGroupServerSid|$WinNtAuthoritySid|$WinDialupSid|$WinNetworkSid|$WinBatchSid|$WinInteractiveSid|$WinServiceSid|$WinAnonymousSid|$WinProxySid|$WinEnterpriseControllersSid|$WinSelfSid|$WinAuthenticatedUserSid|$WinRestrictedCodeSid|$WinTerminalServerSid|$WinRemoteLogonIdSid|$WinLogonIdsSid|$WinLocalSystemSid|$WinLocalServiceSid|$WinNetworkServiceSid|$WinBuiltinDomainSid|$WinBuiltinAdministratorsSid|$WinBuiltinUsersSid|$WinBuiltinGuestsSid|$WinBuiltinPowerUsersSid|$WinBuiltinAccountOperatorsSid|$WinBuiltinSystemOperatorsSid|$WinBuiltinPrintOperatorsSid|$WinBuiltinBackupOperatorsSid|$WinBuiltinReplicatorSid|$WinBuiltinPreWindows2000CompatibleAccessSid|$WinBuiltinRemoteDesktopUsersSid|$WinBuiltinNetworkConfigurationOperatorsSid|$WinAccountAdministratorSid|$WinAccountGuestSid|$WinAccountKrbtgtSid|$WinAccountDomainAdminsSid|$WinAccountDomainUsersSid|$WinAccountDomainGuestsSid|$WinAccountComputersSid|$WinAccountControllersSid|$WinAccountCertAdminsSid|$WinAccountSchemaAdminsSid|$WinAccountEnterpriseAdminsSid|$WinAccountPolicyAdminsSid|$WinAccountRasAndIasServersSid|$WinNTLMAuthenticationSid|$WinDigestAuthenticationSid|$WinSChannelAuthenticationSid|$WinThisOrganizationSid|$WinOtherOrganizationSid|$WinBuiltinIncomingForestTrustBuildersSid|$WinBuiltinPerfMonitoringUsersSid|$WinBuiltinPerfLoggingUsersSid|$WinBuiltinAuthorizationAccessSid|$WinBuiltinTerminalServerLicenseServersSid|$WinBuiltinDCOMUsersSid|$WinBuiltinIUsersSid|$WinIUserSid|$WinBuiltinCryptoOperatorsSid|$WinUntrustedLabelSid|$WinLowLabelSid|$WinMediumLabelSid|$WinHighLabelSid|$WinSystemLabelSid|$WinWriteRestrictedCodeSid|$WinCreatorOwnerRightsSid|$WinCacheablePrincipalsGroupSid|$WinNonCacheablePrincipalsGroupSid|$WinEnterpriseReadonlyControllersSid|$WinAccountReadonlyControllersSid|$WinBuiltinEventLogReadersGroup|$WinNewEnterpriseReadonlyControllersSid|$WinBuiltinCertSvcDComAccessGroup|$WinMediumPlusLabelSid|$WinLocalLogonSid|$WinConsoleLogonSid|$WinThisOrganizationCertificateSid|$WinApplicationPackageAuthoritySid|$WinBuiltinAnyPackageSid|$WinCapabilityInternetClientSid|$WinCapabilityInternetClientServerSid|$WinCapabilityPrivateNetworkClientServerSid|$WinCapabilityPicturesLibrarySid|$WinCapabilityVideosLibrarySid|$WinCapabilityMusicLibrarySid|$WinCapabilityDocumentsLibrarySid|$WinCapabilitySharedUserCertificatesSid|$WinCapabilityEnterpriseAuthenticationSid|$WinCapabilityRemovableStorageSid|$WinBuiltinRDSRemoteAccessServersSid|$WinBuiltinRDSEndpointServersSid|$WinBuiltinRDSManagementServersSid|$WinUserModeDriversSid|$WinBuiltinHyperVAdminsSid|$WinAccountCloneableControllersSid|$WinBuiltinAccessControlAssistanceOperatorsSid|$WinBuiltinRemoteManagementUsersSid|$WinAuthenticationAuthorityAssertedSid|$WinAuthenticationServiceAssertedSid|$WinLocalAccountSid|$WinLocalAccountAndAdministratorSid|$WinAccountProtectedUsersSid", "|", 2)

;;
;; Well known SID definitions for lookup.
;;
Global Enum _ ;; $WELL_KNOWN_SID_TYPE
    $WinNullSid                                    = 0, _    ;; Indicates a null SID.
    $WinWorldSid                                   = 1, _    ;; "WD" - $SDDL_EVERYONE - Indicates a SID that matches everyone.
    $WinLocalSid                                   = 2, _    ;; Indicates a local SID.
    $WinCreatorOwnerSid                            = 3, _    ;; "CO" - $SDDL_CREATOR_OWNER - Indicates a SID that matches the owner or creator of an object.
    $WinCreatorGroupSid                            = 4, _    ;; "CG" - $SDDL_CREATOR_GROUP - Indicates a SID that matches the creator group of an object.
    $WinCreatorOwnerServerSid                      = 5, _    ;; Indicates a creator owner server SID.
    $WinCreatorGroupServerSid                      = 6, _    ;; Indicates a creator group server SID.
    $WinNtAuthoritySid                             = 7, _    ;; Indicates a SID for the Windows NT authority account.
    $WinDialupSid                                  = 8, _    ;; Indicates a SID for a dial-up account.
    $WinNetworkSid                                 = 9, _    ;; "NU" - $SDDL_NETWORK - Indicates a SID for a network account. This SID is added to the process of a token when it logs on across a network. The corresponding logon type is LOGON32_LOGON_NETWORK.
    $WinBatchSid                                   = 10, _   ;; Indicates a SID for a batch process. This SID is added to the process of a token when it logs on as a batch job. The corresponding logon type is LOGON32_LOGON_BATCH.
    $WinInteractiveSid                             = 11, _   ;; "IU" - $SDDL_INTERACTIVE - Indicates a SID for an interactive account. This SID is added to the process of a token when it logs on interactively. The corresponding logon type is LOGON32_LOGON_INTERACTIVE.
    $WinServiceSid                                 = 12, _   ;; "SU" - $SDDL_SERVICE - Indicates a SID for a service. This SID is added to the process of a token when it logs on as a service. The corresponding logon type is LOGON32_LOGON_SERVICE.
    $WinAnonymousSid                               = 13, _   ;; "AN" - $SDDL_ANONYMOUS - Indicates a SID for the anonymous account.
    $WinProxySid                                   = 14, _   ;; Indicates a proxy SID.
    $WinEnterpriseControllersSid                   = 15, _   ;; "ED" - $SDDL_ENTERPRISE_DOMAIN_CONTROLLERS - Indicates a SID for an enterprise controller.
    $WinSelfSid                                    = 16, _   ;; "PS" - $SDDL_PERSONAL_SELF - Indicates a SID for self.
    $WinAuthenticatedUserSid                       = 17, _   ;; "AU" - $SDDL_AUTHENTICATED_USERS - Indicates a SID that matches any authenticated user.
    $WinRestrictedCodeSid                          = 18, _   ;; "RC" - $SDDL_RESTRICTED_CODE - Indicates a SID for restricted code.
    $WinTerminalServerSid                          = 19, _   ;; Indicates a SID that matches a terminal server account.
    $WinRemoteLogonIdSid                           = 20, _   ;; Indicates a SID that matches remote logons.
    $WinLogonIdsSid                                = 21, _   ;; Indicates a SID that matches logon IDs.
    $WinLocalSystemSid                             = 22, _   ;; "SY" - $SDDL_LOCAL_SYSTEM - Indicates a SID that matches the local system.
    $WinLocalServiceSid                            = 23, _   ;; "LS" - $SDDL_LOCAL_SERVICE - Indicates a SID that matches a local service.
    $WinNetworkServiceSid                          = 24, _   ;; "NS" - $SDDL_NETWORK_SERVICE - Indicates a SID that matches a network service.
    $WinBuiltinDomainSid                           = 25, _   ;; Indicates a SID that matches the domain account.
    $WinBuiltinAdministratorsSid                   = 26, _   ;; "BA" - $SDDL_BUILTIN_ADMINISTRATORS - Indicates a SID that matches the administrator group.
    $WinBuiltinUsersSid                            = 27, _   ;; "BU" - $SDDL_BUILTIN_USERS - Indicates a SID that matches built-in user accounts.
    $WinBuiltinGuestsSid                           = 28, _   ;; "BG" - $SDDL_BUILTIN_GUESTS - Indicates a SID that matches the guest account.
    $WinBuiltinPowerUsersSid                       = 29, _   ;; "PU" - $SDDL_POWER_USERS - Indicates a SID that matches the power users group.
    $WinBuiltinAccountOperatorsSid                 = 30, _   ;; "AO" - $SDDL_ACCOUNT_OPERATORS - Indicates a SID that matches the account operators account.
    $WinBuiltinSystemOperatorsSid                  = 31, _   ;; "SO" - $SDDL_SERVER_OPERATORS - Indicates a SID that matches the system operators group.
    $WinBuiltinPrintOperatorsSid                   = 32, _   ;; "PO" - $SDDL_PRINTER_OPERATORS - Indicates a SID that matches the print operators group.
    $WinBuiltinBackupOperatorsSid                  = 33, _   ;; "BO" - $SDDL_BACKUP_OPERATORS - Indicates a SID that matches the backup operators group.
    $WinBuiltinReplicatorSid                       = 34, _   ;; "RE" - $SDDL_REPLICATOR - Indicates a SID that matches the replicator account.
    $WinBuiltinPreWindows2000CompatibleAccessSid   = 35, _   ;; "RU" - $SDDL_ALIAS_PREW2KCOMPACC - Indicates a SID that matches pre-Windows 2000 compatible accounts.
    $WinBuiltinRemoteDesktopUsersSid               = 36, _   ;; "RD" - $SDDL_REMOTE_DESKTOP - Indicates a SID that matches remote desktop users.
    $WinBuiltinNetworkConfigurationOperatorsSid    = 37, _   ;; "NO" - $SDDL_NETWORK_CONFIGURATION_OPS - Indicates a SID that matches the network operators group.
    $WinAccountAdministratorSid                    = 38, _   ;; Indicates a SID that matches the account administrator's account.
    $WinAccountGuestSid                            = 39, _   ;; Indicates a SID that matches the account guest group.
    $WinAccountKrbtgtSid                           = 40, _   ;; Indicates a SID that matches account Kerberos target group.
    $WinAccountDomainAdminsSid                     = 41, _   ;; Indicates a SID that matches the account domain administrator group.
    $WinAccountDomainUsersSid                      = 42, _   ;; Indicates a SID that matches the account domain users group.
    $WinAccountDomainGuestsSid                     = 43, _   ;; Indicates a SID that matches the account domain guests group.
    $WinAccountComputersSid                        = 44, _   ;; Indicates a SID that matches the account computer group.
    $WinAccountControllersSid                      = 45, _   ;; Indicates a SID that matches the account controller group.
    $WinAccountCertAdminsSid                       = 46, _   ;; Indicates a SID that matches the certificate administrators group.
    $WinAccountSchemaAdminsSid                     = 47, _   ;; Indicates a SID that matches the schema administrators group.
    $WinAccountEnterpriseAdminsSid                 = 48, _   ;; Indicates a SID that matches the enterprise administrators group.
    $WinAccountPolicyAdminsSid                     = 49, _   ;; Indicates a SID that matches the policy administrators group.
    $WinAccountRasAndIasServersSid                 = 50, _   ;; Indicates a SID that matches the RAS and IAS server account.
    $WinNTLMAuthenticationSid                      = 51, _   ;; Indicates a SID present when the Microsoft NTLM authentication package authenticated the client.
    $WinDigestAuthenticationSid                    = 52, _   ;; Indicates a SID present when the Microsoft Digest authentication package authenticated the client.
    $WinSChannelAuthenticationSid                  = 53, _   ;; Indicates a SID present when the Secure Channel (SSL/TLS) authentication package authenticated the client.
    $WinThisOrganizationSid                        = 54, _   ;; Indicates a SID present when the user authenticated from within the forest or across a trust that does not have the selective authentication option enabled. If this SID is present, then WinOtherOrganizationSid cannot be present.
    $WinOtherOrganizationSid                       = 55, _   ;; Indicates a SID present when the user authenticated across a forest with the selective authentication option enabled. If this SID is present, then WinThisOrganizationSid cannot be present.
    $WinBuiltinIncomingForestTrustBuildersSid      = 56, _   ;; Indicates a SID that allows a user to create incoming forest trusts. It is added to the token of users who are a member of the Incoming Forest Trust Builders built-in group in the root domain of the forest.
    $WinBuiltinPerfMonitoringUsersSid              = 57, _   ;; "MU" - $SDDL_PERFMON_USERS - Indicates a SID that matches the performance monitor user group.
    $WinBuiltinPerfLoggingUsersSid                 = 58, _   ;; "LU" - $SDDL_PERFLOG_USERS - Indicates a SID that matches the performance log user group.
    $WinBuiltinAuthorizationAccessSid              = 59, _   ;; Indicates a SID that matches the Windows Authorization Access group.
    $WinBuiltinTerminalServerLicenseServersSid     = 60, _   ;; Indicates a SID is present in a server that can issue terminal server licenses.
    $WinBuiltinDCOMUsersSid                        = 61, _   ;; Indicates a SID that matches the distributed COM user group.
    $WinBuiltinIUsersSid                           = 62, _   ;; "IS" - $SDDL_IIS_USERS - Indicates a SID that matches the Internet built-in user group.
    $WinIUserSid                                   = 63, _   ;; Indicates a SID that matches the Internet user group.
    $WinBuiltinCryptoOperatorsSid                  = 64, _   ;; "CY" - $SDDL_CRYPTO_OPERATORS - Indicates a SID that allows a user to use cryptographic operations. It is added to the token of users who are a member of the CryptoOperators built-in group.
    $WinUntrustedLabelSid                          = 65, _   ;; Indicates a SID that matches an untrusted label.
    $WinLowLabelSid                                = 66, _   ;; "LW" - $SDDL_ML_LOW - Indicates a SID that matches an low level of trust label.
    $WinMediumLabelSid                             = 67, _   ;; "ME" - $SDDL_ML_MEDIUM - Indicates a SID that matches an medium level of trust label.
    $WinHighLabelSid                               = 68, _   ;; "HI" - $SDDL_ML_HIGH - Indicates a SID that matches a high level of trust label.
    $WinSystemLabelSid                             = 69, _   ;; "SI" - $SDDL_ML_SYSTEM - Indicates a SID that matches a system label.
    $WinWriteRestrictedCodeSid                     = 70, _   ;; "WR" - $SDDL_WRITE_RESTRICTED_CODE - Indicates a SID that matches a write restricted code group.
    $WinCreatorOwnerRightsSid                      = 71, _   ;; "OW" - $SDDL_OWNER_RIGHTS - Indicates a SID that matches a creator and owner rights group.
    $WinCacheablePrincipalsGroupSid                = 72, _   ;; Indicates a SID that matches a cacheable principals group.
    $WinNonCacheablePrincipalsGroupSid             = 73, _   ;; Indicates a SID that matches a non-cacheable principals group.
    $WinEnterpriseReadonlyControllersSid           = 74, _   ;; Indicates a SID that matches an enterprise wide read-only controllers group.
    $WinAccountReadonlyControllersSid              = 75, _   ;; Indicates a SID that matches an account read-only controllers group.
    $WinBuiltinEventLogReadersGroup                = 76, _   ;; "ER" - $SDDL_EVENT_LOG_READERS - Indicates a SID that matches an event log readers group.
    $WinNewEnterpriseReadonlyControllersSid        = 77, _   ;; Indicates a SID that matches a read-only enterprise domain controller.
    $WinBuiltinCertSvcDComAccessGroup              = 78      ;; "CD" - $SDDL_CERTSVC_DCOM_ACCESS - Indicates a SID that matches the built-in DCOM certification services access group.
Global Enum _ ;; $WELL_KNOWN_SID_TYPE - Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP:  This value is not available.
    $WinMediumPlusLabelSid                         = 79, _   ;; "MP" - $SDDL_ML_MEDIUM_PLUS - Indicates a SID that matches the medium plus integrity label.
    $WinLocalLogonSid                              = 80, _   ;; Indicates a SID that matches a local logon group.
    $WinConsoleLogonSid                            = 81, _   ;; Indicates a SID that matches a console logon group.
    $WinThisOrganizationCertificateSid             = 82, _   ;; Indicates a SID that matches a certificate for the given organization.
    $WinApplicationPackageAuthoritySid             = 83, _   ;; Indicates a SID that matches the application package authority.
    $WinBuiltinAnyPackageSid                       = 84, _   ;; "AC" - $SDDL_ALL_APP_PACKAGES - Indicates a SID that applies to all app containers.
    $WinCapabilityInternetClientSid                = 85, _   ;; Indicates a SID of Internet client capability for app containers.
    $WinCapabilityInternetClientServerSid          = 86, _   ;; Indicates a SID of Internet client and server capability for app containers.
    $WinCapabilityPrivateNetworkClientServerSid    = 87, _   ;; Indicates a SID of private network client and server capability for app containers.
    $WinCapabilityPicturesLibrarySid               = 88, _   ;; Indicates a SID for pictures library capability for app containers.
    $WinCapabilityVideosLibrarySid                 = 89, _   ;; Indicates a SID for videos library capability for app containers.
    $WinCapabilityMusicLibrarySid                  = 90, _   ;; Indicates a SID for music library capability for app containers.
    $WinCapabilityDocumentsLibrarySid              = 91, _   ;; Indicates a SID for documents library capability for app containers.
    $WinCapabilitySharedUserCertificatesSid        = 92, _   ;; Indicates a SID for shared user certificates capability for app containers.
    $WinCapabilityEnterpriseAuthenticationSid      = 93, _   ;; Indicates a SID for Windows credentials capability for app containers.
    $WinCapabilityRemovableStorageSid              = 94, _   ;; Indicates a SID for removable storage capability for app containers.
    $WinBuiltinRDSRemoteAccessServersSid           = 95, _   ;; "RA" - $SDDL_RDS_REMOTE_ACCESS_SERVERS
    $WinBuiltinRDSEndpointServersSid               = 96, _   ;; "ES" - $SDDL_RDS_ENDPOINT_SERVERS
    $WinBuiltinRDSManagementServersSid             = 97, _   ;; "MS" - $SDDL_RDS_MANAGEMENT_SERVERS
    $WinUserModeDriversSid                         = 98, _   ;; "UD" - $SDDL_USER_MODE_DRIVERS
    $WinBuiltinHyperVAdminsSid                     = 99, _   ;; "HA" - $SDDL_HYPER_V_ADMINS
    $WinAccountCloneableControllersSid             = 100, _  ;;
    $WinBuiltinAccessControlAssistanceOperatorsSid = 101, _  ;; "AA" - $SDDL_ACCESS_CONTROL_ASSISTANCE_OPS
    $WinBuiltinRemoteManagementUsersSid            = 102, _  ;; "RM" - $SDDL_REMOTE_MANAGEMENT_USERS
    $WinAuthenticationAuthorityAssertedSid         = 103, _  ;; "AS" - $SDDL_AUTHORITY_ASSERTED
    $WinAuthenticationServiceAssertedSid           = 104, _  ;; "SS" - $SDDL_SERVICE_ASSERTED
    $WinLocalAccountSid                            = 105, _  ;;
    $WinLocalAccountAndAdministratorSid            = 106, _  ;;
    $WinAccountProtectedUsersSid                   = 107     ;;
Global Const $WELL_KNOWN_SID_TYPE                  = "INT"

; #FUNCTION# ====================================================================================================================================
; Name...........: _WinAPI_SetPrivilegeEx
; Description ...: Enables or disables special privileges as required by some DllCalls
; Syntax.........: _WinAPI_SetPrivilegeEx($avPrivilege)
; Parameters ....: $avPrivilege - An array of privileges and respective attributes
;                                 $SE_PRIVILEGE_ENABLED - The function enables the privilege
;                                 $SE_PRIVILEGE_REMOVED - The privilege is removed from the list of privileges in the token
;                                 0 - The function disables the privilege
; Requirement(s).: None
; Return values .: Success - An array of modified privileges and their respective previous attribute state
;                  Failure - An empty array
;                            Sets @Error
; Author ........: engine
; Modified.......: FredAI, DXRW4E
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......;
; ===============================================================================================================================================
Func _WinAPI_SetPrivilegeEx($avPrivilege)
    $iTokenPrivilegesState = $iTokenPrivilegesState ? 0 : 1
    If Not UBound($avPrivilege) Then Return SetError(1, 0, 0)
    Local $tagTP = "DWORD", $iTokens = UBound($avPrivilege), $iError = 0, $iCount
    For $i = 1 To $iTokens
        $tagTP &= ";DWORD;LONG;DWORD"
    Next
    Local $tCurrState = DLLStructCreate($tagTP), $tPrevState = DllStructCreate($tagTP), $tLUID = DllStructCreate("DWORD;LONG")
    DLLStructSetData($tCurrState, 1, $iTokens)
    For $i = 0 To $iTokens - 1
        DllCall($hAdvapi32Dll, "BOOL", "LookupPrivilegeValueW", "WSTR", Null, "WSTR", $avPrivilege[$i][0], "STRUCT*", $tLUID)
        DLLStructSetData($tCurrState, 3 * $i + 2, DllStructGetData($tLUID, 1))
        DLLStructSetData($tCurrState, 3 * $i + 3, DllStructGetData($tLUID, 2))
        DLLStructSetData($tCurrState, 3 * $i + 4, $avPrivilege[$i][1])
    Next
    Local $hToken = DllCall($hAdvapi32Dll, "BOOL", "OpenProcessToken", "HANDLE", DllCall($hKernel32DLL, "HANDLE", "GetCurrentProcess")[0], "DWORD", 40, "HANDLE*", 0)[3] ;; TOKEN_ADJUST_PRIVILEGES + TOKEN_QUERY = 40
    DllCall($hAdvapi32Dll, "BOOL", "AdjustTokenPrivileges", "HANDLE", $hToken, "BOOL", False, "STRUCT*", $tCurrState, "DWORD", DllStructGetSize($tCurrState), "STRUCT*", $tPrevState, "DWORD*", 0)
    $iError = DllCall($hKernel32DLL, "DWORD", "GetLastError")[0]
    DllCall($hKernel32DLL, "BOOL", "CloseHandle", "HANDLE", $hToken)
    $iCount = DllStructGetData($tPrevState, 1)
    If $iCount < 1 Then Return SetError($iError, 0, 0)
    Local $pLUID, $tName, $avPrevState[$iCount][2], $pPrevState = DllStructGetPtr($tPrevState)
    For $i = 0 To $iCount - 1
        $pLUID = $pPrevState + 12 * $i + 4
        $tName = DllStructCreate("WCHAR[" & DllCall($hAdvapi32Dll, "BOOL", "LookupPrivilegeNameW", "WSTR", Null, "PTR", $pLUID, "PTR", 0, "DWORD*", 0)[4] & "]")
        DllCall($hAdvapi32Dll, "BOOL", "LookupPrivilegeNameW", "WSTR", Null, "PTR", $pLUID, "STRUCT*", $tName, "DWORD*", DllStructGetSize($tName))
        $avPrevState[$i][0] = DllStructGetData($tName, 1)
        $avPrevState[$i][1] = DllStructGetData($tPrevState, 3 * $i + 4)
    Next
    Return SetError($iError, 1, $avPrevState)
EndFunc ;==> _WinAPI_SetPrivilegeEx

; #FUNCTION# ====================================================================================================================
; Name...........: _WinAPI_GetWellKnownSidEx
; Description ...: Get\Create SID
; Syntax.........: _WinAPI_GetWellKnownSidEx($sWellKnownSid)
; Parameters ....: $sWellKnownSid - A member of the WELL_KNOWN_SID_TYPE enumeration that specifies what the SID will identify
;                                   Or a string containing the string-format SID. The SID string can use either the standard
;                                    S-R-I-S-S… format for SID strings, or the SID string constant format, such as "BA" for built-in
;                                    administrators. For more information about SID string notation, see SDDL User aliases ($SDDL_*) and
;                                    SID Components http://msdn.microsoft.com/en-us/library/windows/desktop/aa379597%28v=vs.85%29.aspx
;                                  Or set NULL thi parameter to clean everything, to delete all SID Structure\pointer in $aWellKnownSid
;                  $iFlags - Optional
;                  |0 - (Default) Return pointer of the SID Structure
;                  |1 - Return SID Structure (the SID in a byte structure)
;                  |2 - Return the standard S-R-I-S-S… format for SID strings
;                  |3 - Return SID SDDL User aliases (example BA or BU etc etc)
;                  |4 - Return SID WELL_KNOWN_SID_TYPE (0 to 107)
;                  |8 - Return Array2D ($aWellKnownSid) of SID
; Return values .: Success - A pointer to a SID structure that identifies the object Or see $iFlags option
; Author ........: DXRW4E
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......:
; ===============================================================================================================================
Func _WinAPI_GetWellKnownSidEx($sWellKnownSid, $iFlags = 0)
    Local Static $aWellKnownSid[5][5] = [[0,4,@LF, @CR & "0" & @LF]]
    If BitAND($iFlags, 8) Then Return $aWellKnownSid
    If $sWellKnownSid == Null Then
        Local $_aWellKnownSid[5][5] = [[0,4,@LF, @CR & "0" & @LF]]
        $aWellKnownSid = $_aWellKnownSid
        Return
    EndIf
    Local $iType = BitAND($iFlags, ($iFlags > 4 ? 3 : 7)), $iSid = Int(StringRegExp($aWellKnownSid[0][2] & $sWellKnownSid & $aWellKnownSid[0][3], "(?i)\n\K\Q" & $sWellKnownSid & "\E\r(\d+)\n", 1)[0])
    If $iSid Then Return SetError(0, $aWellKnownSid[$iSid][0], $aWellKnownSid[$iSid][$iType])
    If $aWellKnownSid[0][0] = $aWellKnownSid[0][1] Then
        $aWellKnownSid[0][1] *= 2
        ReDim $aWellKnownSid[$aWellKnownSid[0][1] + 1][5]
    EndIf
    $iSid = $aWellKnownSid[0][0] + 1
    If String($sWellKnownSid) = @UserName Then
        $sWellKnownSid = DllStructCreate("Byte SID[256]")
        $arDllCall = DllCall($hAdvapi32Dll, "BOOL", "LookupAccountNameW", "WSTR", Null, "WSTR", @UserName, "STRUCT*", $sWellKnownSid, "DWORD*", DllStructGetSize($sWellKnownSid), "WSTR", "", "DWORD*", DllStructGetSize($sWellKnownSid), "INT*", 0)
        If @Error Or Not $arDllCall[0] Then Return SetError((@Error ? @Error : _WinAPI_GetLastErrorEx()), 1, 0)
        $arDllCall = DllCall($hAdvapi32Dll, "INT", "ConvertSidToStringSidW", "STRUCT*", $sWellKnownSid, "PTR*", 0)
        If @Error Or Not $arDllCall[0] Then Return SetError((@Error ? @Error : _WinAPI_GetLastErrorEx()), 2, 0)
        $sWellKnownSid = DllStructGetData(DllStructCreate("WCHAR[256]", $arDllCall[2]), 1)
        DllCall($hKernel32DLL, "PTR", "LocalFree", "PTR", $arDllCall[2])
        $aWellKnownSid[0][2] &= @UserName & @CR & $iSid & @LF
    EndIf
    If StringIsDigit($sWellKnownSid) Then
        $arDllCall = DllCall($hAdvapi32Dll, "BOOL", "CreateWellKnownSid", "INT", Int($sWellKnownSid), "PTR", Null, "PTR", Null, "DWORD*", 0)
        If @Error Or Not $arDllCall[4] Then Return SetError((@Error ? @Error : _WinAPI_GetLastErrorEx()), 3, 0)
        $aWellKnownSid[$iSid][1] = DllStructCreate("Byte SID[" & $arDllCall[4] & "]")
        $arDllCall = DllCall($hAdvapi32Dll, "BOOL", "CreateWellKnownSid", "INT", $arDllCall[1], "PTR", Null, "STRUCT*", $aWellKnownSid[$iSid][1], "DWORD*", $arDllCall[4])
        If Not $arDllCall[0] Then Return SetError(_WinAPI_GetLastErrorEx(), 4, 0)
        $aWellKnownSid[$iSid][4] = $arDllCall[1]
    Else
        $arDllCall = DllCall($hAdvapi32Dll, "BOOL", "ConvertStringSidToSidW", "WSTR", $sWellKnownSid, "PTR*", 0)
        If @Error Or Not $arDllCall[0] Then
            If $sWellKnownSid <> "BA" Then Return SetError((@Error ? @Error : _WinAPI_GetLastErrorEx()), 5, 0)
            $aWellKnownSid[$iSid][1] = DllStructCreate("Byte Data[16]")
            DllStructSetData($aWellKnownSid[$iSid][1], "Data", "0x01020000000000052000000020020000")
        Else
            $arDllCall = DllCall($hAdvapi32Dll, "DWORD", "GetLengthSid", "PTR", $arDllCall[2])
            $aWellKnownSid[$iSid][1] = DllStructCreate("Byte Data[" & $arDllCall[0] & "]")
            DllStructSetData($aWellKnownSid[$iSid][1], "Data", DllStructGetData(DllStructCreate("Byte Data[" & $arDllCall[0] & "]", $arDllCall[1]), "Data"))
            DllCall($hKernel32DLL, "PTR", "LocalFree", "PTR", $arDllCall[1])
        EndIf
        $aWellKnownSid[$iSid][3] = $sWellKnownSid
    EndIf
    $aWellKnownSid[$iSid][2] = DllCall($hAdvapi32Dll, "BOOL", "ConvertSidToStringSidW", "STRUCT*", $aWellKnownSid[$iSid][1], "WSTR*", 0)[2]
    If Not $aWellKnownSid[$iSid][3] Then $aWellKnownSid[$iSid][3] = $aWellKnownSid[$iSid][2]
    If StringRegExp($aWellKnownSid[0][2], "(?i)\n\K\Q" & $aWellKnownSid[$iSid][2] & "\E\r\d+\n") Then
        $iSid = StringRegExp($aWellKnownSid[0][2], "(?i)\n\K\Q" & $aWellKnownSid[$iSid][2] & "\E\r(\d+)\n", 1)[0]
        $aWellKnownSid[0][2] &= $sWellKnownSid & @CR & $iSid & @LF
        $aWellKnownSid[$iSid][(StringIsDigit($sWellKnownSid) ? 4 : 3)] = $sWellKnownSid
        Return SetError(0, $aWellKnownSid[$iSid][0], $aWellKnownSid[$iSid][$iType])
    EndIf
    $aWellKnownSid[0][0] = $iSid
    $aWellKnownSid[$iSid][0] = DllStructGetPtr($aWellKnownSid[$iSid][1])
    $aWellKnownSid[0][2] &= $sWellKnownSid & @CR & $iSid & @LF & $aWellKnownSid[$iSid][2] & @CR & $iSid & @LF
    Return SetError(0, $aWellKnownSid[$iSid][0], $aWellKnownSid[$iSid][$iType])
EndFunc

Func _WinAPI_GetLastErrorEx()
    $arDllCall = DllCall($hKernel32DLL, "LONG", "GetLastError")
    Return (@Error ? @Error : $arDllCall[0])
EndFunc ;==>_WinAPI_GetLastErrorEx

;~ Func _WinAPI_CreateWellKnownSid($iWellKnownSidType = 26, $iFlags = 0)
;~  $arDllCall = DllCall($hAdvapi32Dll, "BOOL", "CreateWellKnownSid", "INT", $iWellKnownSidType, "PTR", Null, "PTR", Null, "DWORD*", 0)
;~  If @Error Or Not $arDllCall[4] Then Return SetError((@Error ? @Error : _WinAPI_GetLastErrorEx()), 1, 0)
;~  Local $TheSID = DllStructCreate("Byte SID[" & $arDllCall[4] & "]")
;~  $arDllCall = DllCall($hAdvapi32Dll, "BOOL", "CreateWellKnownSid", "INT", $iWellKnownSidType, "PTR", Null, "STRUCT*", $TheSID, "DWORD*", $arDllCall[4])
;~  If Not $arDllCall[0] Then Return SetError(_WinAPI_GetLastErrorEx(), 2, 0)
;~  If $iFlags Then Return DllCall($hAdvapi32Dll, "BOOL", "ConvertSidToStringSidW", "STRUCT*", $TheSID, "WSTR*", 0)[2]
;~  Return $TheSID
;~ EndFunc

#Endregion ;**** Token Privileges ****

Ciao.

PrivilegesEx.au3

Edited by DXRW4E

apps-odrive.pngdrive_app_badge.png box-logo.png new_logo.png MEGA_Logo.png

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now