Что нового

Установка привилегий для AutoIt скриптов

Yashied

Модератор
Команда форума
Глобальный модератор
Сообщения
5,379
Репутация
2,724
Меня интересует такой вопрос: как можно установить / снять выбранные привилегии для AutoIt скрипта? В частности нужно установить SE_BACKUP_NAME привилегии(ю). Отпишитесь, если кто имел с этим дело. Работаю в Windows XP SP2 (так, на всякий случай). Для чего это нужно? Есть такая функция RegSaveKeyEx(), так вот, для ее работы необходимо иметь включенную эту самую привилегию. :Censored:

PS

Интересует не сама запись ключей реестра в .reg файл, а именно использование этой функции.
 
Автор
Yashied

Yashied

Модератор
Команда форума
Глобальный модератор
Сообщения
5,379
Репутация
2,724
Ладно, сам разобрался. В ближайшее время выложу обновленную библиотеку WinAPIEx.au3 (v2.0), где все необходимые функции на эту тему присутствуют. А пока, если кому интересно, вот решение:

Код:
; ===============================================================================================================================
; _WinAPI_OpenProcessToken()
; ===============================================================================================================================

#cs

Global Const $TOKEN_ADJUST_DEFAULT = 0x00000080
Global Const $TOKEN_ADJUST_GROUPS = 0x00000040
Global Const $TOKEN_ADJUST_PRIVILEGES = 0x00000020
Global Const $TOKEN_ADJUST_SESSIONID = 0x00000100
Global Const $TOKEN_ASSIGN_PRIMARY = 0x00000001
Global Const $TOKEN_DUPLICATE = 0x00000002
Global Const $TOKEN_EXECUTE = 0x00020000
Global Const $TOKEN_IMPERSONATE = 0x00000004
Global Const $TOKEN_QUERY = 0x00000008
Global Const $TOKEN_QUERY_SOURCE = 0x00000010
Global Const $TOKEN_READ = 0x00020008
Global Const $TOKEN_WRITE = 0x000200E0
Global Const $TOKEN_ALL_ACCESS = 0x000F01FF

#ce

; ===============================================================================================================================
; _WinAPI_LookupPrivilegeValue()
; ===============================================================================================================================

#cs

Global Const $SE_ASSIGNPRIMARYTOKEN_NAME = 'SeAssignPrimaryTokenPrivilege'
Global Const $SE_AUDIT_NAME = 'SeAuditPrivilege'
Global Const $SE_BACKUP_NAME = 'SeBackupPrivilege'
Global Const $SE_CHANGE_NOTIFY_NAME = 'SeChangeNotifyPrivilege'
Global Const $SE_CREATE_GLOBAL_NAME = 'SeCreateGlobalPrivilege'
Global Const $SE_CREATE_PAGEFILE_NAME = 'SeCreatePagefilePrivilege'
Global Const $SE_CREATE_PERMANENT_NAME = 'SeCreatePermanentPrivilege'
Global Const $SE_CREATE_SYMBOLIC_LINK_NAME = 'SeCreateSymbolicLinkPrivilege'
Global Const $SE_CREATE_TOKEN_NAME = 'SeCreateTokenPrivilege'
Global Const $SE_DEBUG_NAME = 'SeDebugPrivilege'
Global Const $SE_ENABLE_DELEGATION_NAME = 'SeEnableDelegationPrivilege'
Global Const $SE_IMPERSONATE_NAME = 'SeImpersonatePrivilege'
Global Const $SE_INC_BASE_PRIORITY_NAME = 'SeIncreaseBasePriorityPrivilege'
Global Const $SE_INCREASE_QUOTA_NAME = 'SeIncreaseQuotaPrivilege'
Global Const $SE_INC_WORKING_SET_NAME = 'SeIncreaseWorkingSetPrivilege'
Global Const $SE_LOAD_DRIVER_NAME = 'SeLoadDriverPrivilege'
Global Const $SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege'
Global Const $SE_MACHINE_ACCOUNT_NAME = 'SeMachineAccountPrivilege'
Global Const $SE_MANAGE_VOLUME_NAME = 'SeManageVolumePrivilege'
Global Const $SE_PROF_SINGLE_PROCESS_NAME = 'SeProfileSingleProcessPrivilege'
Global Const $SE_RELABEL_NAME = 'SeRelabelPrivilege'
Global Const $SE_REMOTE_SHUTDOWN_NAME = 'SeRemoteShutdownPrivilege'
Global Const $SE_RESTORE_NAME = 'SeRestorePrivilege'
Global Const $SE_SECURITY_NAME = 'SeSecurityPrivilege'
Global Const $SE_SHUTDOWN_NAME = 'SeShutdownPrivilege'
Global Const $SE_SYNC_AGENT_NAME = 'SeSyncAgentPrivilege'
Global Const $SE_SYSTEM_ENVIRONMENT_NAME = 'SeSystemEnvironmentPrivilege'
Global Const $SE_SYSTEM_PROFILE_NAME = 'SeSystemProfilePrivilege'
Global Const $SE_SYSTEMTIME_NAME = 'SeSystemtimePrivilege'
Global Const $SE_TAKE_OWNERSHIP_NAME = 'SeTakeOwnershipPrivilege'
Global Const $SE_TCB_NAME = 'SeTcbPrivilege'
Global Const $SE_TIME_ZONE_NAME = 'SeTimeZonePrivilege'
Global Const $SE_TRUSTED_CREDMAN_ACCESS_NAME = 'SeTrustedCredManAccessPrivilege'
Global Const $SE_UNDOCK_NAME = 'SeUndockPrivilege'
Global Const $SE_UNSOLICITED_INPUT_NAME = 'SeUnsolicitedInputPrivilege'

#ce

Global Const $tagLUID = 'dword LowPart;long HighPart'

; #FUNCTION# ====================================================================================================================
; Name...........: _WinAPI_LookupPrivilegeValue
; Description....: Retrieves the locally unique identifier (LUID) to locally represent the specified privilege name.
; Syntax.........: _WinAPI_LookupPrivilegeValue ( $sPrivilege )
; Parameters.....: $sPrivilege - The string that specifies the name of the privilege ($SE_...).
; Return values..: Success     - $tagLUID structure that contains the LUID.
;                  Failure     - 0 and sets the @error flag to non-zero.
; Author.........: Yashied
; Modified.......:
; Remarks........: None
; Related........:
; Link...........: @@MsdnLink@@ LookupPrivilegeValue
; Example........: Yes
; ===============================================================================================================================

Func _WinAPI_LookupPrivilegeValue($sPrivilege)

	$tLUID = DllStructCreate($tagLUID)
	Local $Ret = DllCall('advapi32.dll', 'int', 'LookupPrivilegeValueW', 'ptr', 0, 'wstr', $sPrivilege, 'ptr', DllStructGetPtr($tLUID))

	If (@error) Or ($Ret[0] = 0) Then
		Return SetError(1, 0, 0)
	EndIf
	Return $tLUID
EndFunc   ;==>_WinAPI_LookupPrivilegeValue

; #FUNCTION# ====================================================================================================================
; Name...........: _WinAPI_LookupPrivilegeName
; Description....: Retrieves the name that corresponds to the privilege by a specified locally unique identifier (LUID).
; Syntax.........: _WinAPI_LookupPrivilegeName ( $tLUID )
; Parameters.....: $tLUID  - $tagLUID structure that specifies the LUID by which the privilege is known on the target system.
; Return values..: Success - The string that represents the privilege name. For example, "SeSecurityPrivilege".
;                  Failure - Empty string and sets the @error flag to non-zero.
; Author.........: Yashied
; Modified.......:
; Remarks........: None
; Related........:
; Link...........: @@MsdnLink@@ LookupPrivilegeName
; Example........: Yes
; ===============================================================================================================================

Func _WinAPI_LookupPrivilegeName($tLUID)

	$tData = DllStructCreate('wchar[128]')
	Local $Ret = DllCall('advapi32.dll', 'int', 'LookupPrivilegeNameW', 'ptr', 0, 'ptr', DllStructGetPtr($tLUID), 'ptr', DllStructGetPtr($tData), 'dword*', 128)

	If (@error) Or ($Ret[0] = 0) Then
		Return SetError(1, 0, '')
	EndIf
	Return DllStructGetData($tData, 1)
EndFunc   ;==>_WinAPI_LookupPrivilegeName

; #FUNCTION# ====================================================================================================================
; Name...........: _WinAPI_OpenProcessToken
; Description....: Opens the access token associated with a process.
; Syntax.........: _WinAPI_OpenProcessToken ( $iAccess [, $hProcess] )
; Parameters.....: $iAccess  - Access mask that specifies the requested types of access to the access token. This parameter can be
;                              one or more of the following values.
;
;                              $TOKEN_ADJUST_DEFAULT
;                              $TOKEN_ADJUST_GROUPS
;                              $TOKEN_ADJUST_PRIVILEGES
;                              $TOKEN_ADJUST_SESSIONID
;                              $TOKEN_ASSIGN_PRIMARY
;                              $TOKEN_DUPLICATE
;                              $TOKEN_EXECUTE
;                              $TOKEN_IMPERSONATE
;                              $TOKEN_QUERY
;                              $TOKEN_QUERY_SOURCE
;                              $TOKEN_READ
;                              $TOKEN_WRITE
;                              $TOKEN_ALL_ACCESS
;
;                  $hProcess - Handle to the process whose access token is opened. If this parameter is 0, will use the current process.
; Return values..: Success   - Handle that identifies the newly opened access token.
;                  Failure   - 0 and sets the @error flag to non-zero.
; Author.........: Yashied
; Modified.......:
; Remarks........: Close the access token handle returned through this function by calling _WinAPI_FreeHandle().
; Related........:
; Link...........: @@MsdnLink@@ OpenProcessToken
; Example........: Yes
; ===============================================================================================================================

Func _WinAPI_OpenProcessToken($iAccess, $hProcess = 0)

	If Not $hProcess Then
		$hProcess = _WinAPI_GetCurrentProcess()
	EndIf

	Local $Ret = DllCall('advapi32.dll', 'int', 'OpenProcessToken', 'ptr', $hProcess, 'dword', $iAccess, 'ptr*', 0)

	If (@error) Or ($Ret[0] = 0) Then
		Return SetError(1, 0, 0)
	EndIf
	Return $Ret[3]
EndFunc   ;==>_WinAPI_OpenProcessToken

; #FUNCTION# ====================================================================================================================
; Name...........: _WinAPI_AdjustTokenPrivileges
; Description....: Enables or disables privileges in the specified access token.
; Syntax.........: _WinAPI_AdjustTokenPrivileges ( $hToken, $aPrivileges, $iState )
; Parameters.....: $hToken      - Handle to the access token that contains the privileges to be modified. The handle must have
;                                 $TOKEN_ADJUST_PRIVILEGES and $TOKEN_QUERY accesses to the token.
;                  $aPrivileges - The variable that specifies a privileges. If this parameter is (-1), the function disables of the token's
;                                 privileges and ignores the $iState parameter. $aPrivileges can be one of the following types.
;
;                                 Single privileges constants ($SE_...).
;                                 1D array of $SE_... constants.
;                                 2D array of $SE_... constants and their attributes (see $iState).
;
;                                 [0][0] - Privilege
;                                 [0][1] - Attribute
;                                 [n][0] - Privilege
;                                 [n][1] - Attribute
;
;                  $iState      - The privilege attribute. If $aPrivileges parameter is 1D array, $iState applied to the entire
;                                 array. If $aPrivileges parameter is (-1) or 2D array, the function ignores this parameter and will
;                                 use the attributes specified in the array. This parameter can be one of the following values.
;
;                                 0 - The privilege is disabled.
;                                 1 - The privilege is enabled.
;                                 2 - The privilege is enabled by default.
;
; Return values..: Success      - If $aPrivileges is a single $SE_... constant, returns a previous privilege attribute (0 or 1),
;                                 otherwise always returns 1. To determine whether the function adjusted all of the specified privileges,
;                                 check @extended flag, which returns one of the following values when the function succeeds:
;
;                                 0 - The function adjusted all specified privileges.
;                                 1 - The token does not have one or more of the privileges specified in the $aPrivileges parameter.
;
;                  Failure      - 0 and sets the @error flag to non-zero.
; Author.........: Yashied
; Modified.......:
; Remarks........: This function cannot add new privileges to the access token. It can only enable or disable the token's
;                  existing privileges.
; Related........:
; Link...........: @@MsdnLink@@ AdjustTokenPrivileges
; Example........: Yes
; ===============================================================================================================================

Func _WinAPI_AdjustTokenPrivileges($hToken, $aPrivileges, $iState)

	Switch $iState
		Case 0, 1, 2

		Case Else
			Return SetError(1, 0, 0)
	EndSwitch

	Local $tLUID, $tPrivileges = 0, $tPrev = 0, $iPrivileges = $aPrivileges, $Global = 0, $Result = 1
	Local $Struct = 'dword;dword;long;dword'

	If $aPrivileges = -1 Then
		$Global = 1
	Else
		If Not IsArray($aPrivileges) Then
			Dim $aPrivileges[1][2] = [[$iPrivileges, $iState]]
			$tPrev = DllStructCreate($Struct)
			If @error Then
				Return SetError(1, 0, 0)
			EndIf
		Else
			If Not UBound($aPrivileges, 2) Then
				Dim $aPrivileges[UBound($iPrivileges)][2]
				For $i = 0 To UBound($iPrivileges) - 1
					$aPrivileges[$i][0] = $iPrivileges[$i]
					$aPrivileges[$i][1] = $iState
				Next
			EndIf
		EndIf
		For $i = 1 To UBound($aPrivileges) - 1
			$Struct &= ';dword;long;dword'
		Next
		$tPrivileges = DllStructCreate($Struct)
		If @error Then
			Return SetError(1, 0, 0)
		EndIf
		DllStructSetData($tPrivileges, 1, UBound($aPrivileges))
		For $i = 0 To UBound($aPrivileges) - 1
			$tLUID = _WinAPI_LookupPrivilegeValue($aPrivileges[$i][0])
			If @error Then
				Return SetError(1, 0, 0)
			EndIf
			DllStructSetData($tPrivileges, 3 * $i + 2, DllStructGetData($tLUID, 1))
			DllStructSetData($tPrivileges, 3 * $i + 3, DllStructGetData($tLUID, 2))
			DllStructSetData($tPrivileges, 3 * $i + 4, $aPrivileges[$i][1])
		Next
	EndIf

	Local $Ret = DllCall('advapi32.dll', 'int', 'AdjustTokenPrivileges', 'ptr', $hToken, 'int', $Global, 'ptr', DllStructGetPtr($tPrivileges), 'dword', DllStructGetSize($tPrev), 'ptr', DllStructGetPtr($tPrev), 'dword*', 0)

	If (@error) Or ($Ret[0] = 0) Then
		Return SetError(1, 0, 0)
	EndIf
	If IsDllStruct($tPrev) Then
		$Result = DllStructGetData($tPrev, 4)
	EndIf
	Return SetError(0, _WinAPI_GetLastError(), $Result)
EndFunc   ;==>_WinAPI_AdjustTokenPrivileges
 

Medic84

Омега
Команда форума
Администратор
Сообщения
1,590
Репутация
341
А собственно что это дает? Получить скрипту полные права как я полагаю?
 
Верх