Teach Your Apps To Play Nicely With Windows Vista User Account Control(转)

来源:互联网 发布:linux 下载文件 编辑:程序博客网 时间:2024/04/28 18:11

转自 http://msdn.microsoft.com/en-us/magazine/cc163486.aspx

怕忘了,收藏一个;

 

Least Privilege
Teach Your Apps To Play Nicely With Windows Vista User Account Control
Chris Corio

 

This article discusses:
  • User Account Control
  • Designing applications to run as standard users
  • Elevating privileges when neccessary
This article uses the following technologies:
Windows Vista

Active at Logon
Creating a Filtered Token
Designing Apps to Run with the Filtered Token
Designing Apps that Require Administrator Privileges
Privileges During Installation
Marking the Privileges for an MSI
Running Your App with Administrator Privileges
Marking Required Privileges Using an Application Manifest
Marking a COM Object
Alerting Users to Elevated Privileges
Communicating between Processes in Different Security Contexts
Low Rights Internet Explorer
Securing a Windows Service in Windows Vista
Common Application Compatibility Issues
Problems During Installation
Typical Runtime Application Issues
Conclusion

Ihave worked with so many developers over the past year that theirconcerns and their eventual understanding of how User Account Control(UAC) works have all blended into a giant haze. There really is nodoubt: it will take time to learn how to write good applications forstandard users, but this knowledge will make you a better programmerfor Windows®. The goal of this article is to give you the information necessary to make the journey quick and easy.
UACis the Microsoft answer to reducing the privileges users run with bydefault in Windows Vista™. Strategically, Microsoft is moving to anenvironment where users do not have or need privileges that can affectthe operating system and machine-wide configuration in order to performday-to-day tasks. Such an environment also keeps users from affectingeach other's state and settings.
Thereare countless practical reasons for this move. UAC limits theprivileges that applications run with by default. In the enterprise,this lets users run in the Users group rather than as Administrators,allowing meaningful corporate security policies to be enforced. This inturn reduces user impact on machines, lowering the total cost ofownership (TCO). In the home, malware cannot affect the system orinstall a service or driver without the user going through the UACConsent or Credential prompt. While the risk of social engineeringstill exists, the consolidation of the path to obtain elevatedprivileges allows the future implementation of technologies to controlwhich applications can execute with machine-wide privileges without theneed to prompt the user.
Theprimary goal of UAC is to make the default user token that applicationsare run with mimic that of a member of the Users group. This startswith creating a restricted, or filtered, token during interactive logonfor users with elevated privileges. When more privileges are necessaryto execute a restricted operation, the user will be prompted forauthorization on the secure desktop. UAC also includes othertechnologies to support application compatibility and to secure theelevated processes.

 

Active at Logon
UACstarts working when a user logs onto a machine. During an interactivelogon, the Local Security Authority (LSA) takes the user's credentialsand performs the initial logon, evaluating the user's token to see ifit has what are defined as elevated privileges. If the LSA determinesthat the user has elevated privileges, it will filter this token andthen perform a second logon with the filtered token. The most commoncase in which a user will have both a filtered and fully privilegedtoken is when the user is a member of the Administrators group. Thefully privileged token of an administrator can write to machine-widelocations such as Program Files and HKEY_LOCAL_MACHINE (HKLM), thusaffecting the entire machine. However, the filtered token is just likea member of the Users group, which doesn't have these privileges, andis used to create the user's interactive desktop session.
Thedesktop session and explor­er.exe will always be created with a tokenthat approximates the token of a member of the Users group. Any processthat is initiated from the Start Menu or by a user double-clicking inan Explorer window that doesn't require elevation will simply inheritthis filtered token. Therefore, by default, every application will berunning with the standard user token. When a process is marked asrequiring administrator privileges in the manifest or in theapplication compatibility settings, UAC will prompt the user forelevation. Figures 1 and 2 show theprompts for consent and for credentials. If the user so authorizes, theApplication Information service will create the process with the fullyprivileged token.
Figure 1 Prompt for Consent (Click the image for a larger view)
Figure 2 Prompt for Credentials (Click the image for a larger view)

 

Creating a Filtered Token
User Account Control defines the groups listed in Figure 3as having elevated privileges. Therefore, if the LSA notices that anyof those group memberships or privileges are listed in the user'sinitial token, a filtered token will be created during an interactivelogon, using a version of the CreateRestrictedToken API, and the fullyprivileged token is saved by LSA. These two tokens are linked and thefully privileged token can be obtained from the filtered token usingthe Get­Token­Infor­mation API with the new TokenLinkedTokeninformation type. Note, however, that UAC does not affect service,network, or batch logons.


Built-In AdministratorsPower UsersAccount OperatorsServer OperatorsPrinter OperatorsBackup OperatorsRAS Servers GroupWindows NT 4.0 App Compat GroupNetwork Configuration OperatorsDomain Administrators Domain ControllersCertificate PublishersSchema AdministratorsEnterprise Administrators Group Policy Administrators

If the user does not belong to any of the groups listed in Figure 3but has certain privileges, a filtered token will be created with theseprivileges removed. The privileges in question are:SeCreateTokenPriv­i­lege, SeTcbPrivilege,Se­Take­Owner­ship­Priv­ilege, Se­Back­up­Priv­i­lege,Se­Re­store­Privilege, Se­De­bug­Priv­ilege, Se­Im­personatePrivilege,and Se­Re­labelPrivilege.
Ifthe user is a member of the Ad­ministrators group, the filtered tokenwill have the Administrators group membership set to DENY ONLY, whichprohibits AccessCheck from using this group to allow access to aresource. Also, all machine-impacting privileges are removed from thetoken. (This is the default token used to create explorer.exe andnon-elevated processes.) You can look at this token using whoami.exe,which is included in Windows Vista; just run whoami.exe /all in aCommand window. Figure 4 and Figure 5 respectively describe group memberships listed in the token and privileges in the token.


Privilege Description SeShutdownPrivilegeShut down the system.SeChangeNotifyPrivilege Bypass traverse checking.SeUndockPrivilege Remove computer from docking station.SeIncreaseWorkingSetPrivilege Increase a process working set.SeTimeZonePrivilege Change the time zone.

Group Name Attributes Group NameAttributesEveryoneMandatory group, enabled by default, enabled groupBUILTIN/Administrators Group used for deny onlyBUILTIN/Users Mandatory group, enabled by default, enabled groupMandatory Label/Medium Mandatory Level Mandatory group, enabled by default, enabled group

Designing Apps to Run with the Filtered Token
Mostapplications do not require administrator privileges at run time. Ifyour application doesn't maintain cross-session state while it executesand doesn't do something like modifying the local security policy, itshould be just fine running with a standard-user token. Sometimescertain parts of your application will require administratorprivileges, and you should separate out those pieces into a separateprocess. I'll get into that a little later.
Themost important step you can take during the development of a standarduser application is to test it while running as a standard user. One ofthe most common reasons an application fails in production is becausethe developers never tested it as a standard user. Remember to do this.
Thenext most important step is deciding where to save your applicationbinaries and per-user configuration data. An application that iscompletely per-user, meaning that both its binaries and configurationare specific to the user, should maintain all of its state in the userprofile: %userprofile%. In the registry, you should write all of thestate to the user's hive, HKEY_CURRENT_USER (HKCU). In many cases, itmakes sense to install the binaries into the %ProgramFiles% directorybut this requires administrator privileges and is discussed later inthe article.
Sometimes,as when you're storing high scores for a game, you need to maintainsystem-wide state and allow users to write to it. The recommended placeto store this data is in the %allusersprofile% directory. Here you cancreate a directory specific to your application and allow users towrite to it. Just remember, other users can tamper with this file.

 

Designing Apps that Require Administrator Privileges
Myhonest advice about writing applications that require administratorprivileges is: don't do it! Unless you're absolutely certain that yourapplication requires elevated privileges, just write your applicationto use the standard user token. There are very few APIs that must becalled by administrators.
Ofcourse, there are circumstances where you might need to useadministrator privileges, like during installation or when you'remaintaining cross-session state, which generally means your applicationis implemented as a service. UAC doesn't apply to services; there areother security settings available for Windows services that I'lldiscuss later. If your application implements a security model on thelocal machine, you'd also need administrator privileges. For example,if you have settings that are deployed with a Group Policy ApplicationDistribution and Management (ADM) or through Systems Management Server(SMS), you will probably have an application on the local machine toupdate them as well. This would require administrator privileges.

 

Privileges During Installation
Installingapplications typically requires administrator privileges, usuallybecause application binaries are written to the Program Filesdirectory, which is read-only for standard users. This means that anyapplication that writes binaries to this location will need to bemarked as requiring administrator privileges. Because Windows Installerhas been integrated with UAC, installation packages (MSI files) havebecome an even more attractive method for installation. They can bespecified in two ways: to be per-user or per-machine installations,which would only prompt the user for administrator privileges whennecessary.
Whileinstallation to the Program Files directory will result in an elevationprompt being shown to users, there are definitely benefits to puttingthe application's binaries there. Installing in that directory requiresthe user to be an administrator so a standard user in an enterprise ora Parental Controls user couldn't arbitrarily install the application.Also, your application will share one set of binaries across themachine and they will be protected from tampering by a standard user.This will make it easier to determine the state and version of theapplication when updating the binaries after a bug fix or to addfunctionality.
Whenyou design your application, there will likely be some applicationsettings you'll want applied for the user. Perhaps the users specifycustom information about how their views are shown or which menus aredisplayed. A good way to provide this facility is to create a defaulttemplate under the Program Files directory, then copy and modify it inthe user's AppData directory, %local­appdata%. This data can be copiedat first run of your application and enables per-user state for eachuser. If, on the other hand, you want machine-wide state thatindividual users can modify, you would want to put this in the%allusersprofile%, as in the high scores example mentioned earlier.
Anotheraspect of installation that causes some grief in the UAC world isupdating. If you are going to update binaries in the Program Filesdirectory, the process overwriting the binaries must have administratoror system privileges. One benefit of using Windows Installer is theability to patch using an MSI patch (MSP) file. Since Windows Installer3.1, which is a required update for Windows XP, an MSP file will beapplied to the system if it is signed by a certificate that wasincluded in the original MSI file. For more information, see thedocumentation on User Account Control Patching on MSDN® (at windows­sdk.msdn.micro­soft.com/ms710366.aspx).
Otherthan using MSI files, application developers can either integrate abinary that is specified to run with administrator privileges-whichwill prohibit updating in an enterprise with standard users-or includea service that will execute any updates required. Shipping a service isstrongly discouraged because any security vulnerability in the servicecould make the ISV an attack vector for malware. MSP files are yourbest bet.

 

Marking the Privileges for an MSI
BeforeWindows Vista, the ALLUSERS property was used to mark whether an MSIfile would install an application's shortcuts to the user location orfor all users on the machine. These shortcuts included theDesktopFolder, ProgramMenuFolder, StartMenuFolder, and StartupFolder.Because there was no analogous per-user Program Files directory, theapplication binaries generally were still written to the Program Filesdirectory.
Unfortunately,for app compatibility reasons Windows Installer could not determinewhether the user should be prompted for credentials based solely on theALLUSERS property. Instead, an additional bit was allocated in the MSIfile to determine whether to prompt the user. This is bit 3 in the WordCount Summary property. If this bit is set to 1, the package is assumedto be a per-user MSI and the user will not be prompted for anAdministrator token.
Tospecify that a package can only be installed by an administrator intothe Public profile, set ALLUSERS="1" or ALLUSERS="2" and set bit 3 ofthe Word Count Summary property to 0. To specify that a package is aper-user installation that can be installed by a standard user, setALLUSERS="" or don't define the property, and set bit 3 of the WordCount Summary property to 1.

 

Running Your App with Administrator Privileges
Thereare times that you may need administrator privileges for anapplication. You may write code that directly interacts with a piece ofhardware or an app that sets machine-wide settings in HKLM. Whenpossible, you should design your apps to limit the need for adminprivileges to narrow sections of code, or communicate to an applicationstarted with full administrator privileges.
Asidefrom MSI-based elevation, there are two ways to create processes with auser's full administrator token. The Application Information Service(AIS) will check during process creation and during the creation of aCOM object using the CoCreateAsAdmin moniker to see if the binariesrequire administrator privilege. It is important to note that theelevation occurs at the time of process creation. The process tokennever has privileges or group membership added during run time, onlywhen it is created.
Oneword of caution: the UAC elevation prompt is only presented to the userwhen ShellExecute is called to create the process.ERROR_ELEVATION_REQUIRED is returned by any call to the CreateProcessfamily that requires elevation.

 

Marking Required Privileges Using an Application Manifest
Whena new process is created, the AIS will inspect the binary to determinewhether it requires elevation. The first thing that gets checked is theapplication manifest that is embedded into the application's resources.This takes precedence over any other type of application markingincluding an application compatibility marking or UAC's InstallerDetection, which is described later. The manifest defines a run levelthat tells Windows the privileges needed to run the binary. The threechoices for run level are: asInvoker, highestAvailable, andrequireAdministrator.
WhenAIS finds a binary that is marked with the "asInvoker" run level, ittakes no action and the process inherits the process token of theparent process that created it. The "requireAdministrator" run level ispretty straightforward as well and defines that the process must becreated by a user token that is a member of the administrator group. Ifthe user who attempted to create this process is not an administrator,he will be presented with the Credential dialog to input hiscredentials.
ThehighestAvailable run level is a little more complicated. It denotesthat if a user has a linked token, then the application should run withthe higher privileged token. This is generally used for applicationsthat have a UI designed for the Users and Administrators groups and itensures that the application gets the user's full privileges. It isimportant to note that users in the Backup Operators and NetworkOperators group will have a linked token and will be prompted for theircredentials; the credentials dialog will have their user tile and thoseof the members of the administrators group. Figure 6 is an example of an application manifest.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0"
processorArchitecture="X86" name="AdminApp" type="win32"/>
<description>Description of your application</description>
<!-- Identify the application security requirements. -->
<ms_asmv2:trustInfo xmlns:ms_asmv2="urn:schemas-microsoft-com:asm.v2">
<ms_asmv2:security>
<ms_asmv2:requestedPrivileges>
<ms_asmv2:requestedExecutionLevel
level="requireAdministrator"
uiAccess="false"/>
</ms_asmv2:requestedPrivileges>
</ms_asmv2:security>
</ms_asmv2:trustInfo>
</assembly>

Theapplication manifest marking is only relevant to EXEs, not DLLs. Thisis because UAC does not inspect DLLs during the creation of theprocess. To embed this manifest into your native application, copy themanifest file into the same directory as your source and add themanifest into the resource files to specify that the manifest is to beembedded. The following lines in the .rc file would embed the manifestabove if it were saved as Ad­min­App.exe.man­ifest:
#define MANIFEST_RESOURCE_ID 1
MANIFEST_RESOURCE_ID RT_MANIFEST "AdminApp.exe.manifest"

 

Marking a COM Object
Whena COM object is being created, you can use the Co­Cre­ateAsAdminmoniker to get a COM object running with elevated privileges. This isvery useful for creating objects that run elevated and are exposed inyour application's UI.
Thereare a couple additions that must be made to a COM object so it can runwith the fully privileged token. A display name to show in the UACelevation dialog must be specified as well as a marking showing thatthe object can be created with elevated privileges. The followingregistry keys must be added to the registration of your object.
HKEY_LOCAL_MACHINE/Software/Classes/CLSID/
{CLSID}/LocalizedString = <displayname>
HKEY_LOCAL_MACHINE/Software/Classes/CLSID/
{CLSID}/Elevation/Enabled = 1
Ifthe COM object is not registered in HKLM and both of these pieces ofinformation are not specified, then trying to create the elevated COMobject will fail. If it succeeds, the user will be prompted forelevation, assuming the call is coming from a process with a filteredtoken, and a new process will be created to host the COM object. Formore information about creating elevated COM objects, see the MSDNdocumentation for the CoCreateAsAdmin moniker at msdn2.microsoft.com/ms679687.aspx.

 

Alerting Users to Elevated Privileges
Anotherchallenge for UAC is communicating to users that may not have anynotion of the difference between an application that is running withreduced privileges and one that is running as an administrator. The keyto understanding this difference is the standardized workflow when theprompt for elevation occurs. The elevation sequence always begins withthe user clicking on something that has a shield image in its icon. Ifstarting an application is going to cause an elevation, you should seea shield overlaying the icon. Anywhere in your application that causeselevation should be marked with a shield.
Manyof the common controls have been updated to allow you to add shields tothem. This is extremely helpful if you want to expose settings whereclicking on a button or link results in the creation of a new processthat will require elevation. The code to add the shield glyph is verysimple. For example, the standard button control (PUSHBUTTON,DEFPUSHBUTTON) has been enhanced to let you add an icon along with thedisplayed text, without requiring the BS_ICON or BS_BITMAP styles to beset.
Figure 7 The Shield on a Button 
To show the shield icon (which you can see in Figure 7), you should call the following macro (defined in commctrl.h), which sends a SETSHIELD message to the button:
Button_SetElevationRequiredState(hwndButton, true);
Thesame style of showing the shield can be used for Aero™ Wizard buttons,Syslink and Hyperlink controls, Commandlink and Command buttons, andmore.

 

Communicating between Processes in Different Security Contexts
WindowsVista also includes an authentication technology called WindowsIntegrity Mechanism (WIM). WIM defines different security levels thatare used as labels on objects for further authorization: Low, Medium,High, and System. Because of UAC there may be processes in the samedesktop session that have full administrator privileges and others thatare running with a standard user token. UAC uses WIM to block Windowsmessages from being sent between processes of different privilegelevels.
Thetoken used to create the desktop will be running at the mediumintegrity level-see the sample filtered administrator token. This wayeverything by default is running with an integrity level of medium.When a user is prompted for elevation and gives his consent, theresulting process is created with the fully privileged token and has anintegrity level of high. In the past, there have been attacks, called"shatter attacks," where a lower-privileged UI sends messages to ahigher-privileged UI to drive the higher privileged process. In orderto avoid this, most Windows messages are no longer sent from lowerprivileged processes to higher privileged processes, and this is basedon the integrity level.
Thereare still ways to communicate between processes of different integritylevels. You can use shared memory or a remote procedure call (RPC). Besure that when you create your RPC entry point or IPC mechanism, youspecify that it can be connected to by a process that is running as astandard user. You will need to specify this in the object's securitydescriptor.

 

Low Rights Internet Explorer
One other side note about WIM and UAC is that it enables LowRights Internet Explorer®,a setting that takes advantage of the low integrity level to protectusers while they browse the Web. When running at Low, the process caninteract with a very narrow set of directories and files on the system.If you have an ActiveX® controlimplemented as part of your application, which is hosted by InternetExplorer, you will want to test it to make sure it runs properly. Formore information, see the whitepaper atmsdn.micro­soft.com/library/en-us/ietechcol/dnwebgen/protectedmode.asp.

 

Securing a Windows Service in Windows Vista
Thereare many new facilities for locking down services in Windows Vista.Developers can specify the privilege level that a service needs, and aservice can have a Security Identifier (SID) applied to it, which canbe used to secure resources so that only the service can write to them.Services can also be prevented from accessing the network. For moreinformation, see the documentation on Windows services available atmicro­soft.com/whdc/system/vista/Vista_Services.mspx.
You can still use sc.exe to define these new security parameters in Windows Vista (see Figure 8).Privileges is a string that contains a list of privileges that areseparated by a forward slash (/). For example, to specify backup andrestore privileges, set Privileges toSeBackupPrivilege/SeRestorePrivilege.


Command Syntax Purpose Privs sc <server> privs [service name} [privileges]Sets the required privileges for a service. Qprivssc <server> qprivs [service name] buffersizeQueries for the required privileges of a service.Sidtypesc <server> sidtype [service name] [type]Applies service SID to process token. Qsidtypesc <server> qsidtype [service name]Retrieves the setting for service's SID.

Sc.execan also be used to get a specified service's SID. The followingcommand returns the SID for a service that is named service name.
Sc showsid [service name]
Toprogrammatically change this information, use the new API calledChangeServiceConfig2. To change the service privileges specified, callChangeServiceConfig2 with the following parameter values. (The changein privileges takes effect the next time the service is started.)
ThedwInfo parameter should be SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO andthe lpInfo buffer should point to a SERVICE_REQUIRED_PRIVILEGES_INFOstructure. This structure contains a single multistring that lists therequired privileges.
Toenforce the service SID for the service, set the flag programmatically,calling ChangeServiceConfig2 with the following parameter values. (Thechange takes effect the next time the system is booted.) The dwInfoparameter should be set to SERVICE_CONFIG_SERVICE_SID_INFO, and thelpInfo buffer should be set to point to a SERVICE_SID_INFO structure.This structure contains a single DWORD member that contains the SIDtype.
Tworelated public functions are also useful to service owners:LookupAccountName and LookupAccountSID. Look­up­AccountName takes a SIDand returns the associated service name while LookupAccountSID takes aservice name and returns the associated SID. To query the values ofthese settings use the QueryServiceConfig2 API.
Anotherway to protect your service is to limit its access to the network. Toconfigure firewall restrictions for the service, use theINetFwServiceRestriction interface.
Onelast note-be wary of exposing RPC interfaces that can be connected tofrom lower-privileged processes. These interfaces should be carefullydesigned and tested so that the tasks that can be performed on theuser's behalf do not allow an elevation of privilege by the user.

 

Common Application Compatibility Issues
Oneof the biggest challenges our team encountered while producing UAC wasthe incredible impact it had on our application ecosystem. Manyapplications were not designed to be run by a member of the Usersgroup. Microsoft has invested many hours to understand the commonapplication compatibility issues and has added technologies to WindowsVista to address some of the problems. In the final section of thisarticle, I will describe some of the problems and briefly describe howto fix them.
Thefirst application compatibility technology that is part of UAC iscalled Installer Detection. Because most installers write binaries tothe Program Files directory, they overwhelmingly need administratorprivileges. Installer Detection is designed to scan the name and theresources of the EXE to determine whether an application is aninstaller. For example, an executable would be marked as an installerif the executable name or description contained the strings "install"or "setup". So an application named setup.exe, without an applicationmanifest, would trigger a UAC elevation if launched by a token withoutadministrator privileges.
Anothertechnology under the UAC umbrella designed to help fix file andregistry issues at run time is called File and Registry Virtualization.Many applications write their log files or their configuration to theProgram Files or Windows directory. These directories do not allow astandard user to write to these locations and hence these writes wouldimmediately fail. In order to fix these issues, File Virtualizationtakes the files written to certain protected locations in the filesystem and redirects the writes to the user's profile-it will notperform virtualization if the file being written to is a binary.Registry virtualization does the same thing for the registry byredirecting writes to HKLM/Software to a per-user location in theregistry. These technologies have raised the application compatibilityfor legacy applications immensely.
Oneimportant note is that these technologies are disabled if the binaryhas an application manifest or if the binaries are natively compiledfor 64-bit. This is because these technologies are really just crutchesfor legacy applications that were not designed with the standard userin mind. Unfortunately, these technologies don't solve all of theproblems. Next, I'll look at some other common issues.

 

Problems During Installation
Oneof the most frequent problems we see is mismarked CustomActions in anMSI file. Many CustomActions do not specify the no impersonate flagmsidbCustomActionTypeNoImpersonate, causing the CustomAction to be runas Local System. Because the default token on Windows Vista is nowsimilar to that of a member of the Users group, these MSI files failbecause the CustomActions attempt to do something that requiresadministrator privileges. Usually this can be fixed by merely addingthe msidbCustomActionTypeNoImpersonate attribute to the CustomActions.
Anothertypical problem we've encountered during testing concerns applicationsthat are launched as part of an install. It is very common to start anapplication at the end of installation. Unfortunately, the applicationis often started under the wrong user context because the user providedelevated credentials to perform the installation and the application iscreated with the elevated user token. The recommended guidance forsolving this problem is to create a bootstrapper EXE. This bootstrappermay unpack the binaries to a temp location and then start anotherprocess that initiates the installation (see Figure 9).When the process that started the installation completes, it returnscontrol to the unpacker that starts the application. This way theapplication is running with the standard user token.
Figure 9 Using a Bootstrapper to Install and Execute an App (Click the image for a larger view)
Thelast installation issue we've often come up against is performingoperations that require administrator privileges on the first run ofthe application. These include copying or updating binaries intoProgram Files, installing a driver, or any other operation that assumesthe user is an administrator. The best way to get a handle on theseissues is to test your application when installed and run as a standarduser.
Manyapplications have some mechanism for updating the application binaries.Often these updaters fail because they are running with alower-privileged token and attempt to overwrite the binaries in theProgram Files directory. If your application updates its binaries, movethe update functionality to a separate process and mark it as requiringadministrator privilege. Another option is to employ MSP files to dothe elevation based on the signature of the patch. For this, you wouldneed to populate the MsiPatchCertificate table in your original MSIfile.

 

Typical Runtime Application Issues
Oneof the most common mistakes that occur at run time is an unnecessarycheck to see if the user is an administrator. In many games, forexample, the first thing checked is whether the user is a member of theadministrator group. Often the games will report a failure to theuser-but they actually don't ever call any APIs that requireadministrator privileges! Obviously, this should be avoided. However,for resiliency, if you write an application that requires administratorprivileges and is manifested, add this check and exit if the userdoesn't have administrator privileges.
Manyapplications will begin execution and immediately attempt to register aclass to HKEY_CLASSES_ROOT (HKCR). Because the applications no longerhave administrator privileges, it will be impossible for them to writeto this location and the operation will fail. Registering these classesshould be done during installation or redirected to the user's classesroot: HKCU/Software/Classes.
Anotherpotential issue to look out for is that standard users are preventedfrom creating objects in the Global namespace. For example, a standarduser could not create a Named Pipe or Shared Memory within thenamespace. Global is intended only for use by services or applicationsmaintaining cross-session state. The Local namespace should be usedinstead. This is writable by a standard user.
UsingMAX_ALLOWED when opening an object is another issue. In Windows XP, itis generally assumed that the users running the applications wereadministrators. Therefore, when developers used MAX_ALLOWED whenopening files and registry keys, there was never a problem in thisenvironment because they were always opening the files with fulladministrator rights. In Windows Vista, this has changed. Now, whendevelopers write applications they need to be more careful whenspecifying the privileges a user will need to open an object.

 

Conclusion
Thisarticle is an overview of the new environment you'll be developingunder in Windows Vista. The most fundamental change is thatapplications now run with a lower-privileged token by default and thuscannot impact the machine or other users. For more information abouttopics related to UAC in Windows Vista, see the UAC whitepapersmentioned earlier on MSDN and TechNet. And remember that UAC will makethe lives of your users and systems administrators a lot easier.

 

Chris Coriowas a member of the Windows Security team at Microsoft for more thanfive years. His primary focus at Microsoft was application securitytechnologies and management technologies for securing Windows. You canreach Chris at winsecurity@chriscorio.com.
原创粉丝点击