<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JEDI Windows API &#187; Privilege</title>
	<atom:link href="http://blog.delphi-jedi.net/tag/privilege/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.delphi-jedi.net</link>
	<description>Joint Endeavor of Delphi Innovators of Windows Programming</description>
	<lastBuildDate>Wed, 19 Oct 2011 18:52:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How to work with privileges EXTENDED version</title>
		<link>http://blog.delphi-jedi.net/2008/03/15/how-to-work-with-privileges/</link>
		<comments>http://blog.delphi-jedi.net/2008/03/15/how-to-work-with-privileges/#comments</comments>
		<pubDate>Sat, 15 Mar 2008 17:27:47 +0000</pubDate>
		<dc:creator>Christian Wimmer</dc:creator>
				<category><![CDATA[JEDI Windows Security Code Lib]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[JWSCL]]></category>
		<category><![CDATA[Privilege]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://blog.delphi-jedi.net/2008/03/15/how-to-work-with-privileges/</guid>
		<description><![CDATA[Some functions (like ExitWindowsEx) need a privilege (SE_SHUTDOWN_NAME) to be enabled to work properly. With the help of JWSCL this task is made very easy. JWSCL provides several ways to enable and disable privileges. Use the methods of TJwSecurityToken Use the function JWEnablePrivilege Use the interface IJwPrivilegeScope 1. Use the methods of TJwSecurityToken You can [...]]]></description>
			<content:encoded><![CDATA[<p>Some functions (like <a href="http://blog.delphi-jedi.net/2008/03/03/how-to-work-with-privileges/"><em>ExitWindowsEx</em></a>) need a privilege (<em>SE_SHUTDOWN_NAME</em>) to be enabled to work properly.<br />
With the help of <strong>JWSCL</strong> this task is made very easy.</p>
<p><strong>JWSCL</strong> provides several ways to enable and disable privileges.</p>
<ol>
<li>Use the methods of <em>TJwSecurityToken</em></li>
<li>Use the function <em>JWEnablePrivilege</em></li>
<li>Use the interface <em>IJwPrivilegeScope</em><span id="more-27"></span></li>
</ol>
<p><u>1. Use the methods of TJwSecurityToken</u></p>
<p>You can use TJwSecurityToken to enable, disable or test a privilege. However there are some tool functions that do it for you already in only a single call. They are called</p>
<ul>
<li><a href="http://jwscldoc.delphi-jedi.net/JwsclToken.html#JwEnablePrivilege" title="Get help."><em>JwEnablePrivilege</em></a>, enables or disables a privilege</li>
<li><a href="http://jwscldoc.delphi-jedi.net/JwsclToken.html#JwIsPrivilegeSet" title="Get help."><em>JwIsPrivilegeSet</em></a> checks whether a privilege is set or available (despite its name)</li>
</ul>
<p><u>2.Use the function JwEnablePrivilege and friends<br />
</u></p>
<p>A very convienient way to enable and disable a privilege is to use the function <em>JwEnablePrivilege</em>.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">type</span><br />
&nbsp; TJwPrivilegeSetType =<br />
&nbsp; &nbsp;<span class="br0">&#40;</span>pst_Enable , pst_EnableIfAvail ,pst_Disable<span class="br0">&#41;</span>;</p>
<p><span class="kw1">function</span> JwEnablePrivilege <span class="br0">&#40;</span><span class="kw1">const</span> Index : <span class="kw4">string</span>;<br />
&nbsp; <span class="kw1">const</span> Query : JwPrivilegeSetType<span class="br0">&#41;</span>: <span class="kw4">boolean</span>;</div>
<p>There are two ways to enabe a privilege and one way to disable it.</p>
<ol>
<li>Enable a privilege or die if the privilege does not exist
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">try</span><br />
&nbsp; JwEnablePrivilege<span class="br0">&#40;</span>SE_DEBUG_NAME, pst_Enable<span class="br0">&#41;</span>;<br />
<span class="kw1">except</span><br />
&nbsp; <span class="kw1">on</span> E: EJwsclPrivilegeException <span class="kw1">do</span><br />
&nbsp; &nbsp;<span class="co1">//do error stuff here</span><br />
<span class="kw1">end</span>;</div>
<p>You should check for the exception <em>EJwsclPrivilegeException</em> because if the flag <strong>pst_Enable</strong> is used, the function raises the exception when the privilege does not exist.</li>
<li>Enable a privilege only if it exists
<div class="dean_ch" style="white-space: wrap;"> JwEnablePrivilege<span class="br0">&#40;</span>SE_DEBUG_NAME, pst_EnableIfAvail<span class="br0">&#41;</span>;</div>
<p>The code above may or may not enable the privilege depending on its availability. This is sometimes useful if you do not really need a privilege, but it might come handy if available. For example you could use SE_DEBUG_NAME privilege in a call to OpenProcess to open a foreign process. In the worst case that happens without the process is that OpenProcess will fail on processes that were not executed by the same user. However in each case you have to check the result of OpenProcess.</li>
<li>Disable a privilege<br />
Disabling a privilege is not much work. It even won&#8217;t throw an exception if the privilege does not exist.</p>
<div class="dean_ch" style="white-space: wrap;"> JwEnablePrivilege<span class="br0">&#40;</span>SE_DEBUG_NAME, pst_Disable<span class="br0">&#41;</span>;</div>
</li>
</ol>
<p>To find out whether a special privilege is available use <em>JwIsPrivilegeSet</em>.<br />
The following code illustrates how to use <em>JwIsPrivilegeSet</em>.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">uses</span> JwsclToken;&#8230; &nbsp; &nbsp; &nbsp;</p>
<p>&nbsp; <span class="kw1">if</span> JwIsPrivilegeSet<span class="br0">&#40;</span>SE_DEBUG_NAME, pqt_Available<span class="br0">&#41;</span> <span class="kw1">then</span><br />
&nbsp; <span class="kw1">begin</span><br />
&nbsp; &nbsp; <span class="kw1">if</span> JwIsPrivilegeSet<span class="br0">&#40;</span>SE_DEBUG_NAME, pqt_Enabled<span class="br0">&#41;</span> <span class="kw1">then</span><br />
&nbsp; &nbsp; &nbsp; JwEnablePrivilege<span class="br0">&#40;</span>SE_DEBUG_NAME, pst_Disable<span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="kw1">else</span><br />
&nbsp; &nbsp; &nbsp; JwEnablePrivilege<span class="br0">&#40;</span>SE_DEBUG_NAME, pst_Enable<span class="br0">&#41;</span>;<br />
&nbsp; <span class="kw1">end</span>;<br />
&#8230;</div>
<p>With this helper function <em>JwEnablePrivilege</em> won&#8217;t throw the exception <em>EJwsclPrivilegeException</em> if the privilege is not available.<br />
A handy function is <em>JwGetPrivilegesText</em>, which returns a string of available privileges and their status. You also can define which privileges are shown.</p>
<ul>
<li><a href="http://jwscldoc.delphi-jedi.net/JwsclToken.html#JwGetPrivilegesText" title="Get help.">JwGetPrivilegesText</a></li>
</ul>
<p><em>JwGetPrivilegesText</em> comes in two versions. The first version does not have any parameters and just returns a string with privilege names and their status. Each privilege is separated by a line break.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw3">WriteLn</span><span class="br0">&#40;</span>JwGetPrivilegesText<span class="br0">&#41;</span>;</div>
<p>The output may look like depending on your status. The following privileges are from a standard user in Vista:</p>
<blockquote><p><em>SeShutdownPrivilege [disabled]<br />
SeChangeNotifyPrivilege [enabled]<br />
SeUndockPrivilege [disabled]<br />
SeIncreaseWorkingSetPrivilege [disabled]<br />
SeTimeZonePrivilege [disabled]</em></p></blockquote>
<p>The second version of <em>JwGetPrivilegesText</em> receives a list of privileges you want to be displayed:</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw3">WriteLn</span><span class="br0">&#40;</span>JwGetPrivilegesText<span class="br0">&#40;</span><span class="br0">&#91;</span><br />
&nbsp; SE_CHANGE_NOTIFY_NAME,<br />
&nbsp; SE_DEBUG_NAME,<br />
&nbsp; SE_SHUTDOWN_NAME,<br />
&nbsp; SE_CHANGE_NOTIFY_NAME<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;</div>
<p>The output may look like this:</p>
<blockquote><p><em>SeChangeNotifyPrivilege [enabled]<br />
SeDebugPrivilege [not available]<br />
SeShutdownPrivilege [disabled]<br />
SeChangeNotifyPrivilege [enabled]</em></p></blockquote>
<p><u><strong>Multipe threads and privileges:</strong></u></p>
<p>You should always use a thread token when you work with several threads. Enabling and disabling privileges on a process token is very problematic. The reason is that you enable or disable a privilege for all threads. If a single thread enables a privilege and another one disables it, the first thread will fail to call a function that depends on that privilege.<br />
It is possible to introduce lock mechanisms like semaphores. But this is not necessary because each thread can (and should) have its own token: An <em>impersonated token</em> or in other words : a <em>thread token</em>.</p>
<p>To use a thread token properly you have to add this code to your main thread function.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">procedure</span> TMyThread.<span class="me1">Execute</span>;<br />
<span class="kw1">var</span> Token : TJwSecurityToken;<br />
<span class="kw1">begin</span><br />
&nbsp; Token := TJwSecurityToken.<span class="me1">CreateTokenEffective</span><span class="br0">&#40;</span>MAXIMUM_ALLOWED<span class="br0">&#41;</span>;<br />
&nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; <span class="co1">//check for error result</span><br />
&nbsp; &nbsp; <span class="co1">//you should proceed very carefully if the call fails</span><br />
&nbsp; &nbsp; Token.<span class="me1">ImpersonateLoggedOnUser</span>;<br />
&nbsp; <span class="kw1">except</span><br />
&nbsp; &nbsp;<span class="kw1">on</span> E1 : &nbsp;EJwsclAccessTypeException <span class="kw1">do</span><br />
&nbsp; &nbsp; &nbsp;<span class="co1">//will be raised if the token is an impersonation token and does not have access type TOKEN_QUERY and TOKEN_IMPERSONATE)</span><br />
&nbsp; &nbsp;<span class="kw1">on</span> E2 : EJwsclAccessTypeException <span class="kw1">do</span><br />
&nbsp; &nbsp; &nbsp;<span class="co1">//will be raised if the token is a primary token and does not have access type TOKEN_QUERY and TOKEN_DUPLICATE)</span><br />
&nbsp; &nbsp;<span class="kw1">on</span> E3 : EJwsclSecurityException <span class="kw1">do</span><br />
&nbsp; &nbsp; &nbsp;<span class="co1">//will be raised if a winapi function failed</span><br />
&nbsp; <span class="kw1">end</span>; &nbsp; &nbsp; &nbsp;</p>
<p>&nbsp;<span class="kw1">try</span><br />
&nbsp; &nbsp;<span class="co1">//do your thread stuff here</span><br />
&nbsp; <span class="kw1">finally</span><br />
&nbsp; &nbsp; Token.<span class="me1">Free</span>;<br />
&nbsp; &nbsp; Token := <span class="kw2">nil</span>;<br />
&nbsp; <span class="kw1">end</span>;<br />
<span class="kw1">end</span>;</div>
<p align="left">ImpersonateLoggedOnUser has a lot of possible exception handlers. This is because there are several ways how the call can fail. You should make sure that your main thread code is not executed without an assigned thread token.</p>
<p>Additionally you should also never call <em>TerminateThread or ExitThread </em>because in this case the <em>finally</em> Block would not be executed (memory leak).</p>
<p><u>3. Use the interface IJwPrivilegeScope</u></p>
<p>It is always a good thing to disable a privilege after it was used. The only way to do it safe is to use a try finally catch. If something happens the privilege is disabled at least.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">try</span><br />
&nbsp; wEnablePrivilege <span class="br0">&#40;</span> SE_SHUTDOWN_NAME , pst_Enable <span class="br0">&#41;</span>;<br />
<span class="kw1">except</span><br />
&nbsp; <span class="kw1">on</span> E : EJwsclPrivilegeException <span class="kw1">do</span><br />
&nbsp; <span class="co1">// error handling</span><br />
<span class="kw1">end</span>; &nbsp; &nbsp; &nbsp;</p>
<p><span class="kw1">try</span><br />
&nbsp; <span class="co1">//do your stuff here</span><br />
<span class="kw1">finally</span><br />
&nbsp; JwEnablePrivilege <span class="br0">&#40;</span> SE_SHUTDOWN_NAME , pst_Disable<span class="br0">&#41;</span>;<br />
<span class="kw1">end</span>;</div>
<p>This codes needs a lot of work to write if several other privileges are necessary. Fortunately there is a way to accomplish this task much more convenient. We use COM and the unit <em>JwsclPrivileges</em> which implements the interface <em>IJwPrivilegeScope</em>.<br />
<em>IJwPrivilegeScope</em> allows to enable several privileges at once and also disable them as soon as the internal reference counter drops to zero. A huge advantage is that Delphi helps a lot with the reference counting. It automatically increases or decreases the reference counter for several actions like passing the interface to another function. Find out more about <a href="http://en.wikipedia.org/wiki/Scope_%28programming%29" title="What is a scope?">scope</a>s and Delphi&#8217;s reference counting for interfaces <a href="http://dn.codegear.com/article/30125">here</a>.<br />
The automatic privilege mangagment can be used in the following way:</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">procedure</span> YourClass.<span class="me1">FooMethod</span>;<br />
<span class="kw1">var</span> Privs : IJwPrivilegeScope;<br />
<span class="kw1">begin</span><br />
&nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; Privs := JwGetPrivilegeScope<span class="br0">&#40;</span><span class="br0">&#91;</span>SE_SHUTDOWN_NAME, SE_TCB_NAME, SE_SECURITY_NAME<span class="br0">&#93;</span><span class="br0">&#41;</span>;<br />
&nbsp; <span class="kw1">except</span><br />
&nbsp; &nbsp; <span class="kw1">on</span> E : EJwsclPrivilegeException <span class="kw1">do</span><br />
&nbsp; &nbsp; &nbsp; <span class="co1">//do things on error and exit</span><br />
&nbsp; <span class="kw1">end</span>;<br />
&nbsp; <span class="co1">//do things on success that needs privileges enabled</span><br />
<span class="kw1">end</span>; <span class="co1">//here the privileges are automatically disabled &nbsp; &nbsp; &nbsp;</span></p>
<p><span class="kw1">begin</span><br />
&nbsp; FooMethod;<br />
&nbsp; <span class="co1">//SE_SHUTDOWN_NAME, SE_TCB_NAME, SE_SECURITY_NAME are disabled.</span><br />
&#8230;</div>
<p>The interface <em>Privs</em> will run out of scope as soon as the method <em>FooMethod</em> exits. In this last step the activated privileges are disabled automatically.<br />
If you combine this mechanism with the thread token shown in &#8220;<em>procedure TYourThread.Execute;</em>&#8221; you can easily play with privileges without disturbing other thread tokens. However you need a thread token only if you run several threads. In a single thread application the effort isn&#8217;t usually necessary for the discussed task (but there may be exceptions).</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">var</span> Text : <span class="kw4">String</span> ; &nbsp; &nbsp; &nbsp;</p>
<p><span class="kw1">procedure</span> YourClass.<span class="me1">FooMethod</span>;<br />
<span class="kw1">var</span> PrivScope : IJwPrivilegeScope ;<br />
<span class="kw1">begin</span><br />
&nbsp; <span class="co1">// Privilege is only active in this procedure</span><br />
&nbsp; PrivScope := JwGetPrivilegeScope <span class="br0">&#40;</span><span class="br0">&#91;</span> SE_SHUTDOWN_NAME <span class="br0">&#93;</span>,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pst_EnableIfAvail <span class="br0">&#41;</span>;<br />
&nbsp; Text := JwGetPrivilegesText <span class="br0">&#40;</span><span class="br0">&#91;</span> SE_SHUTDOWN_NAME <span class="br0">&#93;</span><span class="br0">&#41;</span>; <span class="co1">// enabled</span><br />
&nbsp; <span class="kw3">writeln</span><span class="br0">&#40;</span>Text<span class="br0">&#41;</span>;<br />
<span class="kw1">end</span>; &nbsp; &nbsp; &nbsp;</p>
<p><span class="kw1">var</span> ImpToken : TJwSecurityToken;<br />
<span class="kw1">begin</span><br />
&nbsp; <span class="co1">// create thread token from the process token</span><br />
&nbsp; ImpToken := TJwSecurityToken . <span class="me1">CreateTokenByProcess</span> <span class="br0">&#40;</span><span class="nu0">0</span>,<br />
&nbsp; &nbsp; TOKEN_ADJUST_PRIVILEGES <span class="kw1">or</span> TOKEN_QUERY <span class="kw1">or</span> TOKEN_READ <span class="kw1">or</span><br />
&nbsp; &nbsp; TOKEN_IMPERSONATE <span class="kw1">or</span> TOKEN_DUPLICATE <span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp;</p>
<p>&nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; ImpToken . <span class="me1">ImpersonateLoggedOnUser</span> ;<br />
&nbsp; <span class="kw1">except</span><br />
&nbsp; &nbsp; <span class="co1">//exception handling left out</span><br />
&nbsp; <span class="kw1">end</span>; &nbsp; &nbsp; &nbsp;</p>
<p>&nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; FooMethod;<br />
&nbsp; <span class="kw1">finally</span><br />
&nbsp; &nbsp; ImpToken.<span class="me1">Free</span>;<br />
&nbsp; <span class="kw1">end</span>;<br />
<span class="kw1">end</span></div>
<p><u></u></p>
<hr id="null" /><u>Some hints to remember:</u></p>
<ol>
<li>You cannot add privileges that were not granted to the token. There are two ways to do so with a SYSTEM account (like a service)
<ol>
<li>Use another process token that contains the necessary privilege</li>
<li>Create your own token by using LsaLogonUser. It allows to add groups and privileges.</li>
</ol>
<p>Be warned that using these mechanisms incorrectly may create a security hole.</li>
<li>You can remove privileges by recreating the token using CreateRestrictedToken. The new token is then called restricted token. Maybe you already know the word from Vista and the twin token.</li>
<li>Using a (restricted) thread token on code that is not trustworthy is very risky because the code can always return to the process token. This is done by calling RevertToSelf. In this case you must execute the code in a seperate process. Create the process with CreateProcessAsUser and pass the (restricted) token to the hToken parameter. If you fear the inter-process communication you can also use an out-of process COM DLL.</li>
<li>Always use an exception handler if the method could raise an exception. If an exception is raised within a thread, the thread will immediately stop working and leave resource leaks.</li>
<li>Do not force a user to have a special privilege. Many privileges aren&#8217;t needed anyway. For example, the SE_DEBUG_NAME privilege &#8211; despite its name &#8211; isn&#8217;t needed for debugging applications. In fact you can debug an application that was started under your user&#8217;s account. However you need the debug privilege only for foreign processes. This includes system processes of course. Raymond answers the question <a href="http://blogs.msdn.com/oldnewthing/archive/2008/03/14/8080140.aspx">why the debug privilege grants administrator accesss</a>.</li>
</ol>
<p><strong>Tell me how you liked this blog entry by adding a comment.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.delphi-jedi.net/2008/03/15/how-to-work-with-privileges/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

