<?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; Thread</title>
	<atom:link href="http://blog.delphi-jedi.net/tag/thread/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>New threads do not automatically impersonate themselves.</title>
		<link>http://blog.delphi-jedi.net/2008/04/09/new-threads-do-not-automatically-impersonate/</link>
		<comments>http://blog.delphi-jedi.net/2008/04/09/new-threads-do-not-automatically-impersonate/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 19:58:02 +0000</pubDate>
		<dc:creator>Christian Wimmer</dc:creator>
				<category><![CDATA[JEDI Windows Security Code Lib]]></category>
		<category><![CDATA[JWSCL]]></category>
		<category><![CDATA[Thread]]></category>
		<category><![CDATA[Token]]></category>

		<guid isPermaLink="false">http://blog.delphi-jedi.net/?p=108</guid>
		<description><![CDATA[Whenever you impersonate a running thread and create a new thread while impersonating, your new thread will not get impersonated, too. The new thread will run without any thread token and thus a called function will use the process token instead. So you have to impersonate the new thread again. Ignoring that fact may lead [...]]]></description>
			<content:encoded><![CDATA[<p>Whenever you impersonate a running thread and create a new thread while impersonating, your new thread will not get impersonated, too. The new thread will run without any thread token and thus a called function will use the process token instead. So you have to impersonate the new thread again.  Ignoring that fact may lead to problems if the process as a high access level (SYSTEM, Administrator) and  the new thread touches resources e.g. files. These files are opened with higher privileges, even if the user usually cannot access them.</p>
<p>The sample shows how we can spawn a token for the new thread exclusively.</p>
<div class="dean_ch" style="white-space: wrap;">
<span class="kw1">procedure</span> ThreadFunc<span class="br0">&#40;</span>Data : <span class="kw4">Pointer</span>&#8230;<span class="br0">&#41;</span><br />
<span class="kw1">var</span> Token : TJwSecurityToken;<br />
<span class="kw1">begin</span><br />
&nbsp; Token := TJwSecurityToken<span class="br0">&#40;</span>Data<span class="br0">&#41;</span>;<br />
&nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; Token.<span class="me1">ImpersonateLoggedOnUser</span>;<br />
&nbsp; &nbsp; &#8230;<br />
&nbsp; &nbsp; &#8230;<br />
&nbsp; <span class="kw1">except</span><br />
&nbsp; &nbsp; <span class="co1">//check here the problem</span><br />
&nbsp; &nbsp; <span class="co1">//and inform the thread creator</span><br />
&nbsp; &nbsp; <span class="co1">//To raise an exception within a thread does end it immediately.</span><br />
&nbsp; <span class="kw1">end</span>;<br />
&nbsp; Token.<span class="me1">Free</span>;<br />
<span class="kw1">end</span>;</p>
<p><span class="kw1">var</span> Token, Token2 : TJwSecurityToken;<br />
<span class="kw1">begin</span><br />
&nbsp; &#8230;<br />
&nbsp; <span class="kw1">try</span><br />
&nbsp; &nbsp; Token.<span class="me1">ImpersonateLoggedOnUser</span>;<br />
&nbsp; &nbsp; <span class="co1">//the new thread will not run in Token context</span><br />
&nbsp; &nbsp; <span class="co1">//get a second handle to the token for the thread</span><br />
&nbsp; &nbsp; Token2 := TJwSecurityToken.<span class="me1">CreateDuplicateExistingToken</span><span class="br0">&#40;</span>Token.<span class="me1">TokenHandle</span>, TOKEN_ALL_ACCESS, <span class="kw2">true</span><span class="br0">&#41;</span>;<br />
&nbsp; &nbsp; CreateThread<span class="br0">&#40;</span>&#8230;, @ThreadFunc, <span class="kw4">Pointer</span><span class="br0">&#40;</span>Token2<span class="br0">&#41;</span><span class="br0">&#41;</span>;<br />
&nbsp; &nbsp; &#8230;<br />
&nbsp; <span class="kw1">finally</span><br />
&nbsp; &nbsp; Token.<span class="me1">Free</span>;<br />
&nbsp; <span class="kw1">end</span>;</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.delphi-jedi.net/2008/04/09/new-threads-do-not-automatically-impersonate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get the threads of a process?</title>
		<link>http://blog.delphi-jedi.net/2008/03/19/how-to-get-the-threads-of-a-process/</link>
		<comments>http://blog.delphi-jedi.net/2008/03/19/how-to-get-the-threads-of-a-process/#comments</comments>
		<pubDate>Wed, 19 Mar 2008 15:00:25 +0000</pubDate>
		<dc:creator>Christian Wimmer</dc:creator>
				<category><![CDATA[JEDI Windows API Headers]]></category>
		<category><![CDATA[JWA]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://blog.delphi-jedi.net/2008/03/19/how-to-get-the-threads-of-a-process/</guid>
		<description><![CDATA[Yesterday, I described how to get the process of a window. Today I show you how to obtain the threads of a process. There are two ways to retrieve all the threads of a foreign process. Use the Tool Help Library. There is also a sample about enumerating threads. So I am not going to [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I described <a href="http://blog.delphi-jedi.net/2008/03/18/how-to-get-the-process-of-a-window/">how to get the process of a window</a>. Today I show you how to obtain the threads of a process.</p>
<p>There are two ways to retrieve all the threads of a foreign process.</p>
<ol>
<li>Use the <a href="http://msdn2.microsoft.com/en-us/library/ms686728(VS.85).aspx">Tool Help Library</a>. There is also a <a href="http://msdn2.microsoft.com/en-us/library/ms686852(VS.85).aspx">sample</a> about enumerating threads. So I am not going to to show you code in Delphi. The sample is simple enough to understand and convert.<br />
But these functions are necessary.</p>
<ul>
<li><a href="http://msdn2.microsoft.com/en-us/library/ms682489%28VS.85%29.aspx" target="_top">CreateToolhelp32Snapshot</a></li>
<li><a href="http://msdn2.microsoft.com/en-us/library/ms686728%28VS.85%29.aspx" class="tocSelected" target="_top">Thread32First</a></li>
<li><a href="http://msdn2.microsoft.com/en-us/library/ms686731%28VS.85%29.aspx" target="_top">Thread32Next</a></li>
</ul>
<p>The Tool Help Library declarations are defined in JwaTLHelp32.pas or JwaWindows.pas</li>
<li>Use Performance Data Helper as described in a <a href="http://www.codeproject.com/KB/system/ntenumthreads.aspx?display=Print">CodeProject article</a>.<br />
The PDH declarations are defined in JwaPdh.pas, JwaPdhMsg.pas or JwaWindows.pas</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/19/how-to-get-the-threads-of-a-process/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use VCL and SetThreadDesktop</title>
		<link>http://blog.delphi-jedi.net/2008/03/19/how-to-use-vcl-and-setthreaddesktop/</link>
		<comments>http://blog.delphi-jedi.net/2008/03/19/how-to-use-vcl-and-setthreaddesktop/#comments</comments>
		<pubDate>Wed, 19 Mar 2008 09:00:49 +0000</pubDate>
		<dc:creator>Christian Wimmer</dc:creator>
				<category><![CDATA[JEDI Windows API Headers]]></category>
		<category><![CDATA[JEDI Windows Security Code Lib]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[JWA]]></category>
		<category><![CDATA[JWSCL]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://blog.delphi-jedi.net/2008/03/19/how-to-use-vcl-and-setthreaddesktop/</guid>
		<description><![CDATA[It is impossible to use SetThreadDesktop and the VCL at the same time because a thread can only show windows on one desktop at a time. However VCL is not written for the use with multiple threads, so there is no way to show Delphi forms of same process on two different desktops. SetThreadDesktop describes [...]]]></description>
			<content:encoded><![CDATA[<p>It is impossible to use <a href="http://msdn2.microsoft.com/en-us/library/ms686250(vs.85).aspx">SetThreadDesktop</a> and the <strong>VCL </strong>at the same time because a thread can only show windows on one desktop at a time.  However <strong>VCL </strong>is not written for the use with multiple threads, so there is no way to show <strong>Delphi </strong>forms of same process on two different desktops. <em>SetThreadDesktop </em>describes this issue as followed.</p>
<blockquote><p>The  <strong>SetThreadDesktop</strong> function will fail if the calling thread has any windows or hooks on its current desktop (unless the <em>hDesktop</em> parameter is a handle to the current desktop).</p></blockquote>
<p><u>Though there is a  workaround</u> to make <strong>VCL </strong>work with <em>SetThreadDesktop </em>and <a href="http://msdn2.microsoft.com/en-us/library/ms686347(VS.85).aspx">SwitchDesktop</a>. The <em>Application </em>variable defined in unit <em>Forms </em>must be freed and then renewed. Here is the correct order :</p>
<ol>
<li>Close all your forms so the Application is going to quit.</li>
<li>Free the Application instance in your DPR file.
<div class="dean_ch" style="white-space: wrap;">Application.<span class="me1">Run</span>;<br />
Application.<span class="me1">Free</span>;</div>
</li>
<li>Then call <em>SetThreadDesktop </em>and <em>SwitchDesktop</em></li>
<li>Recreate the application object &#8211; now on the new desktop:
<div class="dean_ch" style="white-space: wrap;">Application := TApplication.<span class="me1">Create</span><span class="br0">&#40;</span><span class="kw2">nil</span><span class="br0">&#41;</span>;<br />
Application.<span class="kw3">Initialize</span>;</div>
</li>
<li>Call all the usual stuff that has to be done to show your forms</li>
</ol>
<p>&#8230;follow the same way as described to get back to the original desktop and forms (in this order!). However this has to be done in the  main project file (DPR) (except you&#8217;re going to source it out) because you cannot just free <em>Application</em> in the event method of a button click. You have to shutdown your application (not your process) and continue right after :</p>
<div class="dean_ch" style="white-space: wrap;">Application.<span class="me1">Free</span>;</div>
<p>In this way the process does not shut down and you can use <strong>VCL </strong>on one desktop at a time.</p>
<p><u>A second possibility</u> is to use <strong>VCL </strong>on one desktop and <strong>NonVCL</strong> on the other. However in this way you have to create a new thread and use your own message loop (located in the new thread).  Then you can call <em>SetThreadDesktop </em>in this thread and show the <strong>NonVCL</strong> windows.</p>
<p><u>A third possibility</u> is to execute another or the same application with <a href="http://msdn2.microsoft.com/en-us/library/ms682425.aspx"><em>CreateProcess</em></a>. This function allows you to specify the target desktop name for the new process in <em>lpDesktop </em>of the <em><a href="http://msdn2.microsoft.com/en-us/library/ms686331(VS.85).aspx">TProcessInformation</a></em> structure.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">uses</span> JwaWindows;</p>
<p><span class="kw1">var</span><br />
&nbsp; StartupInfo: TStartupInfo;<br />
&nbsp; ProcInfo : TProcessInformation;<br />
<span class="kw1">begin</span><br />
&nbsp; StartupInfo.<span class="me1">cb</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;:= <span class="kw3">SizeOf</span><span class="br0">&#40;</span>StartupInfo<span class="br0">&#41;</span>;<br />
&nbsp; StartupInfo.<span class="me1">lpDesktop</span> &nbsp; := <span class="st0">&#8216;winsta0\default&#8217;</span>;</p>
<p>&nbsp; CreateProcess<span class="br0">&#40;</span><br />
&nbsp; &nbsp; <span class="st0">&#8216;appname.exe&#8217;</span>,<span class="co1">//__in_opt &nbsp; &nbsp; LPCTSTR lpApplicationName,</span><br />
&nbsp; &nbsp; <span class="kw2">nil</span>,<span class="co1">//__inout_opt &nbsp;LPTSTR lpCommandLine,</span><br />
&nbsp; &nbsp; <span class="kw2">nil</span>,<span class="co1">//__in_opt &nbsp; &nbsp; LPSECURITY_ATTRIBUTES lpProcessAttributes,</span><br />
&nbsp; &nbsp; <span class="kw2">nil</span>,<span class="co1">//__in_opt &nbsp; &nbsp; LPSECURITY_ATTRIBUTES lpThreadAttributes,</span><br />
&nbsp; &nbsp; <span class="kw2">true</span>,<span class="co1">//__in &nbsp; &nbsp; &nbsp; &nbsp; BOOL bInheritHandles,</span><br />
&nbsp; &nbsp; CREATE_NEW_CONSOLE,<span class="co1">//__in &nbsp; &nbsp; &nbsp; &nbsp; DWORD dwCreationFlags,</span><br />
&nbsp; &nbsp; <span class="kw2">nil</span>,<span class="co1">//__in_opt &nbsp; &nbsp; LPVOID lpEnvironment,</span><br />
&nbsp; &nbsp; <span class="kw2">nil</span>,<span class="co1">//__in_opt &nbsp; &nbsp; LPCTSTR lpCurrentDirectory,</span><br />
&nbsp; &nbsp; StartInfo,<span class="co1">//__in &nbsp; &nbsp; &nbsp; &nbsp; LPSTARTUPINFO lpStartupInfo,</span><br />
&nbsp; &nbsp; ProcInfo,<span class="co1">//__out &nbsp; &nbsp; &nbsp; &nbsp;LPPROCESS_INFORMATION lpProcessInformation</span><br />
&nbsp; <span class="br0">&#41;</span>;<br />
&nbsp; CloseHandle<span class="br0">&#40;</span>ProcInfo.<span class="me1">hProcess</span><span class="br0">&#41;</span>;<br />
&nbsp; CloseHandle<span class="br0">&#40;</span>ProcInfo.<span class="me1">hThread</span><span class="br0">&#41;</span>;<br />
&#8230;</div>
<hr size="2" width="100%" /><u><strong>JWSCL</strong></u><br />
Did you know that there is already a desktop class that provides all necessary function to administer desktops? Yes, there is! It is called <a href="http://jwscldoc.delphi-jedi.net/JwsclDesktops.TJwSecurityDesktop.html">TJwSecurityDesktop</a> and resides in unit <a href="http://jwscldoc.delphi-jedi.net/JwsclDesktops.html" class="bold">JwsclDesktops</a>.<br />
<hr size="2" width="100%" /><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/19/how-to-use-vcl-and-setthreaddesktop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get the process of a window?</title>
		<link>http://blog.delphi-jedi.net/2008/03/18/how-to-get-the-process-of-a-window/</link>
		<comments>http://blog.delphi-jedi.net/2008/03/18/how-to-get-the-process-of-a-window/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 18:00:35 +0000</pubDate>
		<dc:creator>Christian Wimmer</dc:creator>
				<category><![CDATA[JEDI Windows API Headers]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[ID]]></category>
		<category><![CDATA[JWA]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[Thread]]></category>
		<category><![CDATA[Window]]></category>

		<guid isPermaLink="false">http://blog.delphi-jedi.net/2008/03/18/how-to-get-the-process-of-a-window/</guid>
		<description><![CDATA[This answer is very easy &#8211; just use GetWindowThreadProcessId JWA declares it as followed: function GetWindowThreadProcessId&#40;hWnd: HWND; lpdwProcessId: LPDWORD&#41;: DWORD; stdcall; The function returns an identifier (not a handle) and also may set lpdwProcessId to the identifier (again not a handle!) if it is not nil. Be aware that identifiers aren&#8217;t handles, so you must [...]]]></description>
			<content:encoded><![CDATA[<p>This answer is very easy &#8211; just use <a href="http://msdn2.microsoft.com/en-us/library/ms633522(VS.85).aspx">GetWindowThreadProcessId</a></p>
<p>JWA declares it as followed:</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">function</span> GetWindowThreadProcessId<span class="br0">&#40;</span>hWnd: HWND; lpdwProcessId: LPDWORD<span class="br0">&#41;</span>: <span class="kw4">DWORD</span>; <span class="kw1">stdcall</span>;</div>
<p>The function returns an identifier (not a handle) and also may set lpdwProcessId to the identifier (again not a handle!) if it is not nil. Be aware that identifiers aren&#8217;t handles, so you must not close them by using CloseHandle. Identifiers are only numbers that makes an object distinguishable from other objects of the same type.</p>
<div class="dean_ch" style="white-space: wrap;"><span class="kw1">uses</span> JwaWindows;</p>
<p><span class="kw1">var</span> ProcessID,<br />
&nbsp;ThreadID &nbsp;: <span class="kw4">DWORD</span>;<br />
&nbsp;WndHandle : HWND;</p>
<p><span class="kw1">begin</span><br />
&nbsp; WndHandle := FindWindow<span class="br0">&#40;</span>&#8230;<span class="br0">&#41;</span>;<br />
&nbsp; ThreadID := GetWindowThreadProcessId<span class="br0">&#40;</span>WndHandle, @ProcessID<span class="br0">&#41;</span>;<br />
&#8230;</div>
<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/18/how-to-get-the-process-of-a-window/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The case of the unexplained&#8230;</title>
		<link>http://blog.delphi-jedi.net/2008/03/16/the-case-of-the-unexplained/</link>
		<comments>http://blog.delphi-jedi.net/2008/03/16/the-case-of-the-unexplained/#comments</comments>
		<pubDate>Sun, 16 Mar 2008 17:51:24 +0000</pubDate>
		<dc:creator>Christian Wimmer</dc:creator>
				<category><![CDATA[Common]]></category>
		<category><![CDATA[Handle]]></category>
		<category><![CDATA[Kernel Microsoft]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[ProcessExplorer]]></category>
		<category><![CDATA[Russinovich]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://blog.delphi-jedi.net/2008/03/16/the-case-of-the-unexplained/</guid>
		<description><![CDATA[As you maybe already have noted, I use the ProcessExplorer of Mark Russinovich a lot. It is a very powerful tool, that can help you finding out what&#8217;s going on in your Windows system&#8230; Processes Threads Properties Handles Kernel Bluescreens (WinDbg) and many more If you are interested in getting an introduction into the great [...]]]></description>
			<content:encoded><![CDATA[<p>As you maybe already have noted, I use the <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">ProcessExplorer</a> of Mark Russinovich a lot. It is a very powerful tool, that can help you finding out what&#8217;s going on in your Windows system&#8230;</p>
<ul>
<li>
<div>Processes</div>
</li>
<li>
<div>Threads</div>
</li>
<li>
<div>Properties</div>
</li>
<li>
<div>Handles</div>
</li>
<li>
<div>Kernel</div>
</li>
<li>Bluescreens (WinDbg)</li>
<li>
<div>and many more</div>
</li>
</ul>
<p>If you are interested in getting an introduction into the great application, you should watch this video. Mark presents his tool with many examples from his own experiences.</p>
<p><a href="http://www.microsoft.com/emea/spotlight/sessionh.aspx?videoid=722">http://www.microsoft.com/emea/spotlight/sessionh.aspx?videoid=722</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.delphi-jedi.net/2008/03/16/the-case-of-the-unexplained/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>

