using Programming;

A Blog about some of the intrinsics related to programming and how one can get the best out of various languages.

Demonstrating Insecurity of Managed Windows Program Memory

Is Memory in a Managed Windows Program Secure?

Recently I was on one of the (many) Stack Exchange sites answering a question a user posted, like usual. This question was a bit different though: the asker was concerned about the best way to make sure people couldn't read the password the user entered out of memory.

Unfortunately, this is not a task that can really be solved on consumer devices. Anyone with enough knowledge (and it's not really a lot) can do it. I'm going to demonstrate how to today with a simple Visual Studio programme.

Essentially, what I'm going to do is 'connect' to a fake SQL server (nothing about it will really exist) and then demonstrate how one can (with a copy of Visual Studio) extract the entire Connection String of that SQL connection out. It's actually quite trivial and with enough practice can be done in seconds.

Of course there are other ways to do this, it can be done programatically, there are other bits of software for it, etc. I'm just going to demonstrate how any developer can do it with the tools (s)he has at their disposal.

Creating our test projects

So the first step is to create a test project we can use to 'attack'. We're going to consider this an attacker/victim scenario, since that's what one of the real world applications is.

Our code is going to be pretty simple:

using Evbpc.Framework.Utilities.Prompting;
using System;
using System.Data.SqlClient;

namespace VictimApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var consolePrompt = new ConsolePrompt(null);

            var connectionString = new SqlConnectionStringBuilder();
            connectionString.DataSource = consolePrompt.Prompt<string>("Enter the SQL server hostname/ip", PromptOptions.Required);
            connectionString.UserID = consolePrompt.Prompt<string>("Enter the SQL server user id", PromptOptions.Required);
            connectionString.Password = consolePrompt.Prompt<string>("Enter the SQL server password", PromptOptions.Required);
            connectionString.InitialCatalog = consolePrompt.Prompt<string>("Enter the SQL server database", PromptOptions.Required);

            using (var sqlConnection = new SqlConnection(connectionString.ToString()))
            {
                try
                {
                    Console.WriteLine("Connecting...");
                    sqlConnection.Open();

                    using (var command = new SqlCommand("SELECT 15", sqlConnection))
                    {
                        Console.WriteLine($"Command output: {command.ExecuteScalar()}");
                    }
                }
                catch
                {
                    Console.WriteLine("Could not establish a connection to the server.");
                }
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }
}

Do note this uses my ConsolePrompt from GitHub.

So we have our victim application, now we'll go ahead and attack it.

Attaching Visual Studio to a running application

You're probably expecting a title like 'attacking an application with Visual Studio' but that's not as descriptive as what we're doing. Yes, this is how you attack it, but attack sounds nefarious. We're not doing anything nefarious, we're just attaching a debugger to a running application.

So we're going to open a new instance of Visual Studio, and not open or create a project. Just open the instance.

Screenshot 1 - Fresh Visual Studio Instance

So, we've opened Visual Studio (I'm using 2015 but this should work on 2010+). The next thing we'll do is launch our application.

Screenshot 2 - Launch Application Outside Debugger

Right, so we have the application running outside the debugger. No other instances of Visual Studio need to be open, nothing else needs to be running, just that application and our fresh instance. The next step is to attach the debugger to a process.

This is under Debug -> Attach to Process. You should see a new window open, and we want to find our 'Victim Application' (VictimApplication.exe).

Screenshot 3 - Attach to Process

We'll go ahead and attach it. Our screen should change to look like we're in a regular debug session, even though we didn't launch the program through Visual Studio.

Screenshot 4 - Debug Session is Green err Blue

Now we still have our other window open with our running application in it. All we have to do next is start checking it out and see what we can inspect.

This next part isn't required, but it should help you familiarize yourself with what we're going to do. Let's hit the 'Break All' button (CTRL + ALT + Break with default shortcuts).

Screenshot 5 - Break mode

As of this moment the program is paused. Since it's a console application, you can still type into it, but your typing will not be processed by the program at this point.

Screenshot 6 - Text not handled by program

Next we'll hit 'Show Diagnostic Tools' and then select the 'Memory Usage' tab. Once we have done that, we'll hit 'Take Snapshot'.

Screenshot 7 - Taking our first memory snapshot

So now we're at the point we can start inspecting objects in our program. The first thing we'll want to do is click the blue 429 (your number may vary) link to the list of objects.

We'll then sort them by name since we're not concerned about the count, we just want to look through them.

I'm going to inspect our ConsolePrompt as an example, which in this case is listed as Evbpc.Framework.Utilities.Prompting.ConsolePrompt. When you find an object you want to inspect, hover over it and you should see an icon that looks like a square grid with a circular shape on the top-left corner, click that and a new page should open.

Screenshot 8 - Selecting an object to inspect

We'll then see a new page with all the instances of that object listed. If you hover over the Value, you should get a tool-tip that has a breakdown of the object itself, which you can explore just like normal. We'll see that the Logger is in fact null like we wanted.

Screenshot 9 - Exploring our object

Now that we've played with our explorer, we can go ahead and close that breakdown and continue with our program. We'll hit 'Continue' and resume execution. If you typed a server host into the console, you'll see as soon as we hit continue that the program continues to the next step. We'll fill out all our requirements and then break our program again when it starts connecting, and take another memory snapshot.

Screenshot 10 - Connecting to our server

We see that the new snapshot has 3,825 objects allocated, and the difference is an increase of 3,396. Our graph shows that we allocated a lot more memory (relatively speaking) and we can now go ahead and inspect our snapshot to try to find our password. We'll be looking for a string type with a value of pass.

We know it'll be part of the SqlConnection, so we'll sort that by name and then go down to SqlConnection and explore it like before.

Screenshot 11 - Find our SqlConnection

Upon exploring it we'll just a different method of extracting our string. Click 'Referenced Objects' at the bottom of our window, and hover over the middle String object. (Mine is 0x2FB0BD8)

Screenshot 12 - Extracting our Connection String

And there we have it. We have successfully extracted our password from a separate Visual Studio instance while the original application was running completely separately.

Debug Symbols and why they are important

Of course, our demonstration was made slightly easier by the inclusion of the .pdb files (debug symbols), usually you won't have access to these for the running application, so you'll have to look a little harder sometimes to find what you're looking for.

If you don't know what Debug Symbols are, Wikipedia has a nice description. Essentially, the pdb file (stands for 'Program Database') is the symbol map for .NET programs. It contains each generated instruction header and what the generated name of it was.

Finding our String without SqlConnection

The last thing we'll do is find our string value without exploring the SqlConnection object. We're only going to look with the Diff list, and run from there.

So, we'll restart our application, then attach the debugger, then enter our host and user, then take a memory snapshot like we did earlier.

Screenshot 13 - Round 2 First Snapshot

Then we'll hit 'Continue', enter our password, and take another snapshot.

Screenshot 14 - Round 2 Second Snapshot

The next step is to disable 'Just My Code' in the filter. If we don't do this it becomes much more difficult to locate what we changed.

Screenshot 15 - Round 2 Disable Just My Code

So we see that it created one string, by the Count Diff. being +1 on the String type, this helps us narrow down what we're looking for. If click once into it, and view our 'Paths to Root', it helps us discover that we have +1 in String [Local Variable]. So we're in the right place.

Screenshot 16 - Round 2 String Local Variable

We'll inspect the String like before (Square icon with Round outset) and we'll see that by default it sorts the list by `'Inclusive Size (Bytes)', we'll sort it by 'Instance'. Theorhetically our password should be the last instance listed. If we scroll to the bottom of the list we see that, indeed, it is.

We also see that our user id is right above it.

Screenshot 17 - Round 2 Find our Password


And there we have it! We learned how to inspect objects in our program when it was launched outside Visual Studio by attaching a debug instance of Visual Studio to it.