Using SecureString in code

Securing your application against malicious attacks is not an easy task. It is the constant struggle between writing secure code while minimizing bugs (which hackers usually exploit) and black hats writing more and more sophisticated methods to compromise systems and networks. I personally believe that higher learning institutions need to teach IT students two things:

  • How to use and integrate with a popular ERP system
  • Proper software security principles

In fact, I believe that secure programming 101 must not simply be a module or topic in a given IT course, but a whole course on its own. It needs to be handled with the seriousness and respect it deserves and needs to preferably be taught by someone that can actually hack a system or network.

White hats teaching students how to compromise systems, exploit vulnerable code, and infiltrate networks will make a big difference in changing the way future software developers approach programming. It comes down to developers knowing what not to do when programming defensively. It is quite possible that some of those students might go on to become black hats themselves, but they would have done that irrespective of whether they took a class on hacking secure programming or not.

Getting ready

The code might look a little funny in some places. This is because SecureString is using unmanaged memory to store the sensitive information. Rest assured that SecureString is well supported and used within the .NET Framework, as can be seen from the instantiation of the SqlCredential object used in creating connections to a database:

Getting ready

How to do it…

  1. Start by adding a new Windows Forms project to your solution:
    How to do it…
  2. Call the project winformSecure and click on the OK button:
    How to do it…
  3. In the Toolbox, search for the TextBox control and add it to your form:
    How to do it…
  4. Lastly, add a button control to your form. You can resize this form however you like to look more like a login form:
    How to do it…
  5. With the text box control selected on the Windows Forms, open up the Properties panel and click on the Events button (it looks like a lightning bolt). In the Key group, double-click on the KeyPress event to create the handler in the code behind:
    How to do it…

    The code that is created for you is the KeyPress event handler for the text box control. This will fire whenever a user presses a key on the keyboard:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        
    }
  6. Back in the Properties panel, expand the Behavior group and change the value of UseSystemPasswordChar to true:
    How to do it…
  7. In the code behind, add the following using statement:
    using System.Runtime.InteropServices;
  8. Add the SecureString variable as a global variable to your Windows Forms:
    SecureString secure = new SecureString();
  9. Then in the KeyPress event, append the KeyChar value to the SecureString variable every time the user presses a key. You might want to add code to ignore certain key presses, but this is beyond the scope of this recipe:
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        secure.AppendChar(e.KeyChar);
    }
  10. Then in the Login button's event handler, add the following code to read the value from the SecureString object. Here we are working with unmanaged memory and unmanaged code:
    private void btnLogin_Click(object sender, EventArgs e)
    {
        IntPtr unmanagedPtr = IntPtr.Zero;
    
        try
        {
            if (secure == null)
                throw new ArgumentNullException("Password not defined");
            unmanagedPtr = Marshal.SecureStringToGlobalAllocUnicode(secure);
            MessageBox.Show($"SecureString password to validate is {Marshal.PtrToStringUni(unmanagedPtr)}");
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            Marshal.ZeroFreeGlobalAllocUnicode(unmanagedPtr);
            secure.Dispose();
        }
    }
  11. Run your Windows Forms application and type in a password:
    How to do it…
  12. Then click on the Login button. You will then see the password you typed in displayed in the message box:
    How to do it…

How it works…

It has become almost a habit for many developers to use System.String to store sensitive information such as passwords. The problem with this approach is that System.String is immutable. This means that the object created in memory by System.String can't be changed. If you modify the variable, a new object is created in memory. You also cannot determine when the object created by System.String will be removed from memory during garbage collection. Conversely, by using the SecureString object, you will encrypt sensitive information and when that object is no longer needed, it is deleted from memory. SecureString encrypts and decrypts your sensitive data in unmanaged memory.

Now I need to be clear regarding one thing here. SecureString is by no means foolproof. If your system contains a virus with the sole purpose of compromising the SecureString operations, using it doesn't help much (be sure to use proper anti-virus software anyway). At some point during the code execution, the string representation of your password (or sensitive information) is visible. Secondly, if a hacker somehow found a way to inspect your heap or log your key strokes, the password might be visible. The use of SecureString, however makes this window of opportunity for a hacker much smaller. The window of opportunity reduces because there are less attack vectors (points of entry for a hacker), thereby reducing your attack surface (sum of all points of attack by a hacker).

The bottom line is this: SecureString is there for a reason. As a software developer concerned about security, you should be using SecureString.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.200.3