<?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>David DeWinter</title>
	<atom:link href="http://blogs.rev-net.com/ddewinter/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.rev-net.com/ddewinter</link>
	<description>A Developer's Melting Pot: LINQ to SQL, Entity Framework, .NET Security...</description>
	<lastBuildDate>Tue, 02 Mar 2010 16:02:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tip #20 &#8211; Opting Out of Security Changes in .NET 4 in ASP.NET and Custom AppDomains</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 15:53:01 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[CAS Policy]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/</guid>
		<description><![CDATA[Legacy CAS Policy in ASP.NET
In a previous tip I discussed how you could re-enable CAS policy in applications running in .NET 4 by adding a switch to the application configuration file. However, Constantin Baciu brought up that even when using this configuration switch in a web.config, ASP.NET still threw the SecurityException:
This method explicitly uses CAS [...]]]></description>
			<content:encoded><![CDATA[<h3>Legacy CAS Policy in ASP.NET</h3>
<p><a href="http://blogs.rev-net.com/ddewinter/2009/05/20/opting-out-of-security-changes-in-net-4/">In a previous tip</a> I discussed how you could re-enable CAS policy in applications running in .NET 4 by adding a switch to the application configuration file. However, <a href="http://blogs.rev-net.com/ddewinter/2009/05/20/opting-out-of-security-changes-in-net-4/#comment-17758">Constantin Baciu</a> brought up that even when using this configuration switch in a web.config, ASP.NET still threw the SecurityException:</p>
<blockquote><p>This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see <a href="http://go.microsoft.com/fwlink/?LinkID=155570">http://go.microsoft.com/fwlink/?LinkID=155570</a> for more information.</p>
</blockquote>
<p>Definitely a confusing error message, since you already added the NetFx40_LegacySecurityPolicy configuration switch. The problem is that in order for this switch to actually work, it must be in the executable&#8217;s application configuration file. Putting in the web.config has no effect; the switch must be in the configuration file for the server executable, like IIS or Visual Studio&#8217;s local web server. Since just about all web hosts I know of won&#8217;t let you modify the configuration file for the server, we need a different option.</p>
<p>Fortunately, ASP.NET does support enabling CAS policy in .NET 4, but it&#8217;s with a different switch in the web.config. Enter the new <a href="http://msdn.microsoft.com/en-us/library/dd984947%28VS.100%29.aspx">legacyCasModel attribute</a> of the <a href="http://msdn.microsoft.com/en-us/library/dd984947%28VS.100%29.aspx">trust element</a>. This is the same element that allows you to configure the trust level of the application.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">trust</span><span style="color: blue"> </span><span style="color: red">legacyCasModel</span><span style="color: blue">=</span>&quot;<span style="color: blue">true</span>&quot;<span style="color: blue">/&gt;</span></p>
</p></div>
<p>This enables you to get past the SecurityException above, but keep the following things in mind:</p>
<ul>
<li>You will be using the legacy security configurations from .NET 3.5 when using ASP.NET. These permission sets are kept in the runtime directory&#8217;s Config folder and have names like legacy.web_mediumtrust.config and legacy.web_minimaltrust.config. </li>
<li>Security asserts are no longer required when only full trust code is on the call stack. This is because ASP.NET will still set up a fully trusted AppDomain, because it relies on CAS Policy to apply specific permissions to assemblies. In .NET 4 ASP.NET sets up a <a href="http://blogs.rev-net.com/ddewinter/2009/05/22/how-to-host-a-partial-trust-sandbox/">sandbox AppDomain</a> by default, which means that even if only fully trusted code is on the call stack, as soon as a permission demand occurs, the stack walk will fail once it hits the AppDomain boundary. </li>
<li>Of course, CAS Policy is now enabled, which means the machine&#8217;s policy configuration affects what permissions an assembly has.</li>
</ul>
<h3>Legacy CAS Policy at the AppDomain Level</h3>
<p>When you specify the legacyCasModel attribute in the web.config, ASP.NET uses that information to set up an AppDomain that has legacy CAS policy enabled. The good news is that by using some lower-level APIs, you can do the same thing.</p>
<p>You may ask &quot;why would you want to do this?&quot; One scenario I can think of is for an existing application that uses AppDomains to isolate other pieces of code (e.g. for add-ins), but some of these old pieces of code use the older security APIs that are obsolete in .NET 4.</p>
<p>The key API is <a href="http://msdn.microsoft.com/en-us/library/system.appdomainsetup.setcompatibilityswitches%28VS.100%29.aspx">AppDomainSetup.SetCompatibilitySwitches</a>; remember that when setting up an AppDomain you can optionally use an instance of the AppDomainSetup class to initialize the AppDomain. The code example below shows how this is done.</p>
<h4>C#</h4>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">var</span> setup = <span style="color: blue">new</span> <span style="color: #2b91af">AppDomainSetup</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; ApplicationBase = <span style="color: #2b91af">Environment</span>.CurrentDirectory</p>
<p style="margin: 0px">};</p>
<p style="margin: 0px">setup.SetCompatibilitySwitches(<span style="color: blue">new</span>[] { <span style="color: #a31515">&quot;NetFx40_LegacySecurityPolicy&quot;</span> });</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: #2b91af">AppDomain</span> casPolicyEnabledDomain = <span style="color: #2b91af">AppDomain</span>.CreateDomain(<span style="color: #a31515">&quot;CAS Policy Enabled Domain&quot;</span>, <span style="color: blue">null</span>, setup);</p>
</p></div>
<h4>VB</h4>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Dim</span> setup = <span style="color: blue">New</span> <span style="color: #2b91af">AppDomainSetup</span> <span style="color: blue">With</span> {.ApplicationBase = <span style="color: #2b91af">Environment</span>.CurrentDirectory}</p>
<p style="margin: 0px">setup.SetCompatibilitySwitches(<span style="color: blue">New</span> <span style="color: blue">String</span>() {<span style="color: #a31515">&quot;NetFx40_LegacySecurityPolicy&quot;</span>})</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">Dim</span> casPolicyEnabledDomain <span style="color: blue">As</span> <span style="color: #2b91af">AppDomain</span> = <span style="color: #2b91af">AppDomain</span>.CreateDomain(<span style="color: #a31515">&quot;CAS Policy Enabled Domain&quot;</span>, <span style="color: blue">Nothing</span>, setup)</p>
</p></div>
<p>And that&#8217;s all there is to it. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>We&#8217;re Hiring! Test Positions Open on Entity Framework and WCF Data Services (Astoria) Teams</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 16:33:14 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/</guid>
		<description><![CDATA[With work on Visual Studio 2010 winding down, both the Entity Framework and Astoria teams have test engineer positions open. Here are the job postings:

Astoria 
Entity Framework 

Note: If the job descriptions above still say you need C/C++ experience, this is not true. If you don&#8217;t have experience in these areas, don&#8217;t let that discourage [...]]]></description>
			<content:encoded><![CDATA[<p>With work on Visual Studio 2010 winding down, both the Entity Framework and Astoria teams have test engineer positions open. Here are the job postings:</p>
<ul>
<li><a href="https://careers.microsoft.com/JobDetails.aspx?ss=&amp;pg=0&amp;so=&amp;rw=1&amp;jid=11878&amp;jlang=EN">Astoria</a> </li>
<li><a href="https://careers.microsoft.com/JobDetails.aspx?ss=&amp;pg=0&amp;so=&amp;rw=1&amp;jid=11877&amp;jlang=EN">Entity Framework</a> </li>
</ul>
<p><strong><em>Note: If the job descriptions above still say you need C/C++ experience, this is not true. If you don&#8217;t have experience in these areas, don&#8217;t let that discourage you from applying! </em></strong>In fact, I didn&#8217;t have C/C++ experience upon arriving here…</p>
<p>Now, I know what you&#8217;re thinking—&quot;ugh, test, you mean those guys who sit on the other side of the building and click on things all day?&quot; And actually, when I first joined as a tester, I had a bit of the same mentality. That&#8217;s why I wanted to find out for myself what testers actually do. I have worked at Microsoft for a year now as a tester on the Entity Framework team and have learned a lot about the discipline of test, but I know I have only scratched the surface. Also, I should clarify that these positions are opening on the <em>runtime</em> team, so you won&#8217;t be clicking on things that much, if at all. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My background as a .NET developer has really helped me excel as a test engineer. The challenges that we face are very diverse and as a result I think there are many more opportunities for growth in the test discipline than in other disciplines. In a sense, we are developers ourselves; we don&#8217;t ship code (typically), but we must have the ingenuity and creativity to verify the code that does ship meets a high quality bar. Test can be a very demanding discipline, especially for those people who have a background in development.</p>
<p>If you want to know more about my experiences feel free to contact me using the contact form page, and I hope you consider applying if you&#8217;re looking for a challenging job.</p>
<p>P.S. I should note that the Astoria job description is missing an important sales pitch—you get to work with Pablo Castro! Yes, <a href="http://blogs.msdn.com/pablo/">that Pablo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>POCO Templates for Entity Framework v4 Beta 2 Released</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 20:02:31 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[POCO]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/</guid>
		<description><![CDATA[Today we have finally released an update to the POCO Templates that is compatible with Visual Studio 2010 Beta 2. Official announcement on the ADO.NET team blog.
One thing I will highlight is that the templates won&#8217;t be released with the final version of Visual Studio 2010. Instead we will continue to push releases through the [...]]]></description>
			<content:encoded><![CDATA[<p>Today we have finally released an update to the POCO Templates that is compatible with Visual Studio 2010 Beta 2. <a href="http://blogs.msdn.com/adonet/archive/2010/01/25/announcing-the-entity-framework-poco-template-update-for-visual-studio-2010-beta-2.aspx">Official announcement on the ADO.NET team blog.</a></p>
<p>One thing I will highlight is that the templates won&#8217;t be released with the final version of Visual Studio 2010. Instead we will continue to push releases through the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/">Visual Studio Extension Gallery</a>. This means you can easily download the POCO Templates using Visual Studio&#8217;s Extension Manager (accessed through the Tools menu).</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="Extension Manager menu item" border="0" alt="Extension Manager menu item" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image_thumb.png" width="613" height="534" /></a> </p>
<p>Once in the Extension Manager, click the Online Gallery tab on the left side of the window and use the search box (top right) to type in &quot;POCO template.&quot; After a few seconds you should see the POCO template extensions appear. There are two extensions, one for C# and one for Visual Basic.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image1.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image_thumb1.png" width="640" height="342" /></a> </p>
<p>After you install the extension, you&#8217;ll have a new item template for C# projects or Visual Basic projects (depending on which you installed) that will allow you to generate POCO entities from an Entity Framework model. For more in depth information on how to use the POCO templates, have a look at the <a href="http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx">POCO Template Walkthrough</a>.</p>
<p>As always we are interested in your feedback so feel free to request features or report bugs through the <a href="https://connect.microsoft.com/VisualStudio/content/content.aspx?ContentID=12362">Microsoft Connect web site</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CAS Policy on 64-bit Machines &#8211; #19</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/01/10/cas-policy-on-64-bit-machines-19/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/01/10/cas-policy-on-64-bit-machines-19/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 04:43:04 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[CAS Policy]]></category>
		<category><![CDATA[caspol.exe]]></category>
		<category><![CDATA[permissions]]></category>
		<category><![CDATA[policy]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/10/cas-policy-on-64-bit-machines-19/</guid>
		<description><![CDATA[Well it’s been quite a while since my last post. I hope you all had a happy holiday season!
Today I’m going to talk about an issue I saw recently with a 64-bit machine and the partial trust tests for the Entity Framework. Even though .NET 4 disables CAS policy, it is more interesting for the [...]]]></description>
			<content:encoded><![CDATA[<p>Well it’s been quite a while since my last post. I hope you all had a happy holiday season!</p>
<p>Today I’m going to talk about an issue I saw recently with a 64-bit machine and the partial trust tests for the Entity Framework. Even though .NET 4 <a href="http://blogs.rev-net.com/ddewinter/2009/05/20/whats-new-with-security-in-net-4/">disables CAS policy</a>, it is more interesting for the Entity Framework to test with CAS policy enabled, because this allows us to configure security permissions on a per-assembly basis instead of per-AppDomain. The workflow for the tests is similar to the following:</p>
<ol>
<li>Enable CAS policy. </li>
<li>Use the System.Security.Policy APIs to configure the correct set of permissions for the test assemblies. (Some have ReflectionPermission, some don’t, etc.) This is a separate EXE from the next step. </li>
<li>Initialize the test harness and run the test cases. </li>
</ol>
<p>When running in our lab recently, a few test cases failed for reasons I could not explain. Further analysis revealed that the tests were running in full trust, and so these negative test cases failed because the expected exceptions were not thrown. How did this happen?</p>
<h3>Diagnosis</h3>
<p>The first thing I did was to experiment with the command line switches of caspol.exe. I started a new command prompt and ran the following command. The –rsp switch stands for <strong>r</strong>e<strong>s</strong>olve <strong>p</strong>ermission set. System.Data.Test.PartialTrust.Caller.dll is the name of one of the assemblies that needs a custom permission set.</p>
<p><strong>caspol.exe –rsp System.Data.Test.PartialTrust.Caller.dll</strong></p>
<blockquote><p>Microsoft (R) .NET Framework CasPol 4.0.21006.1      <br />Copyright (c) Microsoft Corporation.&#160; All rights reserved. </p>
<p>WARNING: The .NET Framework does not apply CAS policy by default. Any settings      <br />shown or modified by CasPol will only affect applications that opt into using       <br />CAS policy. </p>
<p>Please see <a href="http://go.microsoft.com/fwlink/?LinkId=131738">http://go.microsoft.com/fwlink/?LinkId=131738</a> for more information. </p>
<p>Resolving permissions for level = Enterprise      <br />Resolving permissions for level = Machine       <br />Resolving permissions for level = User </p>
<p>Grant =      <br /><strong>&lt;PermissionSet class=&quot;System.Security.PermissionSet&quot;        <br />version=&quot;1&quot;         <br />Unrestricted=&quot;true&quot;/&gt;</strong> </p>
<p>Success</p>
</blockquote>
<p>This had at least confirmed my suspicions that the tests were running in full trust. I looked back at the original executable code that configures the policy for the assemblies. It did not seem out of the ordinary, and besides, it had worked in many previous test runs.</p>
<p><strong>C#</strong></p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">static</span> <span style="color: blue">void</span> SetPermissions()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Find the machine policy level</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">PolicyLevel</span> machinePolicyLevel = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">IEnumerator</span> ph = <span style="color: #2b91af">SecurityManager</span>.PolicyHierarchy();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">while</span> (ph.MoveNext())</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">PolicyLevel</span> pl = (<span style="color: #2b91af">PolicyLevel</span>)ph.Current;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (pl.Label == <span style="color: #a31515">&quot;Machine&quot;</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; machinePolicyLevel = pl;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">break</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">NamedPermissionSet</span> ps = <span style="color: blue">new</span> <span style="color: #2b91af">NamedPermissionSet</span>(<span style="color: #a31515">&quot;CallerPermSet&quot;</span>, <span style="color: #2b91af">PermissionState</span>.None);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Add permissions (omitted)</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">StrongNamePublicKeyBlob</span> key = <span style="color: blue">typeof</span>(<span style="color: #2b91af">Caller</span>).Assembly.Evidence</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160; .OfType&lt;<span style="color: #2b91af">StrongName</span>&gt;().First().PublicKey;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">IMembershipCondition</span> mc = <span style="color: blue">new</span> <span style="color: #2b91af">StrongNameMembershipCondition</span>(key, <span style="color: blue">null</span>, <span style="color: blue">null</span>);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Create the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">PolicyStatement</span> policy = <span style="color: blue">new</span> <span style="color: #2b91af">PolicyStatement</span>(ps, <span style="color: #2b91af">PolicyStatementAttribute</span>.Exclusive);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">CodeGroup</span> codeGroup = <span style="color: blue">new</span> <span style="color: #2b91af">UnionCodeGroup</span>(mc, policy);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Description = <span style="color: #a31515">&quot;Permissions for PT Caller&quot;</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Name = <span style="color: #a31515">&quot;CallerGroup&quot;</span>;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Add the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; machinePolicyLevel.RootCodeGroup.AddChild(codeGroup);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Save changes</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">SecurityManager</span>.SavePolicy();</p>
<p style="margin: 0px">}</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Sub</span> SetPermissions()</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Find the machine policy level</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> machinePolicyLevel <span style="color: blue">As</span> PolicyLevel = <span style="color: blue">Nothing</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> ph <span style="color: blue">As</span> IEnumerator = SecurityManager.PolicyHierarchy()</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">While</span> ph.MoveNext()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">Dim</span> pl <span style="color: blue">As</span> PolicyLevel = <span style="color: blue">DirectCast</span>(ph.Current, PolicyLevel)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">If</span> pl.Label = <span style="color: #a31515">&quot;Machine&quot;</span> <span style="color: blue">Then</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; machinePolicyLevel = pl</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">Exit</span> <span style="color: blue">While</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">End</span> <span style="color: blue">If</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">End</span> <span style="color: blue">While</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> ps <span style="color: blue">As</span> NamedPermissionSet = <span style="color: blue">New</span> NamedPermissionSet(<span style="color: #a31515">&quot;CallerPermSet&quot;</span>, PermissionState.None)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Add permissions (omitted)</span></p>
<p style="margin: 0px"><span style="color: green"></span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> key <span style="color: blue">As</span> StrongNamePublicKeyBlob = <span style="color: blue">GetType</span>(Caller).Assembly.Evidence _</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .OfType(<span style="color: blue">Of</span> StrongName)().First().PublicKey()</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> mc <span style="color: blue">As</span> IMembershipCondition = <span style="color: blue">New</span> StrongNameMembershipCondition(key, <span style="color: blue">Nothing</span>, <span style="color: blue">Nothing</span>)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Create the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> policy <span style="color: blue">As</span> PolicyStatement = <span style="color: blue">New</span> PolicyStatement(ps, PolicyStatementAttribute.Exclusive)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> codeGroup <span style="color: blue">As</span> CodeGroup = <span style="color: blue">New</span> UnionCodeGroup(mc, policy)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Description = <span style="color: #a31515">&quot;Permissions for PT Caller&quot;</span></p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Name = <span style="color: #a31515">&quot;CallerGroup&quot;</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Add the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; machinePolicyLevel.RootCodeGroup.AddChild(codeGroup)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Save changes</span></p>
<p style="margin: 0px">&#160;&#160;&#160; SecurityManager.SavePolicy()</p>
<p style="margin: 0px"><span style="color: blue">End</span> <span style="color: blue">Sub</span></p>
</p></div>
<p>My next plan of attack was to determine whether the changes to security policy were really being made. Even though no exceptions were thrown, I couldn’t understand why caspol –rsp would tell me that the framework would run our test assembly in full trust. i tried listing all the code groups from caspol under the Machine level:</p>
<p><strong>caspol –m –lg</strong></p>
<blockquote><p>Microsoft (R) .NET Framework CasPol 4.0.21006.1     <br />Copyright (c) Microsoft Corporation.&#160; All rights reserved. </p>
<p>WARNING: The .NET Framework does not apply CAS policy by default. Any settings     <br />shown or modified by CasPol will only affect applications that opt into using      <br />CAS policy. </p>
<p>Please see <a href="http://go.microsoft.com/fwlink/?LinkId=131738">http://go.microsoft.com/fwlink/?LinkId=131738</a> for more information. </p>
<p>Policy change prompt is ON </p>
<p>Level = Machine </p>
<p>Code Groups: </p>
<p>1.&#160; All code: Nothing     <br />&#160;&#160; 1.1.&#160; Zone &#8211; MyComputer: FullTrust      <br />&#160;&#160;&#160;&#160;&#160; 1.1.1.&#160; StrongName &#8211; 00240000048000009400000006020000002400005253413100040      <br />0000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE      <br />79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E82      <br />1C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8      <br />A12436518206DC093344D5AD293: FullTrust      <br />&#160;&#160;&#160;&#160;&#160; 1.1.2.&#160; StrongName &#8211; 00000000000000000400000000000000: FullTrust      <br />&#160;&#160; 1.2.&#160; Zone &#8211; Intranet: LocalIntranet      <br />&#160;&#160;&#160;&#160;&#160; 1.2.1.&#160; All code: Same site Web      <br />&#160;&#160;&#160;&#160;&#160; 1.2.2.&#160; All code: Same directory FileIO &#8211; &#8216;Read, PathDiscovery&#8217;      <br />&#160;&#160; 1.3.&#160; Zone &#8211; Internet: Internet      <br />&#160;&#160;&#160;&#160;&#160; 1.3.1.&#160; All code: Same site Web      <br />&#160;&#160; 1.4.&#160; Zone &#8211; Untrusted: Nothing      <br />&#160;&#160; 1.5.&#160; Zone &#8211; Trusted: Internet      <br />&#160;&#160;&#160;&#160;&#160; 1.5.1.&#160; All code: Same site Web      <br />Success</p>
</blockquote>
<p>The custom code groups weren’t there! But if I inspected the code groups in code after running the setup executable, then they did appear.</p>
<h3>Resolution</h3>
<p>Eventually I just got frustrated and pulled out <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx">procmon</a> to figure out what caspol.exe was doing under the covers. I saw it reading and writing from configuration files in the .NET Framework directory, and that’s when it hit me. The setup executable that writes to security policy was compiled as AnyCPU and thus any security policy edits were flushed to the configuration files in the %WINDIR%\Microsoft.NET\Framework64 directory. Our test harness was erroneously running as a 32-bit application on a 64-bit machine, which means the security policy it read was actually from the %WINDIR%\Microsoft.NET\Framework directory!</p>
<p><strong>There are two versions of caspol.exe on 64-bit machines! </strong>One is for 32-bit applications, and the other is for 64-bit. As you can probably infer, I was incorrectly using the 32-bit one in my diagnosis above, which is why I never saw any of the custom code groups added to security policy.</p>
<p>It took a couple hours to figure this out, so I hope this post can help save you some time if you ever run into a similar situation!</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/01/10/cas-policy-on-64-bit-machines-19/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Asserting for Permissions in .NET 4 &#8211; #18</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/06/25/asserting-for-permissions-in-net-4/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/06/25/asserting-for-permissions-in-net-4/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 14:35:24 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/25/asserting-for-permissions-in-net-4/</guid>
		<description><![CDATA[Security asserts are a way to tell the CLR to stop checking for permissions past a certain point in the call stack. Of course, not all code is allowed to assert, or we&#8217;d have some big security problems to worry about. Specifically, partial trust code and security transparent code cannot assert for permissions. You may [...]]]></description>
			<content:encoded><![CDATA[<p>Security asserts are a way to tell the CLR to stop checking for permissions past a certain point in the call stack. Of course, not all code is allowed to assert, or we&#8217;d have some big security problems to worry about. Specifically, partial trust code and security transparent code cannot assert for permissions. You may ask why asserting is useful, then, when only fully trusted code can do it.</p>
<p>One use case where asserts are beneficial is in testing products in partial trust. Say we have some test code that runs in partial trust and calls LINQ to SQL to test that a certain scenario still works in a medium trust environment. However, the test framework that the test uses requires permissions that are not granted in medium trust for some operations. Since the test framework knows that its callers won&#8217;t do anything malicious, it can assert for the permissions it needs to run these privileged operations. To do this, however, the test framework must be fully trusted.</p>
<p>Let&#8217;s say I have a test that runs in medium trust and calls some code in LINQ to SQL to verify that that code path works under medium trust. However, during some part of the test, the test framework itself needs to read an environment variable to determine which version of SQL Server to execute the test against (e.g. SQL Server 2000, SQL Server 2005, or SQL Server 2008).</p>
<p>Here&#8217;s the beginning of a test. (Keep in mind that this code is just an example. It doesn&#8217;t represent real types that we use in the LINQ to SQL test code, but it does demonstrate security assertions, which is something we do in the test framework.)</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">void</span> TestMediumTrust()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">DataContext</span> context = <span style="color: #2b91af">DataContextFactory</span>.CreateDataContext();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">}</p>
</p></div>
<p>And here&#8217;s the code in the test framework that the test above calls.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">DataContextFactory</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: #2b91af">DataContext</span> CreateDataContext()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">string</span> sqlVersion = ReadSqlVersion();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Return the correct data context.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">SecuritySafeCritical</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">EnvironmentPermission</span>(<span style="color: #2b91af">SecurityAction</span>.Assert, Read = <span style="color: #a31515">&quot;SQLVERSION&quot;</span>)]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span> ReadSqlVersion()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">Environment</span>.GetEnvironmentVariable(<span style="color: #a31515">&quot;SQLVERSION&quot;</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The TestMediumTrust method resides in a test assembly, while the DataContextFactory resides in another assembly which is part of the test framework. When we <a href="http://blogs.rev-net.com/ddewinter/2009/05/22/how-to-host-a-partial-trust-sandbox/">set up the medium-trust sandbox</a> in which to run the test, we tell the CLR to fully trust the test framework assembly. Full trust implies two things: (1) that SafeCritical and Critical annotations are respected and (2) we can assert for permissions. Remember that security transparent code cannot assert for permissions; this is why the ReadSqlVersion method above must be SafeCritical.</p>
<p>Medium trust code does not have permission to read the SQLVERSION environment variable, so under normal circumstances calling Environment.GetEnvironmentVariable would throw a SecurityException. This is because the .NET Framework itself will do a full Demand for the EnvironmentPermission to read the SQLVERSION variable. Permission Demands walk the entire call stack to ensure that every frame in the stack has the relevant permissions; since the test code runs in medium trust, the CLR will throw once it checks the TestMediumTrust method.</p>
<p>Asserts are a way to tell the CLR to stop checking for permissions past a particular stack frame. Thus with the assert in place on the ReadSqlVersion method, the EnvironmentPermission check stops prematurely and the permission Demand will succeed. To put that graphically…</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/06/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/06/image-thumb1.png" width="813" height="149" /></a> </p>
<p>So what changes in .NET 4? The recommended guidance is now to assert for full trust instead of for a specific permission. This advice seems to contradict the principle of least privilege, but in reality, if you layer your transparent and critical code appropriately, then security transparency can help you realize least privilege much more effectively. A second reason is that asserting for a specific permission causes a dependency on the underlying implementation. (This is a less convincing argument for me personally.) So the ReadSqlVersion method above now becomes…</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">SecuritySafeCritical</span>]</p>
<p style="margin: 0px">[<span style="color: #2b91af">PermissionSet</span>(<span style="color: #2b91af">SecurityAction</span>.Assert, Unrestricted = <span style="color: blue">true</span>)]</p>
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span> ReadSqlVersion()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">Environment</span>.GetEnvironmentVariable(<span style="color: #a31515">&quot;SQLVERSION&quot;</span>);</p>
<p style="margin: 0px">}</p>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/06/25/asserting-for-permissions-in-net-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Build APIs with Transparency in Mind &#8211; #17</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/06/23/how-to-build-apis-with-transparency-in-mind/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/06/23/how-to-build-apis-with-transparency-in-mind/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 13:08:50 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[API Design]]></category>
		<category><![CDATA[security transparency]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/23/how-to-build-apis-with-transparency-in-mind/</guid>
		<description><![CDATA[In the .NET Framework there are a few types which expose both &#34;safe&#34; and &#34;unsafe&#34; equivalents of the same method. Both methods achieve the same goal e.g. BinaryFormatter.Deserialize and BinaryFormatter.UnsafeDeserialize will both deserialize a stream into a .NET object, but the safe variant will do a full Demand for the appropriate permissions. This ensures that [...]]]></description>
			<content:encoded><![CDATA[<p>In the .NET Framework there are a few types which expose both &quot;safe&quot; and &quot;unsafe&quot; equivalents of the same method. Both methods achieve the same goal e.g. BinaryFormatter.Deserialize and BinaryFormatter.UnsafeDeserialize will both deserialize a stream into a .NET object, but the safe variant will do a full Demand for the appropriate permissions. This ensures that callers without proper permissions will fail when trying to call the safe method. The unsafe variant, on the other hand, ensures only that the <em>immediate</em> caller has the necessary permissions. Previous versions of the .NET Framework enforce these invariants with Demands and LinkDemands, as shown in the example below. (Note that this isn&#8217;t exactly what you&#8217;ll see for these methods in the BinaryFormatter class if you examine them in Reflector, but the permission Demand and LinkDemand are present.)</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">SecurityPermission</span>(<span style="color: #2b91af">SecurityAction</span>.Demand, SerializationFormatter = <span style="color: blue">true</span>)]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">object</span> Deserialize(<span style="color: #2b91af">Stream</span> serializationStream)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160; <span style="color: blue">return this</span>.UnsafeDeserialize(serializationStream);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">[<span style="color: #2b91af">SecurityPermission</span>(<span style="color: #2b91af">SecurityAction</span>.LinkDemand, SerializationFormatter = <span style="color: blue">true</span>)]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">object</span> UnsafeDeserialize(<span style="color: #2b91af">Stream</span> serializationStream)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Method body</span></p>
<p style="margin: 0px">}</p>
</p></div>
<p>The reason for the two different versions is that a permission Demand is expensive because it has to check the permissions of every frame in the call stack. If you <strong>know</strong> that you aren&#8217;t introducing a security hole by calling an unsafe method, then you can skip the permission Demand and avoid the performance hit. </p>
<p>In .NET 4 under the Level 2 security rules, LinkDemands have been replaced by the SecurityCriticalAttribute, which means the UnsafeDeserialize will look similar to this.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">SecurityCritical</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">object</span> UnsafeDeserialize(<span style="color: #2b91af">Stream</span> serializationStream)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Method body</span></p>
<p style="margin: 0px">}</p>
</p></div>
<p>Methods annotated with LinkDemands should migrate to use the SecurityCriticalAttribute because the whole purpose of <a href="http://blogs.rev-net.com/ddewinter/2009/05/28/introduction-to-security-transparency-in-net-4/">security transparency</a> is to promote this kind of safe/unsafe API layering. When a method is decorated with the SecurityCriticalAttribute, the CLR ensures that no security transparent code can call that method. When you consider that all code running in partial trust is security transparent, the SecurityCriticalAttribute is effectively the same as a LinkDemand for full trust.</p>
<p>Be careful though! This API layering works for the .NET Framework because the assemblies are installed in the GAC and are therefore fully trusted, even in a partial trust sandbox. If the assembly you create is loaded into a partial trust sandbox but is <strong>not</strong> fully trusted, then the SecurityCriticalAttribute will not enforce anything. Remember, all partial trust code is security transparent, even code annotated with the SecurityCriticalAttribute.</p>
<p>Finally, if your assembly is not intended for partially trusted callers, then do you don&#8217;t need to worry about any of this. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Check out the <a href="http://msdn.microsoft.com/en-us/library/3ky50t49(VS.100).aspx">.NET 4 documentation on Demands vs. LinkDemands</a> for more information.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:7844ae8a-04c2-4b99-a58f-1e0527229cc5" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/.NET+Framework" rel="tag">.NET Framework</a>,<a href="http://technorati.com/tags/API+Design" rel="tag">API Design</a>,<a href="http://technorati.com/tags/.NET+4" rel="tag">.NET 4</a>,<a href="http://technorati.com/tags/security+transparency" rel="tag">security transparency</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/06/23/how-to-build-apis-with-transparency-in-mind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mixing Level 1 and Level 2 Transparency Rules – #16</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/06/09/mixing-level-1-and-level-2-transparency-rules/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/06/09/mixing-level-1-and-level-2-transparency-rules/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 12:56:40 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[Level 1]]></category>
		<category><![CDATA[Level 2]]></category>
		<category><![CDATA[partial trust]]></category>
		<category><![CDATA[SecurityRulesAttribute]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/09/mixing-level-1-and-level-2-transparency-rules/</guid>
		<description><![CDATA[Today&#8217;s tip addresses how assemblies using different transparency rules (CLR v2 and CLR v4) interact with each other in the same AppDomain. Remember you can use the SecurityRulesAttribute to specify which level of security rules your assemblies adhere to. The default in .NET 4 is level 2.
There are only two cases here—a level 1 assembly [...]]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s tip addresses how assemblies using different transparency rules (<a href="http://blogs.rev-net.com/ddewinter/2009/05/18/using-transparency-in-clr-2/">CLR v2</a> and <a href="http://blogs.rev-net.com/ddewinter/2009/05/28/introduction-to-security-transparency-in-net-4/">CLR v4</a>) interact with each other in the same AppDomain. Remember you can use the <a href="http://blogs.rev-net.com/ddewinter/2009/06/08/the-securityrulesattribute/">SecurityRulesAttribute</a> to specify which level of security rules your assemblies adhere to. The default in .NET 4 is level 2.</p>
<p>There are only two cases here—a level 1 assembly calling a level 2 assembly, and a level 2 assembly calling a level 1 assembly. Let&#8217;s take them one at a time.</p>
<p><strong>Level 2 Assembly Calls Level 1 Assembly</strong></p>
<p>Transparency rules are not enforced across assembly boundaries under the level 1 rules, but they are under the level 2 rules. When a level 2 assembly calls a level 1 assembly, transparency violations are <strong>not</strong> enforced—that is, if level 2 transparent code calls a level 1 critical method in another assembly, the call succeeds.</p>
<p><strong>Level 1 Assembly Calls Level 2 Assembly</strong></p>
<p>You might think that transparency is enforced across the assembly boundary since the roles are now reversed, but the CLR acts a bit more interestingly than that. If <em>partial-trust</em> code from a level 1 assembly tries to call a critical method in a level 2 <em>full-trust</em> assembly, then the call fails. Level 1 assemblies, which use the CLR v2&#8217;s transparency semantics, have no way to interpret a public security critical method as it exists in level 2; such a concept didn&#8217;t exist back in the second version of the CLR. Because of this, the CLR goes to great lengths to make everything appear as level 1 to the calling assembly. To do this the CLR transforms the method marked SecurityCritical into a LinkDemand for FullTrust. Thus the call to a public critical method from partial trust code fails.</p>
<p>In the CLR v4, methods that were marked with LinkDemands for FullTrust are now marked SecurityCritical, which is a stronger enforcement mechanism because it prevents all partial-trust code <em>and</em> all transparent code from calling it. It is not a stretch to see that the CLR will transform the SecurityCritical annotation back into a LinkDemand for FullTrust to make everything appear as level 1 to the level 1 assembly.</p>
<p>This means that transparent code in a level 1 assembly <strong>can</strong> call public critical code in a level 2 assembly if the level 1 assembly is fully trusted. The rule states only that partial trust code in a level 1 assembly cannot call fully trusted security critical code in a level 2 assembly.</p>
<p>Furthermore, partial trust code is always security transparent and thus can never call security critical code.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:74d9ec77-c2b8-46a9-ba35-c0fc3c6c7987" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/.NET" rel="tag">.NET</a>,<a href="http://technorati.com/tags/security+tips" rel="tag">security tips</a>,<a href="http://technorati.com/tags/SecurityRulesAttribute" rel="tag">SecurityRulesAttribute</a>,<a href="http://technorati.com/tags/Level+1" rel="tag">Level 1</a>,<a href="http://technorati.com/tags/Level+2" rel="tag">Level 2</a>,<a href="http://technorati.com/tags/partial+trust" rel="tag">partial trust</a>,<a href="http://technorati.com/tags/.NET+4" rel="tag">.NET 4</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/06/09/mixing-level-1-and-level-2-transparency-rules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The SecurityRulesAttribute &#8211; #15</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/06/08/the-securityrulesattribute/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/06/08/the-securityrulesattribute/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 12:07:35 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[IL Verification]]></category>
		<category><![CDATA[SecurityRulesAttribute]]></category>
		<category><![CDATA[transparency]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/08/the-securityrulesattribute/</guid>
		<description><![CDATA[The SecurityRulesAttribute is a new attribute class introduced in .NET 4.0 to specify which set of security rules a particular assembly adheres to. The attribute is specified on the assembly level, and allows you to specify two pieces of information.
The first and more important piece is the version of transparency that your assembly follows. If [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/system.security.securityrulesattribute(VS.100).aspx">SecurityRulesAttribute</a> is a new attribute class introduced in .NET 4.0 to specify which set of security rules a particular assembly adheres to. The attribute is specified on the assembly level, and allows you to specify two pieces of information.</p>
<p>The first and more important piece is the version of transparency that your assembly follows. If you want to use the <a href="http://blogs.rev-net.com/ddewinter/2009/05/19/transparent-code-behavior-in-clr-2/">.NET 2.0 interpretation of transparency</a>, specify SecurityRuleSet.Level1 as the argument to the SecurityRulesAttribute constructor. If you want to use the .NET 4.0 interpretation of transparency, specify SecurityRuleSet.Level2. Level2 is also the default for assemblies built on the .NET 4.0 runtime.</p>
<p>For CLRv2 transparency semantics:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: blue">assembly</span>: <span style="color: #2b91af">SecurityRules</span>(<span style="color: #2b91af">SecurityRuleSet</span>.Level1)]</p>
</p></div>
<p>For CLRv4 transparency semantics:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: blue">assembly</span>: <span style="color: #2b91af">SecurityRules</span>(<span style="color: #2b91af">SecurityRuleSet</span>.Level2)]</p>
</p></div>
<p>The second piece allows to tell the CLR that you want to skip IL verification of your assembly when it is fully trusted and transparent. Remember, transparent code can&#8217;t contain unverifiable code or P/Invokes, so the CLR usually must check that the transparent code it loads does not violate these invariants. You can skip this verification to increase your performance slightly when the JIT compiler compiles your code, but remember that doing this will allow unverifiable code in your assembly. I&#8217;d recommend using this only if you don&#8217;t have unverifiable code in your transparent assembly.</p>
<p>That last scenario is slightly abstract, so I want to show an example of the difference.</p>
<p><strong>SecurityDriver.exe</strong></p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Program</span> : <span style="color: #2b91af">MarshalByRefObject</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">static</span> <span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">PartialTrustSetup</span>.CreatePartialTrustInstance&lt;<span style="color: #2b91af">Program</span>&gt;().PartialTrustMain();</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> PartialTrustMain()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Utility</span> u = <span style="color: blue">new</span> <span style="color: #2b91af">Utility</span>();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; u.ExecuteUnsafeCode();</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p><strong>SecurityLibrary.dll</strong> (Pardon the trivial example of unverifiable code.)</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: blue">assembly</span>: <span style="color: #2b91af">SecurityTransparent</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Utility</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">unsafe</span> <span style="color: blue">void</span> ExecuteUnsafeCode()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">int</span> i = 0;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">int</span>* p = &amp;i;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; *p = 2;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.WriteLine(i);</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The Main method in SecurityDriver.exe sets up a <a href="http://blogs.rev-net.com/ddewinter/2009/05/22/how-to-host-a-partial-trust-sandbox/">partial-trust AppDomain</a> and instantiates a new instance of the Program class in that AppDomain. The partial trust code only has permission to execute (SecurityPermission with SecurityPermissionFlag.Execution). When it calls Utility.ExecuteUnsafeCode, the JIT compiler throws a VerificationException because it can&#8217;t verify the IL in Utility.ExecuteUnsafeCode.</p>
<p>But if we add this attribute to the SecurityLibrary assembly and ensure that it is fully trusted (by using the StrongName[] parameter of the <a href="http://msdn.microsoft.com/en-us/library/ms130766.aspx">AppDomain.CreateDomain</a> method), then the JIT compiler will skip IL verification, and &quot;2&quot; will be printed to the console.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: blue">assembly</span>: <span style="color: #2b91af">SecurityRules</span>(<span style="color: #2b91af">SecurityRuleSet</span>.Level2, SkipVerificationInFullTrust = <span style="color: blue">true</span>)]</p>
</p></div>
<p>Remember, this only works when your transparent assembly is fully trusted.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:accde6eb-cf07-4484-a773-276d770b0448" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/.NET" rel="tag">.NET</a>,<a href="http://technorati.com/tags/security+tips" rel="tag">security tips</a>,<a href="http://technorati.com/tags/transparency" rel="tag">transparency</a>,<a href="http://technorati.com/tags/SecurityRulesAttribute" rel="tag">SecurityRulesAttribute</a>,<a href="http://technorati.com/tags/IL+Verification" rel="tag">IL Verification</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/06/08/the-securityrulesattribute/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Determining the Security Rules for Your Assemblies &#8211; #14</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/06/03/determining-the-security-rules-for-your-assemblies/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/06/03/determining-the-security-rules-for-your-assemblies/#comments</comments>
		<pubDate>Wed, 03 Jun 2009 12:25:10 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/03/determining-the-security-rules-for-your-assemblies/</guid>
		<description><![CDATA[If you&#8217;ve followed this tip series you&#8217;ll know about two different kinds of security transparency, one present in CLR 2.0 and one in CLR 4.0. And you know that in CLR 4.0, you can decide to use the legacy transparency rules in CLR 2.0. And you know about this attribute called APTCA. Maybe a bit [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve followed this tip series you&#8217;ll know about two different kinds of security transparency, <a href="http://blogs.rev-net.com/ddewinter/2009/05/18/using-transparency-in-clr-2/">one present in CLR 2.0</a> and <a href="http://blogs.rev-net.com/ddewinter/2009/05/28/introduction-to-security-transparency-in-net-4/">one in CLR 4.0</a>. And you know that in CLR 4.0, you can decide to use the <a href="http://blogs.rev-net.com/ddewinter/2009/05/20/opting-out-of-security-changes-in-net-4/">legacy transparency rules in CLR 2.0</a>. And you know about this attribute <a href="http://blogs.rev-net.com/ddewinter/2009/05/21/the-allowpartiallytrustedcallersattribute-aptca-6/">called APTCA</a>. Maybe a bit about permissions, too.</p>
<p>It can be really hard to keep all this information straight, so I&#8217;ve put together a flowchart to help you determine which transparency rules a particular assembly is using. I hope it&#8217;s useful!</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/06/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/06/image-thumb.png" width="710" height="952" /></a> </p>
</p>
</p>
<p>As you can see, while the number of rules is not totally unmanageable, it can be difficult to keep them straight. There are also a few situations where two different paths lead to the same outcome. For example, your assembly can be fully critical when it is a level 2 assembly marked with the SecurityCriticalAttribute or when it is a level 1 assembly marked with the SecurityCriticalAttribute with SecurityCriticalScope.Everything. Keep in mind that even though the assembly is fully critical in both cases, the <em>meaning </em>of critical depends on the current level, level 1 or level 2. If you need a review, consult my previous tips on <a href="http://blogs.rev-net.com/ddewinter/2009/05/18/using-transparency-in-clr-2/">CLR v2</a>&#160;<a href="http://blogs.rev-net.com/ddewinter/2009/05/19/transparent-code-behavior-in-clr-2/">transparency</a> and <a href="http://blogs.rev-net.com/ddewinter/2009/05/28/introduction-to-security-transparency-in-net-4/">CLR v4</a> <a href="http://blogs.rev-net.com/ddewinter/2009/05/29/type-transparency-in-net-4/">transparency</a>.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:81c59e5b-453b-43bd-8596-c653f7ee15e5" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/security+tips" rel="tag">security tips</a>,<a href="http://technorati.com/tags/.NET+4" rel="tag">.NET 4</a>,<a href="http://technorati.com/tags/CLR+v2" rel="tag">CLR v2</a>,<a href="http://technorati.com/tags/CLR+v4" rel="tag">CLR v4</a>,<a href="http://technorati.com/tags/security+transparency" rel="tag">security transparency</a>,<a href="http://technorati.com/tags/APTCA" rel="tag">APTCA</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/06/03/determining-the-security-rules-for-your-assemblies/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Transparency and Implicit Static Constructors &#8211; #13</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/06/02/transparency-and-implicit-static-constructors/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/06/02/transparency-and-implicit-static-constructors/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 12:35:17 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/02/transparency-and-implicit-static-constructors/</guid>
		<description><![CDATA[When you create classes that have static fields, and you initialize those fields inline, the compiler will split the code into two parts: the field declaration and the field initialization. Field initialization occurs within a static constructor, whether it&#8217;s declared or not. Have a look at the following class as it appears in C#.

public class [...]]]></description>
			<content:encoded><![CDATA[<p>When you create classes that have static fields, and you initialize those fields inline, the compiler will split the code into two parts: the field declaration and the field initialization. Field initialization occurs within a static constructor, whether it&#8217;s declared or not. Have a look at the following class as it appears in C#.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Wrapper</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> handle = InitializeHandle();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> InitializeHandle()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// get handle</span></p>
<p style="margin: 0px">&#160;&#160;&#160; }&#160;&#160; </p>
<p style="margin: 0px">}</p>
</p></div>
<p>It&#8217;s <em>almost</em> the same as doing this.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Wrapper</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> handle;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">static</span> Wrapper()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; handle = InitializeHandle();</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> InitializeHandle()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// get handle</span></p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The difference between the implicit static constructor and explicit static constructor is that the implicit constructor performs much better than the explicit one. (You can read more about this difference <a href="http://msdn.microsoft.com/en-us/magazine/cc163857.aspx#S1">here</a>.)</p>
<p>What if I deem that the handle itself should be SecurityCritical? This is where things get interesting…</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Wrapper</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">SecurityCritical</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> handle = InitializeHandle();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> InitializeHandle()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// get handle</span></p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>If I instantiate a new Wrapper instance, this code still runs correctly, but if I mark this assembly with APTCA, it fails. What&#8217;s happening here?</p>
<p>We get a FieldAccessException whose message is &quot;ConsoleApplication2.Wrapper.handle&quot; and whose stack trace is &quot;at ConsoleApplication2.Wrapper..cctor().&quot; The &quot;.cctor&quot; is the static constructor. From this we can deduce that the static constructor can&#8217;t initialize the field, and that&#8217;s because the static constructor generated by the compiler is transparent code when we mark the assembly with APTCA.</p>
<p>Unfortunately this is a case in which you must sacrifice performance for security. This might be changed before .NET 4 RTM, but for now, you&#8217;ll need to explicitly specify the static constructor and mark it as security safe critical or security critical. (You can mark it security critical because the runtime itself will call the static constructor from native code.)</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Wrapper</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">SecurityCritical</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> handle;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">SecurityCritical</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">static</span> Wrapper()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; handle = InitializeHandle();</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IntPtr</span> InitializeHandle()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// get handle</span></p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:fed65eaf-d7d4-4f7d-bbe5-e445153d95f4" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/security+tips" rel="tag">security tips</a>,<a href="http://technorati.com/tags/.NET+4" rel="tag">.NET 4</a>,<a href="http://technorati.com/tags/static+constructors" rel="tag">static constructors</a>,<a href="http://technorati.com/tags/security+transparency" rel="tag">security transparency</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/06/02/transparency-and-implicit-static-constructors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
