原理简介
1>通过OpenProcessToken获得与进程相关联的访问令牌。
2>通过LookupPrivilegeValue函数检索指定系统上使用的本地唯一标识符(LUID),以本地表示指定的权限名称。
3>通过AdjustTokenPrivileges函数启用或禁用指定访问令牌中的权限。
4>通过InitiateSystemShutdownEx启动指定计算机的关机和可选重新启动,并可选地记录关机原因。
OpenProcessToken Function
The OpenProcessToken function opens the access token associated with a process.
Syntax
BOOL WINAPI OpenProcessToken( __in HANDLE ProcessHandle, __in DWORD DesiredAccess, __out PHANDLE TokenHandle );Parameters
ProcessHandle
A handle to the process whose access token is opened. The process must have the PROCESS_QUERY_INFORMATION access permission.
DesiredAccess
Specifies an access mask that specifies the requested types of access to the access token. These requested access types are compared with the discretionary access control list (DACL) of the token to determine which accesses are granted or denied.
For a list of access rights for access tokens, see Access Rights for Access-Token Objects.
TokenHandle
A pointer to a handle that identifies the newly opened access token when the function returns.
Return Value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
Close the access token handle returned through the TokenHandle parameter by calling CloseHandle.
Requirements
Client Requires Windows Vista, Windows XP, or Windows 2000 Professional. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Winbase.h; include Windows.h.
Library Use Advapi32.lib.
DLL Requires Advapi32.dll.
LookupPrivilegeValue Function
The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name.
Syntax
BOOL WINAPI LookupPrivilegeValue( __in_opt LPCTSTR lpSystemName, __in LPCTSTR lpName, __out PLUID lpLuid );Parameters
lpSystemName
A pointer to a null-terminated string that specifies the name of the system on which the privilege name is retrieved. If a null string is specified, the function attempts to find the privilege name on the local system.
lpName
A pointer to a null-terminated string that specifies the name of the privilege, as defined in the Winnt.h header file. For example, this parameter could specify the constant, SE_SECURITY_NAME, or its corresponding string, "SeSecurityPrivilege".
lpLuid
A pointer to a variable that receives the LUID by which the privilege is known on the system specified by the lpSystemName parameter.
Return Value
If the function succeeds, the function returns nonzero.
If the function fails, it returns zero. To get extended error information, call GetLastError.
Remarks
The LookupPrivilegeValue function supports only the privileges specified in the Defined Privileges section of Winnt.h. For a list of values, see Privilege Constants.
Example Code
For an example that uses this function, see Enabling and Disabling Privileges.
Requirements
Client Requires Windows Vista, Windows XP, or Windows 2000 Professional. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Winbase.h; include Windows.h.
Library Use Advapi32.lib.
DLL Requires Advapi32.dll.
Unicode Implemented as LookupPrivilegeValueW (Unicode) and LookupPrivilegeValueA (ANSI).
Privilege Constants
Privileges determine the type of system operations that a user account can perform. An administrator assigns privileges to user and group accounts. Each user's privileges include those granted to the user and to the groups to which the user belongs.
The functions that get and adjust the privileges in an access token use the locally unique identifier (LUID) type to identify privileges. Use the LookupPrivilegeValue function to determine the LUID on the local system that corresponds to a privilege constant. Use the LookupPrivilegeName function to convert a LUID to its corresponding string constant.
The operating system represents a privilege by using the string that follows "User Right" in the Description column of the following table. The operating system displays the user right strings in the Policy column of the User Rights Assignment node of the Local Security Settings Microsoft Management Console (MMC) snap-in.
Remarks
Privilege constants are defined as strings in Winnt.h. For example, the SE_AUDIT_NAME constant is defined as "SeAuditPrivilege".
Requirements
Client Requires Windows Vista, Windows XP, or Windows 2000 Professional. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Winnt.h.
AdjustTokenPrivileges Function
The AdjustTokenPrivileges function enables or disables privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access.
Syntax
BOOL WINAPI AdjustTokenPrivileges( __in HANDLE TokenHandle, __in BOOL DisableAllPrivileges, __in_opt PTOKEN_PRIVILEGES NewState, __in DWORD BufferLength, __out_opt PTOKEN_PRIVILEGES PreviousState, __out_opt PDWORD ReturnLength );Parameters
TokenHandle
A handle to the access token that contains the privileges to be modified. The handle must have TOKEN_ADJUST_PRIVILEGES access to the token. If the PreviousState parameter is not NULL, the handle must also have TOKEN_QUERY access.
DisableAllPrivileges
Specifies whether the function disables all of the token's privileges. If this value is TRUE, the function disables all privileges and ignores the NewState parameter. If it is FALSE, the function modifies privileges based on the information pointed to by the NewState parameter.
NewState
A pointer to a TOKEN_PRIVILEGES structure that specifies an array of privileges and their attributes. If the DisableAllPrivileges parameter is FALSE, the AdjustTokenPrivileges function enables, disables, or removes these privileges for the token. The following table describes the action taken by the AdjustTokenPrivileges function, based on the privilege attribute.
Value Meaning SE_PRIVILEGE_ENABLED
The function enables the privilege.
SE_PRIVILEGE_REMOVED
The privilege is removed from the list of privileges in the token. The other privileges in the list are reordered to remain contiguous.
SE_PRIVILEGE_REMOVED supersedes SE_PRIVILEGE_ENABLED.
Because the privilege has been removed from the token, attempts to reenable the privilege result in the warning ERROR_NOT_ALL_ASSIGNED as if the privilege had never existed.
Attempting to remove a privilege that does not exist in the token results in ERROR_NOT_ALL_ASSIGNED being returned.
Privilege checks for removed privileges result in STATUS_PRIVILEGE_NOT_HELD. Failed privilege check auditing occurs as normal.
The removal of the privilege is irreversible, so the name of the removed privilege is not included in the PreviousState parameter after a call to AdjustTokenPrivileges.
Windows XP SP1 and Windows 2000: The function cannot remove privileges. This value is not supported.None
The function disables the privilege.
If DisableAllPrivileges is TRUE, the function ignores this parameter.
BufferLength
Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be zero if the PreviousState parameter is NULL.
PreviousState
A pointer to a buffer that the function fills with a TOKEN_PRIVILEGES structure that contains the previous state of any privileges that the function modifies. That is, if a privilege has been modified by this function, the privilege and its previous state are contained in the TOKEN_PRIVILEGES structure referenced by PreviousState. If the PrivilegeCount member of TOKEN_PRIVILEGES is zero, then no privileges have been changed by this function. This parameter can be NULL.
If you specify a buffer that is too small to receive the complete list of modified privileges, the function fails and does not adjust any privileges. In this case, the function sets the variable pointed to by the ReturnLength parameter to the number of bytes required to hold the complete list of modified privileges.
ReturnLength
A pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL.
Return Value
If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call GetLastError, which returns one of the following values when the function succeeds:
Return code Description ERROR_SUCCESS
The function adjusted all specified privileges.
ERROR_NOT_ALL_ASSIGNED
The token does not have one or more of the privileges specified in the NewState parameter. The function may succeed with this error value even if no privileges were adjusted. The PreviousState parameter indicates the privileges that were adjusted.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
The AdjustTokenPrivileges function cannot add new privileges to the access token. It can only enable or disable the token's existing privileges. To determine the token's privileges, call the GetTokenInformation function.
The NewState parameter can specify privileges that the token does not have, without causing the function to fail. In this case, the function adjusts the privileges that the token does have and ignores the other privileges so that the function succeeds. Call the GetLastError function to determine whether the function adjusted all of the specified privileges. The PreviousState parameter indicates the privileges that were adjusted.
The PreviousState parameter retrieves a TOKEN_PRIVILEGES structure that contains the original state of the adjusted privileges. To restore the original state, pass the PreviousState pointer as the NewState parameter in a subsequent call to the AdjustTokenPrivileges function.
Example Code
For an example that uses this function, see Enabling and Disabling Privileges.
Requirements
Client Requires Windows Vista, Windows XP, or Windows 2000 Professional. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Winbase.h; include Windows.h.
Library Use Advapi32.lib.
DLL Requires Advapi32.dll.
See Also
InitiateSystemShutdownEx Function
Initiates a shutdown and optional restart of the specified computer, and optionally records the reason for the shutdown.
Syntax
BOOL WINAPI InitiateSystemShutdownEx( __in_opt LPTSTR lpMachineName, __in_opt LPTSTR lpMessage, __in DWORD dwTimeout, __in BOOL bForceAppsClosed, __in BOOL bRebootAfterShutdown, __in DWORD dwReason );Parameters
lpMachineName
The network name of the computer to be shut down. If lpMachineName is NULL or an empty string, the function shuts down the local computer.
lpMessage
The message to be displayed in the shutdown dialog box. This parameter can be NULL if no message is required.
Windows Server 2003 and Windows XP: This string is also stored as a comment in the event log entry.Windows Server 2003 and Windows XP SP1: The string is limited to 3072 TCHARs.dwTimeout
The length of time that the shutdown dialog box should be displayed, in seconds. While this dialog box is displayed, shutdown can be stopped by the AbortSystemShutdown function.
If dwTimeout is not zero, InitiateSystemShutdownEx displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, displays the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows in the system. The dialog box can be moved but not closed. A timer counts down the remaining time before shutdown.
If dwTimeout is zero, the computer shuts down without displaying the dialog box, and the shutdown cannot be stopped by AbortSystemShutdown.
Windows Server 2003 and Windows XP SP1: The time-out value is limited to MAX_SHUTDOWN_TIMEOUT seconds.Windows Server 2003 and Windows XP SP1: If the computer to be shut down is a Terminal Services server, the system displays a dialog box to all local and remote users warning them that shutdown has been initiated. The dialog box includes who requested the shutdown, the display message (see lpMessage), and how much time there is until the server is shut down.bForceAppsClosed
If this parameter is TRUE, applications with unsaved changes are to be forcibly closed. If this parameter is FALSE, the system displays a dialog box instructing the user to close the applications.
bRebootAfterShutdown
If this parameter is TRUE, the computer is to restart immediately after shutting down. If this parameter is FALSE, the system flushes all caches to disk and safely powers down the system.
dwReason
The reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes.
If this parameter is zero, the default is an undefined shutdown that is logged as "No title for this reason could be found". By default, it is also an unplanned shutdown. Depending on how the system is configured, an unplanned shutdown triggers the creation of a file that contains the system state information, which can delay shutdown. Therefore, do not use zero for this parameter.
Windows XP/2000: System state information is not saved during an unplanned system shutdown. The preceding text does not apply.Return Value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
To shut down the local computer, the calling thread must have the SE_SHUTDOWN_NAME privilege. To shut down a remote computer, the calling thread must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers. For more information, see Running with Special Privileges.
Common reasons for failure include an invalid or inaccessible computer name or insufficient privilege. The error ERROR_SHUTDOWN_IN_PROGRESS is returned if a shutdown is already in progress on the specified computer. The error ERROR_NOT_READY can be returned if fast-user switching is enabled but no user is logged on.
A non-zero return value does not mean the logoff was or will be successful. The shutdown is an asynchronous process, and it can occur long after the API call has returned, or not at all. Even if the timeout value is zero, the shutdown can still be aborted by applications, services, or even the system. The non-zero return value indicates that the validation of the rights and parameters was successful and that the system accepted the shutdown request.
When this function is called, the caller must specify whether or not applications with unsaved changes should be forcibly closed. If the caller chooses not to force these applications to close and an application with unsaved changes is running on the console session, the shutdown will remain in progress until the user logged into the console session aborts the shutdown, saves changes, closes the application, or forces the application to close. During this period the shutdown may not be aborted except by the console user, and another shutdown may not be initiated.
Note that calling this function with the value of the bForceAppsClosed parameter set to TRUE avoids this situation. Remember that doing this may result in loss of data.
Windows Server 2003 and Windows XP: If the computer is locked and the bForceAppsClosed parameter is FALSE, the last error code is ERROR_MACHINE_LOCKED. If the system is not ready to handle the request, the last error code is ERROR_NOT_READY. The application should wait a short while and retry the call.Requirements
Client Requires Windows Vista, Windows XP, or Windows 2000 Professional. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Winreg.h; include Windows.h.
Library Use Advapi32.lib.
DLL Requires Advapi32.dll.
Unicode Implemented as InitiateSystemShutdownExW (Unicode) and InitiateSystemShutdownExA (ANSI).
System Shutdown Reason Codes
The shutdown reason codes are used by the ExitWindowsEx and InitiateSystemShutdownEx functions in the dwReason parameter.
A maximum of MAX_NUM_REASONS reason codes will be processed by the system. MAX_NUM_REASONS is defined in reason.h.
The following are the major reason flags. They indicate the general issue type.
Constant/value Description SHTDN_REASON_MAJOR_APPLICATION
0x00040000Application issue.
SHTDN_REASON_MAJOR_HARDWARE
0x00010000Hardware issue.
SHTDN_REASON_MAJOR_LEGACY_API
0x00070000The InitiateSystemShutdown function was used instead of InitiateSystemShutdownEx.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM
0x00020000Operating system issue.
SHTDN_REASON_MAJOR_OTHER
0x00000000Other issue.
SHTDN_REASON_MAJOR_POWER
0x00060000Power failure.
SHTDN_REASON_MAJOR_SOFTWARE
0x00030000Software issue.
SHTDN_REASON_MAJOR_SYSTEM
0x00050000System failure.
The following are the minor reason flags. They modify the specified major reason flag. You can use any minor reason in conjunction with any major reason, but some combinations do not make sense.
The following optional flags provide additional information about the event.
Remarks
The following combinations are recognized by the system. The table indicates the string that is displayed in the Shutdown Event Tracker, and provides a more detailed description. The default string is "No title for this reason could be found."
Combination Description SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_HUNG "Application: Unresponsive" An unplanned restart or shutdown to troubleshoot an unresponsive application.
SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION | SHTDN_REASON_FLAG_PLANNED "Application: Installation (Planned)" A planned restart or shutdown to perform application installation.
SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_MAINTENANCE "Application: Maintenance (Unplanned)" An unplanned restart or shutdown to service an application.
SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_MAINTENANCE SHTDN_REASON_FLAG_PLANNED "Application: Maintenance (Planned)" A planned restart or shutdown to perform planned maintenance on an application.
SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_UNSTABLE "Application: Unstable" An unplanned restart or shutdown to troubleshoot an unstable application.
SHTDN_REASON_MAJOR_HARDWARE | SHTDN_REASON_MINOR_INSTALLATION "Hardware: Installation (Unplanned)" An unplanned restart or shutdown to begin or complete hardware installation.
SHTDN_REASON_MAJOR_HARDWARE | SHTDN_REASON_MINOR_INSTALLATION | SHTDN_REASON_FLAG_PLANNED "Hardware: Installation (Planned)" A planned restart or shutdown to begin or complete hardware installation.
SHTDN_REASON_MAJOR_HARDWARE | SHTDN_REASON_MINOR_MAINTENANCE "Hardware: Maintenance (Unplanned)" An unplanned restart or shutdown to service hardware on the system.
SHTDN_REASON_MAJOR_HARDWARE | SHTDN_REASON_MINOR_MAINTENANCE | SHTDN_REASON_FLAG_PLANNED "Hardware: Maintenance (Planned)" A planned restart or shutdown to service hardware on the system.
SHTDN_REASON_MAJOR_LEGACY_API "Legacy API shutdown" This shutdown was initiated by the legacy InitiateSystemShutdown function. Applications should use the InitiateSystemShutdownEx function.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_HOTFIX "Operating System: Hot fix (Unplanned)" An unplanned restart or shutdown to install a hot fix.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_HOTFIX | SHTDN_REASON_FLAG_PLANNED "Operating System: Hot fix (Planned)" A planned restart or shutdown to install a hot fix.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_RECONFIG "Operating System: Reconfiguration (Unplanned)" An unplanned restart or shutdown to change the operating system configuration.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_RECONFIG | SHTDN_REASON_FLAG_PLANNED "Operating System: Reconfiguration (Planned)" A planned restart or shutdown to change the operating system configuration.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_SECURITYFIX "Operating System: Security fix (Unplanned)" An unplanned restart or shutdown to install a security patch.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_SECURITYFIX | SHTDN_REASON_FLAG_PLANNED "Operating System: Security fix (Planned)" A planned restart or shutdown to install a security patch.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_SERVICEPACK | SHTDN_REASON_FLAG_PLANNED "Operating System: Service pack (Planned)" A planned restart or shutdown to install a service pack.
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED "Operating System: Upgrade (Planned)" A planned restart or shutdown to upgrade the operating system configuration.
SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER "Other (Unplanned)" An unplanned shutdown or restart.
SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED "Other (Planned)" A planned shutdown or restart.
SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_HUNG "Other Failure: System Unresponsive" The system became unresponsive.
SHTDN_REASON_MAJOR_POWER | SHTDN_REASON_MINOR_CORDUNPLUGGED "Power Failure: Cord Unplugged" The computer was unplugged.
SHTDN_REASON_MAJOR_POWER | SHTDN_REASON_MINOR_ENVIRONMENT "Power Failure: Environment" There was a power outage.
SHTDN_REASON_MAJOR_SYSTEM | SHTDN_REASON_MINOR_BLUESCREEN "System Failure: Stop error" The computer displayed a blue screen crash event.
SHTDN_REASON_MAJOR_SYSTEM | SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY "Loss of network connectivity (Unplanned)" The computer needs to be shut down due to a network connectivity issue.
SHTDN_REASON_MAJOR_SYSTEM | SHTDN_REASON_MINOR_SECURITY "Security issue" The computer needs to be shut down due to a security issue.
You can also define your own shutdown reasons and add them to the registry. Each reason code should be stored as a registry value in the following key:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Reliability\UserDefined\<default_system_language_ID>
This key contains value names of the following form: xxxxx;nnn;nnnnn. The semicolons delimit the components of a value name.
xxxxx
One to five of the following control flags (no other characters can be used).
Flag Description P Planned shutdown; otherwise, an unplanned shutdown. C A comment is required. This flag must be used with S.
B An ID is required. This flag must be used with D.
S Display the expected shutdown dialog box. Either S, D, or both S and D must be used.
D Display the unexpected shutdown dialog box. Either S, D, or both S and D must be used.
The order in which the flags are used is not important. For example, CSP indicates a planned shutdown where the expected shutdown dialog box is displayed, and a comment is required.
nnn
Major reason. This component must be a number in the range 64-255. The range 0-63 is reserved for use by the system.
nnnnn
Minor reason. This component must be in the range 0-65535.
Custom reasons are sorted in the user interface by major reason number, then by minor reason number. No two custom reasons can use the same major and minor reasons, unless one is planned and the other is unplanned. Otherwise, the system will use the first instance and ignore the others.
The data for each registry value is two strings, separated by \n\r. The first string is a title string to be displayed in the shutdown dialog box, and written to the event log. The maximum size is 64 characters. Title strings must be unique. Custom titles cannot match the standard titles defined by the system, or another custom title. The second string is a description string to be displayed in the shutdown dialog box; it is optional. The maximum size is 256 characters.
Requirements
Client Requires Windows Vista or Windows XP. Server Requires Windows Server 2008 or Windows Server 2003. Header Declared in Reason.h.
int ShuntDownType;//关机类型
BOOL DoublePathDelayShuntDownDlg::OnDelayShuntDownWindows()
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken))
{
return FALSE;
}
LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken,FALSE,&tkp,0,(PTOKEN_PRIVILEGES)NULL,0);
if (GetLastError()!=ERROR_SUCCESS)
{
return FALSE;
}
switch (ShuntDownType)
{
case 0:
if (!InitiateSystemShutdownEx(NULL,_T("送君茉莉, 愿君莫离。正在关闭IPC!"),5,TRUE,FALSE, SHTDN_REASON_MAJOR_APPLICATION))
{
return FALSE;
}
break;
case 1:
if (!InitiateSystemShutdownEx(NULL, _T("送君茉莉, 愿君莫离。正在重启IPC!"), 5,FALSE, TRUE, SHTDN_REASON_MAJOR_APPLICATION))
{
return FALSE;
}
break;
case 2:
if (!InitiateSystemShutdownEx(NULL, _T("送君茉莉, 愿君莫离。正在强启IPC!"), 5, TRUE, TRUE, SHTDN_REASON_MAJOR_APPLICATION))
{
return FALSE;
}
break;
default:
break;
}
return TRUE;
}