Detailed explanation of Windows UAC permissions and sharing of several problems caused by unequal permissions

Table of contents

1. What is UAC?

2. Why did Microsoft design UAC?

3. Standard user rights and administrator rights

4. With which permission does the program run? What factors are involved?

4.1. Set the properties for the program to run with administrator privileges

4.2. Type of currently logged in user

5. Case 1 - Unable to start the installation package program in the corporate WeChat chat box

6. Case 2 - The problem that you may encounter when using Windbg is that the permissions are not equal, causing the operation to fail.

6.1. Windbg fails to attach to the target process

6.2. There is no response after dragging the dump file to Windbg running with administrator privileges.

7. Case 3 - When you double-click the desktop shortcut to start a program, the window of the already started program does not pop up automatically.

8. Other issues related to administrator rights

8.1. How to start a program with administrator rights?

8.2. Administrator permissions cannot be set for programs that start automatically at boot.


Summary of the development of common functions of VC++ (list of column articles, welcome to subscribe, continuous updates...)icon-default.png?t=N7T8https://blog.csdn.net/chenlycly/article/details/124272585 C++ software anomaly troubleshooting series of tutorials from entry to mastery (list of column articles, welcome to subscribe, continuous updates...)icon-default.png?t=N7T8https://blog.csdn. net/chenlycly/article/details/125529931C++ software analysis tools from entry to mastery case collection (column article, continuously updated...)icon-default.png?t=N7T8https: //blog.csdn.net/chenlycly/article/details/131405795C/C++ basics and advanced (column article, continuously updated...)icon-default.png?t=N7T8https://blog.csdn.net/chenlycly/category_11931267.htmlOpen source components and database technology (column article, continuously updated...)icon-default.png?t=N7T8 https://blog.csdn.net/chenlycly/category_12458859.htmlNetwork programming and network problem sharing (column article, continuously updated...)icon-default.png?t=N7T8 https://blog.csdn.net/chenlycly/category_2276111.html       In Windows systems, when we use software, we often encounter operations that fail due to the inconsistency between administrator rights and standard user rights. Many people are confused about the problem. Today we will talk about the related UAC permission control in detail and give specific examples of the problem for everyone to learn from or refer to.


       Here, I would like to recommend my two popular and best-selling columns:

Column 1: (This column has nearly 350 subscriptions, has strong practical reference value, and is widely praised!)

C++ software anomaly troubleshooting series of tutorials from entry to mastery (list of column articles, welcome to subscribe, continuous updates...)icon-default.png?t=N7T8https://blog.csdn.net/chenlycly/ article/details/125529931

Based on the project practice of C++ software exception troubleshooting in recent years, this column systematically summarizes the common causes of C++ software exceptions and common ideas and methods for troubleshooting C++ software exceptions. It also details the debugging methods and methods of C++ software. The method gives specific examples of practical problem analysis in the form of pictures and texts, leading everyone to gradually master the related technologies of C++ software debugging and exception troubleshooting, which is suitable for basic introduction. Level and related C++ developers who want to improve their technology!

The articles in the column are all summarized through actual project operations (a large amount of anomaly troubleshooting materials and cases have been accumulated through actual project operations), and have strong practical reference value! The column articles are still being updated, and the number of articles is expected to be updated to more than 200!

专栏2: 

Summary of VC++ common function developmenticon-default.png?t=N7T8https://blog.csdn.net/chenlycly/article/details/124272585

This column displays the commonly used functions in C++ development practice for more than 10 years in high-quality code, and explains in detail the implementation details of related functions. The quality and stability of these commonly used codes are guaranteed and can be used directly, which can effectively solve the problems encountered in the C++ software development process.

专栏3

C/C++ Basics and Advancedicon-default.png?t=N7T8https://blog.csdn.net/chenlycly/category_11931267.html

Based on many years of practical development, this book summarizes and explains some basic and advanced content of C/C++, and expands and elaborates on relevant knowledge points in detail with pictures and texts! The column covers many aspects of the C/C++ field, and also gives common written interview questions in C/C++ and networking, and details commonly used debugging methods and techniques in Visual Studio!


1. What is UAC?

       UAC (User Account Control), User Account Control, is a new control mechanism introduced by Microsoft starting from Windows Vista. Its principle is to notify the user whether to use the application. Hard drive and system file authorization to prevent malicious programs (sometimes called "malware") from damaging your system.

The UAC user account control mechanism is mainly permission isolation to prevent low-privilege and low-security applications from obtaining high-level system permissions. The system pops up a UAC prompt box, asking the user to confirm whether to trust and run unknown and unsigned applications with administrator privileges.

       When running some programs that will affect system security, UAC will be automatically triggered, and the program can only run after the user confirms. For example, when you run an installation program (usually run with administrator rights) or open an unverified program, a UAC prompt box similar to the following will pop up: (Double-click the QQ program that needs to be run with administrator rights in Win10 system Installation package program as an example)

The program can continue to run only after the user confirms.

       This pop-up box prompts the user that the program may modify the current computer, but this prompt does not seem to be of much use to most users. For ordinary users, not only is it useless, but it will also cause trouble (should it be allowed? Or not allowed?). And it keeps popping up boxes from time to time, which makes users very annoyed!

       Slightly more professional users may turn off UAC notifications. The specific method is to open the control panel and click "User Accounts" to enter the user account settings page:

Then click "Change User Account Control Settings" to go to the following page:

Pull the scroll bar all the way to turn off UAC notifications. After closing, the UAC prompt box will no longer pop up.

       Since everyone doesn’t like the UAC prompt box, why did Microsoft design such a weird thing?

2. Why did Microsoft design UAC?

        Many people have used Windows XP. When most people use Windows XP, they should use an account with administrator rights. In Microsoft's vision, ordinary users should use standard accounts. Why don’t people use standard accounts? Standard accounts in Windows XP may not even be able to install programs properly! No one is willing to switch to the administrator account in order to install a program, and then switch back to the standard user after the installation is completed.

       Of course, Microsoft also noticed this and designed the UAC system. The biggest difference between UAC and Windows XP user account permission management is that UAC is very flexible in controlling permissions. It defaults to all programs running with standard permissions (whether you are using an administrator account or a standard account). When you run a program that requires administrator permissions, UAC will come out and ask you, does this program require Administrator rights, do you want to continue, as follows:

If you allow it, UAC will escalate privileges and run the program with administrator privileges.

       In fact, judging from the original intention of the design of UAC, it not only avoids the direct use of the administrator account, which makes the permission control ineffective, but also solves the problem of standard users needing to frequently switch to the administrator account (possibly imitating the su privilege escalation in the Linux system) .

       But UAC under Windows is not smart at all. Even for operations such as copying files, it will even come over to ask you. Many users take the trouble to turn off UAC directly. Although Windows has made some changes and optimizations to UAC, UAC is still annoying. For example, the first time you open a program that requires administrator privileges, UAC will dutifully ask you if you want to elevate your privileges; the second time you open it, UAC will dutifully ask you if you want to elevate your privileges; the third time you open it, UAC will dutifully ask you if you want to elevate your privileges. If you turn it on, UAC will dutifully ask you if you want to increase your permissions... So everyone was unwilling and turned off UAC.

Some people even directly use Administrator as the super administrator user. When this user logs in, all programs run with administrator privileges by default, and UAC prompt boxes will not pop up for basically all operations.

       Users who have used Android phones know that there is a list of trusted programs in Android. Once added to this list, the system will not make unnecessary inquiries when running it again. There is no such thing in Windows UAC, because Microsoft people believe that if you want to create a trust list, then this list must be stored somewhere in the registry or hard disk, so that hackers can find ways to crack and modify this list. (Just like XP's password).

3. Standard user rights and administrator rights

       Windows has introduced the UAC permission control mechanism since the Vista system, which has strengthened the concept of administrator permissions and implemented stricter permission restrictions and security controls. For example, some permission-sensitive paths, such as C:\Program Files and C:\Windows\system32, require administrator rights to create files and write data to files under these paths. For another example, in the Windows system registry, if you want to write or modify content under the HKEY_LOCAL_MACHINE path, administrator rights are also required.

       There are two main types of program running permissions: standard user permissions and administrator permissions. There are many operations that require administrator rights, such as:

1) Only programs with administrator rights can perform write operations to system security-sensitive paths, such as creating files and copying files in system paths such as C:\Program Files, C:\Windows\system32, and writing to these paths. file to perform write operations.
2) Only programs with administrator rights can create or write to the system registry path HKEY_LOCAL_MACHINE. Programs without administrator rights can only perform write operations on the HKEY_CURRENT_USER path.
3) Only programs with administrator rights can register controls with the system (information must be written to the registry under the HKEY_LOCAL_MACHINE path).

       The installation package program generally installs the program to the C:\Program Files path by default. It needs to register the control with the system. These operations require administrator rights to perform, so the installation package program generally needs to be set to run with administrator rights. If the program is set to run with administrator privileges, a small shield icon will be displayed in the lower right corner of the program icon, as shown below:

Note that if you are logged in as the super administrator Administrator, you will not be able to see the small shield, because when the super administrator is logged in, all programs run with administrator privileges by default, regardless of whether the program is set to run with administrator privileges. .

       In addition, For programs running with standard user rights, if you want to perform operations that require administrator rights to perform normally, it will involve Asystem redirection problem. For detailed description, please refer to the article I wrote before:VC++ Windows7 and above systems Detailed explanation of administrator permissions and UAC virtualization (with source code)icon-default.png?t=N7T8https://blog.csdn.net/chenlycly/article/details/124096307

4. With which permission does the program run? What factors are involved?

        Whether the program runs with administrator privileges is mainly related to two factors. One is the type of user currently logged in to the system (standard user, administrator user, and super administrator user), and the other is whether the program is set to run with administrator privileges. Attributes. The following is based on the win10 system. There are some differences between the win10 system and the win7 system, but they are generally the same.

4.1. Set the properties for the program to run with administrator privileges

       How to set the attribute for a program to run with administrator privileges? For programs compiled with Visual Studio, it is relatively simple to set them up to run with administrator privileges. As long as the linker -> manifest file -> UAC execution level is set in the project properties of the exe main program, as shown below:

We just select the reguireAdministrator option. After setting this attribute, the program will automatically apply to the system to run with administrator privileges when it is started.

If you are currently logged in as an administrator user, the program will run directly with administrator privileges when it starts. If you are currently logged in as a standard user, a privilege escalation prompt box will pop up during startup, and you need to enter an administrator account and password to start the program.

       There is a detail issue here that needs attention. Previously, the Bang Brothers project team investigated a problem where the program settings to run with administrator privileges were invalid. Please refer to the article I wrote before:

Sharing the troubleshooting process for setting up the program to run with administrator privileges and invalid problemicon-default.png?t=N7T8https://blog.csdn.net/chenlycly/article/details/128158192

4.2. Type of currently logged in user

       In addition to setting the properties to run with administrator privileges, which permissions the program runs with is also related to the currently logged-in user.

4.2.1. Super administrator Administrator login

        If you use the Administrator super administrator to log in, the program will run with administrator privileges regardless of whether it is set to run with administrator privileges. The super administrator Administrator has the highest authority.

       In Windows systems, the super administrator Administrator is disabled by default and can be enabled by: right-clicking Computer->Management->System Tools->Local Users and Groups->Users-> Right-click Administrator ->Properties->Cancel account disabling:

Super administrators can be renamed in user management.

4.2.2. Administrator user login

       The administrators mentioned here are ordinary administrators, not super administrators. You can right-click the program and click "Run as administrator" in the pop-up right-click menu:

The program started in this way has administrator rights.

       If it is started directly by double-clicking or run through a desktop shortcut or start menu shortcut, with what permissions it is run, it depends on whether the program has the attribute of running with administrator permissions. If set, it will run with administrator rights; if not set, it will run with standard user rights.

4.2.3. Standard user login

       If you are currently logged in as a standard user, it depends on whether the program has the attribute to run with administrator privileges. If it is not configured, it will run with standard user rights; if it is configured to run with administrator rights, the following prompt box will pop up: (Double-click the program that requires administrator rights to run under standard user login The prompt box that pops up when QQ installs the package)

You need to enter the administrator account and password, and escalate to the administrator account before you can run it with administrator privileges. If you cancel the login of the administrator account, the program will fail to start.

       How to use code to determine whether a program is running with administrator privileges, please refer to my previous article:

VC++ determines whether the process is running with administrator privileges (source code attached)icon-default.png?t=N7T8https://blog.csdn.net/chenlycly/article/details/45419259       If the permissions of two programs (processes) are not equal, they may fail to operate with each other because the system does not allow two processes with different permissions to operate with each other. The following are some examples of problems that may be encountered in actual work for your reference. The following cases are all scenarios where an administrator user (non-super administrator Administrator) logs in.

5. Case 1 - Unable to start the installation package program in the corporate WeChat chat box

       Enterprise WeChat runs as a standard user by default. For example, if you double-click the desktop shortcut or click to run it from the start menu, it will run with standard user rights. One day I sent the latest installation package of the software to the enterprise WeChat group. After my colleagues received the file in the group, theydouble-clicked the installation package file directly in the enterprise WeChat chat box, but The following error message box pops up:

After receiving files in corporate WeChat, everyone is usually accustomed to double-clicking directly to view the file or start a program, but this time an error was reported when double-clicking. A colleague suspected that there was a problem with our software installation package and asked us what was going on. Judging from this screenshot, the title of the screenshot is the path of an enterprise WeChat, and then the prompt text is: Windows cannot access the specified device, path or file. You may not have the appropriate permissions to access this project.

       As developers, we are quite familiar with the issue of running permissions for programs like this, and we can probably tell what is going on at a glance. The current enterprise WeChat runs with standard user rights, while our software installation package is set to run with administrator rights. The rights of the two program processes are not equal, so the operation failed. Low privilege (standard user privileges) processes cannot start high privilege (administrator privileges) processes.

6. Case 2 - The problem that you may encounter when using Windbg is that the permissions are not equal, causing the operation to fail.

       When we used Windbg to statically analyze dump files and attach them to the target process for dynamic debugging, we also encountered the problem of permission asymmetry causing operation failure.

6.1. Windbg fails to attach to the target process

       The target program to be additionally debugged is currently running with administrator privileges. As for why it is running with administrator privileges, it may be that it is run with administrator privileges by right-clicking, or it may be that the program is automatically started after the installation package is installed ( The installation package is run with administrator privileges, and the programs it starts also inherit administrator privileges). The currently started Windbg runs with standard user rights (double-click the desktop shortcut to start).When attaching Windbg to a target program process running with administrator rights, the attachment fails. , as shown below:

Windbg with low privileges (standard user privileges) cannot be attached to a target program process with high privileges (administrator privileges).

       If Windbg is running with administrator privileges, it can be successfully attached to a process running with standard user privileges. This system allows it.​ 

6.2. There is no response after dragging the dump file to Windbg running with administrator privileges.

       One day, a colleague reported that a certain dump file could not be opened with Windbg. The specific phenomenon was,Drag the dump file on the disk into the already opened Windbg but nothing happened< /span>

        The effect when opening the dump file normally is as follows:

Colleagues suspect that the dump file is special. For example, the file is damaged and cannot be opened. This shouldn't be the case. The size of the dump file is non-zero, which is probably caused by the program's running permissions. It was confirmed that Windbg was run with administrator rights by right-clicking, and the dump file was dragged from the disk and ran in the explorer file explorer process, and the file explorer was Run with standard user rights. Because the Windbg process (run with administrator rights) and the explorer.exe file explorer process (run with standard user rights) have unequal rights, the system prohibits file drag and drop behavior, so there is no response when dragging it to Windbg.

7. Case 3 - When you double-click the desktop shortcut to start a program, the window of the already started program does not pop up automatically.

       Many programs only allow one program instance to be started (only one process can be run), unlike browser programs, which can start multiple programs (windows). Only one instance of the program is allowed to run. This is generally implemented.When the program starts, it will detect whether a program process has been started. If there is already a program process running and it is not the current process, it will automatically Exit the newly started process to ensure that only one instance of the program is running.

        It is assumed that the current program is already running and only one program instance is allowed to run, but we do not see the program window (maybe the program is minimized, or minimized to the tray area), and we are not sure whether the program is running. , we're going to double-click the desktop shortcut. At this time, because the program has been started before, it stands to reason that we should automatically pop up the window of the already running program . Our software code is indeed implemented in this way, but on certain occasions the window of the already running program still does not pop up.

       The scenario is like this: The already running program is automatically started after installing the software using the installation package. Because the installation package is run with administrator privileges, it is started. The programs that are started inherit administrator rights by default. The new process we start by double-clicking the desktop shortcut runs with standard permissions. When the program is initialized and run, it will detect whether the program is already running. It is indeed detected that the program is already running, and the main window of the already running program is found.. But it failed when calling the API function ShowWindow to show the window

       So I thought of checking the description of the API function ShowWindow on MSDN to see if I could print out the relevant values ​​and analyze why the function failed to be called. The description of the ShowWindow function on MSDN is as follows:

The return value of this function is of BOOL type, butThis return value only identifies the previous state of the window, and does not identify whether the ShowWindow function is executed successfully,You can only use the GetLastError function to find the reason why ShowWindow failed to execute by getting the LastError value

Some Windows APIs need to use the LastError value obtained by GetLastError to determine whether the execution was successful:

1) If the LastError value is 0, it means the execution was successful;

2) If the LastError value is not 0, it means that the execution failed, and the LastError value corresponds to the reason for the execution failure.

So add the following print:

BOOL bShowTargetWndSuccess = FALSE;
SetLastError(0);
::ShowWindow(hPrevWnd, SW_RESTORE);
dwLastError = GetLastError();
if ( dwLastError == 0 )
{
    // 窗口Show成功了
    bShowTargetWndSuccess = TRUE;
}
else
{
    // 窗口Show失败了,将API函数ShowWindow设置完后设置的LastError值打印出来
    char szLog[256] = { 0 };
    sprintf(szLog, "[CheckShowExsitingWnd] show target window failed, LastError = %d.", dwLastError);
    WriteLog(szLog);
}

Later, this problem reappeared. I found that the LastError value set when calling ShowWindow window Show failed was 5. Go to the error viewing tool that comes with VS to check the meaning of this value as follows:

Access is denied. It should be a permission issue that causes ShowWindow to fail to execute. The already running program process is started automatically after the installation package is installed, so it has administrator rights, while the newly started process is started by double-clicking the desktop shortcut, so it runs with standard user rights. The newly started process detects that the program is already running. The new process with low permissions (standard user permissions) wants to show its window in the started process with high permissions (administrator permissions). The system is It is not allowed, so ShowWindow execution fails.

       The current way to avoid it is that when we find that ShowWindow execution fails (determine the LastError value), a prompt box will pop up directly, but the started program window will still not pop up. , this is just a way to avoid problems, and the user experience is not good.

       The best solution is, when the installation package automatically starts the process after the installation is completed, start the program directly with standard user rights a>, so that there is no problem of unequal permissions, and the window of the already running program can be automatically popped up.

       Compared with Enterprise WeChat, Enterprise WeChat is no problem in the same scenario. Enterprise WeChat can automatically pop up the window of the already running program. We wrote code to detect whether the program process is running with administrator privileges (The code to determine whether the program process is running with administrator privileges will be given later in this article) , and found that the Enterprise WeChat process that was automatically started after the Enterprise WeChat installation package was executed was run with standard user rights. The Enterprise WeChat installation package must be run with administrator rights (The installation package may need to write content to the system's sensitive path, write the registry, and register controls, so generally the installation package needs to be Run with administrator privileges), as can be seen from the icon of the Enterprise WeChat installation package program. There is a small shield in the lower right corner of the icon:

The installation package process running with administrator rights starts the main program of Enterprise WeChat with standard user rights. That is, the main program of Enterprise WeChat that is started runs with standard user rights.

       How to start a process running with standard user rights? Remember the open source tool Process Hacker that I talked about before? We use Process Hacker when troubleshooting problems on a daily basis. We have previously seen the function of creating processes with standard user rights in the menu. In the tool's menu bar, hacker -> Run as limited user...:

Because the source code of Process Hacker is open source, if you need this function, you can go to the source code to find the source code implementation corresponding to the menu item. Here is part of the Process Hacker open source code to create a process with standard user permissions:

NTSTATUS status;
HANDLE tokenHandle;
HANDLE newTokenHandle;

if (NT_SUCCESS(status = PhOpenProcessToken(
    NtCurrentProcess(),
    TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ADJUST_GROUPS |
    TOKEN_ADJUST_DEFAULT | READ_CONTROL | WRITE_DAC,
    &tokenHandle
    )))
{
    if (NT_SUCCESS(status = PhFilterTokenForLimitedUser(
        tokenHandle,
        &newTokenHandle
        )))
    {
        status = PhCreateProcessWin32(
			NULL,
			(PWSTR)runFileDlg->lpszFile,
			NULL,
			NULL,
			0,
			newTokenHandle,
			NULL,
			NULL
			);

        NtClose(newTokenHandle);
    }

    NtClose(tokenHandle);
}

If you want to implement this function, you need to copy the complete source code from the Process Hacker open source code.

We have also talked about a similar tool calledProcess Explorer. We use this tool more every day and it also has similar functions. , but this tool is not open source, and we cannot see its source code implementation.

8. Other issues related to administrator rights

        There are also other issues related to administrator rights, such as how to start a program with administrator rights through code, and setting a program to run with administrator rights when the program cannot be started automatically at boot. Let's take a closer look at these two typical problems.

8.1. How to start a program with administrator rights?

       A program with administrator rights will have other programs started by it with administrator rights by default. That is, the child process will inherit the administrator running rights of the parent process by default. In the same way, if a program does not have administrator rights, other programs it starts will not have administrator rights by default.

       Can a program without administrator rights start a program with administrator rights? The answer is yes, it can be done. A program without administrator rights cancall the API function ShellExecuteEx and pass in the runas parameter to start another program, so that the started program is Started with administrator rights, that is, the started program is run with administrator rights. The code to start the program in runas mode is as follows:

SHELLEXECUTEINFO si;
RtlZeroMemory( &si, sizeof( SHELLEXECUTEINFO ) );
si.cbSize = sizeof(SHELLEXECUTEINFO);
si.lpFile = _T("D:\\test.exe");
//si.lpParameters = lpCmdParam;
si.nShow = SW_SHOWNORMAL;
si.lpVerb = _T("runas");
BOOL bRet = ShellExecuteEx( &si );
if ( !bRet ) // TL启动失败
{
    TCHAR achLog[256] = { 0 };
 
    // 先取lasterror值
    DWORD dwLastErr = GetLastError();
    _stprintf( achLog, _T("ShellExecuteEx failed, GetLastError: %d."), dwLastErr );
    WriteLog( achLog );
 
    // 再取hInstApp错误代码
    int nHInsVal = (int)si.hInstApp;
    if ( nHInsVal <= 32 )
    {
        _stprintf( achLog, _T("ShellExecuteEx failure, errcode: %d."), nHInsVal );
        WriteLog( achLog );
    }
}

       Note, when calling ShellExecuteEx to start the program fails, the error code can be obtained through the hInstApp field value in the SHELLEXECUTEINFO structure. The code is as shown above. The error codes mainly include the following:

mistake illustrate
ERROR_FILE_NOT_FOUND The file specified could not be found.
ERROR_PATH_NOT_FOUND The specified path was not found.
ERROR_DDE_FAIL Dynamic Data Exchange (DDE) transaction failed.
ERROR_NO_ASSOCIATION There is no application associated with the specified file extension.
ERROR_ACCESS_DENIED Access to the specified file is denied.
ERROR_DLL_NOT_FOUND One of the library files required to run the application could not be found.
ERROR_CANCELLED The function prompted the user for additional information, but the user canceled the request.
ERROR_NOT_ENOUGH_MEMORY There is insufficient memory to perform the specified operation.
ERROR_SHARING_VIOLATION A sharing conflict occurred.

8.2. Administrator permissions cannot be set for programs that start automatically at boot.

       The so-called self-starting means that it starts together with the Windows system, that is, after the Windows system starts and enters the desktop, the program automatically starts. Programs that are set to start automatically at startup cannot be set to start with administrator privileges, otherwise the program will fail to start automatically at startup. For security reasons, the Windows system prohibits programs started with administrator privileges from starting on startup, because programs started with administrator privileges can modify files in key directories of the system.

       If the main program really requires administrator rights to start (it may be that many operations performed in the program require administrator rights, such as writing content to the system path, registering controls with the system, etc.), then you can Write a separate exe startup program, such as Start it in mode, so that the main program runs with administrator privileges. As for the code to start the target program with runas, I have already mentioned it above, just use it directly.

Guess you like

Origin blog.csdn.net/chenlycly/article/details/134418715