{"id":12,"date":"2011-04-04T23:15:15","date_gmt":"2011-04-05T03:15:15","guid":{"rendered":"http:\/\/griffinscs.wordpress.com\/?p=12"},"modified":"2011-04-04T23:15:15","modified_gmt":"2011-04-05T03:15:15","slug":"securestring-soup-to-nuts-part-i","status":"publish","type":"post","link":"https:\/\/brainslug.azurewebsites.net\/?p=12","title":{"rendered":"SecureString: Soup to Nuts, Part I"},"content":{"rendered":"<p><strong>Motivation:<\/strong><\/p>\n<p>Using the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.security.securestring.aspx\">SecureString<\/a> class in .NET is a great way to protect your users' sensitive data from malicious code, intended to pull said data right out of memory.  It is already supported by framework classes that Internet enabled applications use often, like <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.net.networkcredential.aspx\">NetworkCredential<\/a>, making its addition to your existing code fairly straightforward.<\/p>\n<p>That's great, but since nothing is ever easy I want to point out that there are two scenarios where it wasn't so easy to accomplish requested functionality and maintain the proper use of SecureString:<\/p>\n<ol>\n<li>implementing secure local storage \tof a password, and<\/li>\n<li>preserving MVVM design without \texposing the password in an insecure managed object.<\/li>\n<\/ol>\n<p>There is quite a bit of widely accepted advice to be found on community support forums that seeks to  fit each of these scenarios, but defeats the point of using SecureString at all.<\/p>\n<p>As I understand it, there are two commandments one should follow if one intends to use them without sabotaging one's own efforts.  The first is to dispose of the SecureString when processing is complete, the other is never to allow the unprotected contents of the SecureString to find its way into a CLR object, like a string or byte array.  It just isn't clear how long they will be hanging around in memory, and heck, if you wanted to store your secret in a CLR string, you could have saved yourself a lot of time by doing so to begin with.<\/p>\n<p>In part I and II of this article I will address my method of implementing solutions for these two scenarios, respectively.<\/p>\n<p><strong>Secure Local Storage:<\/strong><\/p>\n<p>Finally getting to the point.\u00a0 This guy is first, because it's useful regardless of what design patterns or frameworks you're using to implement your interface, or whether you're implementing a GUI at all.  If you've ever written a program that needs to utilize local storage for any data placed in a SecureString, you've run into this problem.  The last thing you want to do is store it out in clear text, so you know it needs to be encrypted.  DPAPI to the rescue.  Great, but there's good news and bad news.<\/p>\n<p>First the bad.  The <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.security.cryptography.protecteddata.aspx\">ProtectedData'<\/a>s <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.security.cryptography.protecteddata.protect.aspx\">Protect<\/a>\/<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.security.cryptography.protecteddata.unprotect.aspx\">Unprotect<\/a> methods are staring us in the face, just begging us to use them, with their single parameter overloads, and be done.  Alas, the second commandment of SecureStrings prevents us from placing our secret in a CLR byte array, so we're going to have to make the unmanaged calls to CryptoAPI.<\/p>\n<p>The good news is that we can use P\/Invokes and marshaling to accomplish the necessary unmanaged calls to <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/aa380261%28v=VS.85%29.aspx\">CryptProtectData<\/a> and <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/aa380882%28v=VS.85%29.aspx\">CryptUnprotectData<\/a>, zero out and free any sensitive data immediately without actually writing any unmanaged code.<\/p>\n<p>Now for some code.  Moving from an existing SecureString instance into some processing code is always going to look pretty similar to this...<\/p>\n<pre class=\"brush: csharp; \">\nIntPtr unmanagedString = Marshal.SecureStringToBSTR(self);\ntry\n{\n\/\/Processing code here. Resist the urge to Marshal.PtrToStringBSTR.\n}\nfinally\n{\nMarshal.ZeroFreeBSTR(unmanagedString); \/\/free the buffer holding our secret\n}\n<\/pre>\n<p>The rest of the solution is pretty plug-and-chug.  I wrapped the CryptoAPI calls in SecureString extension methods GetProtectedData and  AppendProtectedData found in <a href=\"http:\/\/dl.dropbox.com\/u\/8701079\/SecureStringExtensions.cs\">this file<\/a>.  In the interest of leaving the method of storage as an implementation detail, the extension methods above export and import a byte array (encrypted of course).  It's simple to place them in user.config, for example by using the *.settings file designer to make a user setting called  \u201cPassword\u201d and doing the following in code...<\/p>\n<pre class=\"brush: csharp; \">\nProperties.Settings.Default.Password = Convert.ToBase64String(securePassword.GetProtectedData());\n<\/pre>\n<p>...and to reverse it...<\/p>\n<pre class=\"brush: csharp; \">\nstring encPassword = Properties.Settings.Default.Password;\nif (!string.IsNullOrEmpty(encPassword))\n{\nSecureString passwordString = new SecureString();\npasswordString.AppendProtectedData(Convert.FromBase64String(encPassword));\n}\n<\/pre>\n<p>Thanks to <a href=\"http:\/\/pinvoke.net\/\">pinvoke.net<\/a> for P\/Invoke signatures.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Motivation: Using the SecureString class in .NET is a great way to protect your users&#8217; sensitive data from malicious code, intended to pull said data right out of memory. It is already supported by framework classes that Internet enabled applications use often, like NetworkCredential, making its addition to your existing code fairly straightforward. That&#8217;s great, [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,1],"tags":[6,15,47,48],"_links":{"self":[{"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=\/wp\/v2\/posts\/12"}],"collection":[{"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=12"}],"version-history":[{"count":0,"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=\/wp\/v2\/posts\/12\/revisions"}],"wp:attachment":[{"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=12"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=12"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/brainslug.azurewebsites.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}