<?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>Musings of a technophile &#187; coding</title>
	<atom:link href="http://www.omegaprojex.com/index.php/tag/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.omegaprojex.com</link>
	<description>Just another blog from a computer nerd</description>
	<lastBuildDate>Mon, 19 Jul 2010 15:39:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Deploying External and Unsafe SQL CLR Functions</title>
		<link>http://www.omegaprojex.com/index.php/2010/01/06/deploying-external-and-unsafe-sql-clr-functions/</link>
		<comments>http://www.omegaprojex.com/index.php/2010/01/06/deploying-external-and-unsafe-sql-clr-functions/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 14:20:00 +0000</pubDate>
		<dc:creator>ElementZero</dc:creator>
				<category><![CDATA[Computer Troubleshooting]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.omegaprojex.com/index.php/2010/01/06/deploying-external-and-unsafe-sql-clr-functions/</guid>
		<description><![CDATA[If you ever have to deploy a SQL CLR Function that is not using Safe Permissions, then you may run into a roadblock where you get the error CREATE ASSEMBLY for assembly 'MyProject' failed because assembly 'MyProject' is not authorized for PERMISSION_SET = EXTERNAL_ACCESS. The assembly is authorized when either of the following is true: [...]]]></description>
			<content:encoded><![CDATA[<p>If you ever have to deploy a SQL CLR Function that is not using Safe Permissions, then you may run into a roadblock where you get the error </p>
<pre class="wikitext">
CREATE ASSEMBLY for assembly 'MyProject' failed because assembly 'MyProject' is not authorized for PERMISSION_SET = EXTERNAL_ACCESS.
The assembly is authorized when either of the following is true:
the database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission and the database has the TRUSTWORTHY database property on;
or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with EXTERNAL ACCESS ASSEMBLY permission.
If you have restored or attached this database, make sure the database owner is mapped to the correct login on this server. If not, use sp_changedbowner to fix the problem.
</pre>
<p>Before I go futher, let me redefine the different permissions sets for SQL CLR</p>
<ul>
<li>
<strong>SAFE:</strong> This permissions set is applied by default if not specified otherwise, and SAFE is the most restrictive permission set. Code executed by an assembly with SAFE permissions cannot access external system resources such as files, the network, environment variables, or the registry.
</li>
<li>
<strong>EXTERNAL_ACCESS:</strong> This permissions set enables assemblies to access certain external system resources such as files, networks, environmental variables, and the registry.
</li>
<li>
<strong>UNSAFE:</strong> enables assemblies unrestricted access to resources, both within and outside an instance of SQL Server. Code running from within an UNSAFE assembly can call unmanaged code as well.
</li>
</ul>
<p>SAFE is highly recommended by Microsoft.</p>
<p>So basically you are getting the error because using EXTERNAL or UNSAFE allows code to do something outside the scope of what SQL can normally do, and therefore for security measures SQL blocks you from just going ahead and loading this onto the server.</p>
<p>There are two fixes to this.  The first is to go to the database you will be deploying the CLR function to and running the command</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #597EBB; font-weight: bold;">ALTER</span> <span style="color: #597EBB; font-weight: bold;">DATABASE</span> Databasename <span style="color: #597EBB; font-weight: bold;">SET</span> TRUSTWORTHY <span style="color: #597EBB; font-weight: bold;">ON</span>;</pre></div></div>

<p>While this works, it also is not the right solution as this will enable your database to run any CLR that is deployed to it, making it easier for bad or unreviewed code to get onto the SQL Server (again &#8211; this is bad).</p>
<p>The correct solution is to make an Asymmetric Key for your CLR Function, create a user to use the key, and then Grant the permission set access for that user.  To do this you do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #597EBB; font-weight: bold;">USE</span> master
GO 
<span style="color: #808080; font-style: italic;">-- First Create the Asymmetric Key from the Assembly</span>
<span style="color: #597EBB; font-weight: bold;">CREATE</span> ASYMMETRIC <span style="color: #597EBB; font-weight: bold;">KEY</span> SQLCLRUserKey
<span style="color: #597EBB; font-weight: bold;">FROM</span> EXECUTABLE FILE <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'C:\SQL CLR Functions\SQLCLR\bin\Release\SQLCLR.dll'</span>
GO</pre></div></div>

<p>You can change &#8220;SQLCLRUserKey&#8221; to whatever you would like the key name to be, and the path to the dll must be the path to your CLR functions output dll.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- Create the Login from the Asymmetric Key</span>
<span style="color: #597EBB; font-weight: bold;">CREATE</span> LOGIN SQLCLRUser <span style="color: #597EBB; font-weight: bold;">FROM</span> ASYMMETRIC <span style="color: #597EBB; font-weight: bold;">KEY</span> SQLCLRUserKey
GO</pre></div></div>

<p>This creates the user based off the key we made in step 1.  Again, &#8220;SQLCLRUser&#8221; can be whatever user name you want to use, and you just need to make sure &#8220;SQLCLRUserKey&#8221; matches whatever name you used for Step 1.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- Grant the External Access Priviledge to the Login</span>
<span style="color: #597EBB; font-weight: bold;">GRANT</span> EXTERNAL ACCESS ASSEMBLY <span style="color: #597EBB; font-weight: bold;">TO</span> SQLCLRUser
GO</pre></div></div>

<p>This grants the permissions for this user to deploy SQL CLR Projects with EXTERNAL permission sets.  In order to do UNSAFE just change the words &#8220;EXTERNAL ACCESS&#8221; to &#8220;UNSAFE&#8221;.</p>
<p>Last is</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #597EBB; font-weight: bold;">USE</span> <span style="color: #66cc66;">&#91;</span>MyDatabase<span style="color: #66cc66;">&#93;</span>
GO
<span style="color: #808080; font-style: italic;">-- Add a database user in the SQLCLR_Net Database for the Login</span>
<span style="color: #597EBB; font-weight: bold;">CREATE</span> USER SQLCLRUser <span style="color: #597EBB; font-weight: bold;">FOR</span> LOGIN SQLCLRUser
GO</pre></div></div>

<p>Where &#8220;MyDatabase&#8221; is the name of the database where your CLR Project will be deployed.  This creates the user mapping in that database.</p>
<p>After this, you should be able to deploy your project as normal, and by doing these steps you will just be granting permissions for the specified CLR Project instead of ANY CLR Project (much better don&#8217;t you think?)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.omegaprojex.com/index.php/2010/01/06/deploying-external-and-unsafe-sql-clr-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Encrypting Web.Config connection strings with ASP.NET 2.0</title>
		<link>http://www.omegaprojex.com/index.php/2009/01/29/encrypting-webconfig-connection-strings-with-aspnet-20/</link>
		<comments>http://www.omegaprojex.com/index.php/2009/01/29/encrypting-webconfig-connection-strings-with-aspnet-20/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 19:20:58 +0000</pubDate>
		<dc:creator>ElementZero</dc:creator>
				<category><![CDATA[Computer Troubleshooting]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[Server Administration]]></category>

		<guid isPermaLink="false">http://www.omegaprojex.com/?p=404</guid>
		<description><![CDATA[One of the greatest things in security of your web application is the encryption of the connection strings to the database. If the database connection strings are compromised, then an attacker could gain access to your database and cause unforeseen damage. In order to avoid this, Microsoft has created best practices and instruments for encrypting [...]]]></description>
			<content:encoded><![CDATA[<p>One of the greatest things in security of your web application is the encryption of the connection strings to the database. If the database connection strings are compromised, then an attacker could gain access to your database and cause unforeseen damage. In order to avoid this, Microsoft has created best practices and instruments for encrypting your connection strings in ASP.NET 2.0. This documentation may be found <a href="http://msdn.microsoft.com/en-us/library/ms998283.aspx">here</a>. I wrote this article to attempt to summarize (a.k.a. simplify) the Microsoft documentation, as well as going into further detail about how to configure your web.config and access the connection strings. Just think of this as the &#8220;Cliff&#8217;s Notes&#8221; to the Microsoft article.</p>
<div style="border:1px solid;border-color:#AAAAAA;background-color:#EEEEEE;padding-left:5px;">
<a href="#step1" style="color:navy;">Step 1: Creating a Key Container</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#step1b" style="color:navy;">1b) Removing a key collection</a><br />
<a href="#step2" style="color:navy;">Step 2: Setting up a provider to point to the key container in your web.config</a><br />
<a href="#step3" style="color:navy;">Step 3: Moving your connection strings into a different configuration file</a><br />
<a href="#step4" style="color:navy;">Step 4: Encrypting your connection strings</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#step4b" style="color:navy;">1b) Decrypting your connectionstrings.config</a><br />
<a href="#step5" style="color:navy;">Step 5: Give ASP.NET access to the private key</a><br />
<a href="#step6" style="color:navy;">Step 6: (Optional where applicable) Exporting the private keys to a different server</a><br />
<a href="#step7" style="color:navy;">Step 7: Accessing the connection strings within the web application</a><br />
<a href="#faq" style="color:navy;">F.A.Q.</a>
</div>
<h3><a name="step1">Step 1: Creating a Key Container</a></h3>
<p>In order to secure your web.config, you will first need to create a key container in order to hold the private keys for the encrypted material. This is done with the following command line </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pc "MyConnectionStrings" -exp
</pre>
<p>where &#8220;MyConnectionStrings&#8221; is the name of the key container you wish to create. After creating a key container, you can now modify your web.config to support the encrypted sections.</p>
<p><strong style="font-size:1.2em;"><a name="step1b">Removing a key collection</a></strong></p>
<p>At any point you can also remove a key collection, however doing this will mean that your web application will not be able to decrypt your connection strings anymore, and you will not be able to decrypt the connection strings file yourself for changes (see section 4.1).</p>
<p>The command to remove a key collection is </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pz "MyConnectionStrings"
</pre>
<h3><a name="step2">Step 2: Setting up the web.config</a></h3>
<p>In order to let ASP.NET know about the encryption provider (a.k.a. &#8211; which private keys to use to read the encrypted data), you must add the following section into your web.config under the <configuration> section.</p>
<pre class="wikitext">
&lt;configProtectedData defaultProvider="MyProvider"&gt;
	&lt;providers&gt;
		&lt;add name="MyDBProvider"
		type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
		keyContainerName="MyConnectionStrings" cspProviderName=""
		useMachineContainer="true" useOAEP="false" /&gt;
	&lt;/providers&gt;
&lt;/configProtectedData&gt;
</pre>
<p>The key things to note are the <strong>defaultProvider=&#8221;MyProvider&#8221;</strong>, the <strong>name=&#8221;MyDBProvider&#8221;</strong> and the <strong>keyContainerName=&#8221;MyConnectionStrings&#8221;</strong>.  The Provider name can be whatever you wish, and you may have multiple providers if you wish.  The provider can be set in code on the ConnectionManager.ConnectionStrings().Provider, but if a default one is specified via the &#8220;defaultProvider&#8221; attribute, this does not need to be specified.  Normally you would only use multiple providers if you want to have your connection strings split into multiple documents. <strong>Just as a note &#8211; other things can be encrypted in the web.config besides the connection strings section, in which case multiple providers may be useful as well.</strong>  The keyContainerName <em>MUST</em> be the same name as the key container name you used in Step 1.</p>
<h3><a name="step3">Step 3: Move connection strings into a different configuration file</a></h3>
<p>Now that we have done this, we can encrypt our connection strings. Before we do this though, I would advise moving your connection strings out to an external file. The reason is a) All the connection strings will be kept separate from your web.config settings and b) The encryption tool parses and re-writes the web.config file, and if you have done any special formatting to make your web.config look nice, that formatting may be completely removed.</p>
<p>Doing this is rather simple, all you have to do is create another configuration file for your project (we will be using &#8220;ConnectionStrings.config&#8221; ) and moving your &lt;connectionStrings&gt; settings to that file. So before doing this you may have </p>
<p><strong>Web.config</strong></p>
<pre class="wikitext">
&lt;configuration&gt;
  ...
	&lt;connectionStrings&gt;
		&lt;clear/&gt;
		&lt;add name="MyDBConn"
			connectionString="Data Source=MySQLSvr;Initial Catalog=AdventureWorks;User Id=MyUser;Password=MyPass;"
			providerName="System.Data.SqlClient" /&gt;
        &lt;/connectionStrings&gt;
...
&lt;/configuration&gt;
</pre>
<p>Now you will have<br />
<strong>Web.config</strong></p>
<pre class="wikitext">
&lt;configuration&gt;
...
        &lt;connectionStrings configSource="ConnectionStrings.config"&gt;&lt;/connectionStrings&gt;
...
&lt;/configuration&gt;
</pre>
<p><strong>ConnectionStrings.config</strong></p>
<pre class="wikitext">
&lt;connectionStrings&gt;
	&lt;clear/&gt;
	&lt;add name="MyDBConn"
		connectionString="Data Source=MySQLSvr;Initial Catalog=AdventureWorks;User Id=MyUser;Password=MyPass;"
		providerName="System.Data.SqlClient" /&gt;
        &lt;/connectionStrings&gt;
&lt;/connectionStrings&gt;
</pre>
<h3><a name="step4">Step 4: Encrypting your connection strings</a></h3>
<p>Next you need to encrypt the file where you are keeping the connection strings. This is done with the following command </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "connectionStrings" "PATH"
</pre>
<p>Where &#8220;PATH&#8221; is the full path to the folder where your web.config is stored. i.e. &#8220;C:\inetpub\wwwroot&#8221;. It does not matter where the &#8220;connectionstrings.config&#8221; file is found as the web.config now has the file location of the connectionstrings.config in it, and the program will follow that path to the external file. The best idea is still to put the connectionstring.config file in the same directory as the web.config though. After doing this, you should be able to open the ConnectionStrings.config and see that the information has changed to some encrypted data. </p>
<p><strong style="font-size:1.2em;"><a name="step4b">Decrypting your connectionstrings.config</a></strong></p>
<p>Should the need arise for some changes to come to your connectionstrings, you can simply decrypt the file by executing the command </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pdf "connectionStrings" "PATH"
</pre>
<h3><a name="step5">Step 5: Give ASP.NET access to the private key</a></h3>
<p>The next command to run is to give the ASP.NET service access to the private key for it to be able to decipher the web.config file. By default the &#8220;NT Authority\Network Service&#8221; is the owner of the ASP.NET worker process, however this can be changed so you may need to grant the permissions to a different account instead. Giving access is done using the following commands: </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pa "MyConnectionStrings" "NT Authority\Network Service"
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pa "MyConnectionStrings" "ASPNET"
</pre>
<p>Again, the &#8220;MyConnectionStrings&#8221; <em>MUST</em> be the name of the key container that you named in Step 1. At this point your application should now have access to use the ConnectionStrings.config in it&#8217;s encrypted state.</p>
<h3><a name="step6">Step 6: (Optional where applicable) Exporting the private keys to a different server</a></h3>
<p>One final thing to note is that if you are running the application on some instance where the application will need to be run on multiple web servers with the same ConnectionStrings.config, you will need to export the private key container so that the same file can be used on different machines. This is accomplished via the following command </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -px "MyConnectionStrings" "C:\CustomKeys.xml" -pri
</pre>
<p>After copying the file over to the other server, you would run the command </p>
<pre class="wikitext">
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pi "MyConnectionStrings" "C:\CustomKeys.xml"
</pre>
<p>to import the keys. I believe you will still need to redo Step 5 again in order to grant permissions. </p>
<h3><a name="step7">Step 7: Accessing the connection strings within the web application</a></h3>
<p>The first thing to do in order to access the connection strings is you will need to add a reference to the project to System.Configuration. Although you can access some classes and objects in System.Configuration without adding a reference, the ASP.NET 2.0 connection strings configuration manager (which we will need) is not part of them. Once you add the reference, you simply add </p>
<p><strong>VB.NET</strong></p>

<div class="wp_syntax"><div class="code"><pre class="vbnet" style="font-family:monospace;"><span style="color: #0600FF;">Dim</span> MyConnStr <span style="color: #FF8000;">As</span> <span style="color: #FF8000;">String</span> <span style="color: #008000;">=</span> System.<span style="color: #0000FF;">Configuration</span>.<span style="color: #0000FF;">ConfigurationManager</span>.<span style="color: #0000FF;">ConnectionStrings</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;MyDBConn&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ConnectionString</span></pre></div></div>

<p><strong>C#</strong></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span> MyConnStr <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Configuration</span></span>.<span style="color: #0000FF;">ConfigurationManager</span>.<span style="color: #0000FF;">ConnectionStrings</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;MyDBConn&quot;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">ConnectionString</span></pre></div></div>

<p>to access the connection string, where MyDBConn is the name you gave the connection string. Note that is you have multiple providers or the provider for the connection strings is not the same as the default provider, you will need to add </p>
<p><strong>VB.NET</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="vbnet" style="font-family:monospace;"><span style="color: #0600FF;">Dim</span> DBConn <span style="color: #FF8000;">As</span> <span style="color: #FF8000;">New</span> System.<span style="color: #0000FF;">Configuration</span>.<span style="color: #0000FF;">ConnectionStringSettings</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;MyDBConn&quot;</span><span style="color: #000000;">&#41;</span>
DBConn.<span style="color: #0000FF;">ProviderName</span> <span style="color: #008000;">=</span> <span style="color: #808080;">&quot;MyProvider&quot;</span>
<span style="color: #0600FF;">Dim</span> MyConnStr <span style="color: #FF8000;">As</span> <span style="color: #FF8000;">String</span> <span style="color: #008000;">=</span> DBConn.<span style="color: #0000FF;">ConnectionString</span></pre></td></tr></table></div>

<p><strong>C#</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">System.<span style="color: #0000FF;">Configuration</span></span>.<span style="color: #0000FF;">ConnectionStringSettings</span> DBConn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Configuration</span></span>.<span style="color: #0000FF;">ConnectionStringSettings</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;MyDBConn&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
DBConn.<span style="color: #0000FF;">ProviderName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;MyProvider&quot;</span>
<span style="color: #FF0000;">string</span> MyConnStr <span style="color: #008000;">=</span> DBConn.<span style="color: #0000FF;">ConnectionString</span></pre></td></tr></table></div>

<h3><a name="faq">F.A.Q</a></h3>
<p><strong>Q: I would like to add/update/remove a connection string in the file and I&#8217;ve already encrypted the file, how do I do this?  I have multiple web servers</strong><br />
A: If you just a single web server, all you need to do is <a href="step4b"decrypt the file</a>, change it how you need, and then <a href="step4">encrypt the file</a> again.  If you have multiple web servers, you will need to perform this on one of your servers, and then you can just copy that file to the other servers as the other servers will already have the key and know how to read the encrypted file.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.omegaprojex.com/index.php/2009/01/29/encrypting-webconfig-connection-strings-with-aspnet-20/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
