Category: Code Tips

Code Tips

Async Void Cannot Access a Disposed Object

A SinkRecently, I was trying to throw a quick method on a controller to create a user on the fly. I was pretty new into a .Net Core Web API project and I just needed to add a quick user to start to test some of the authenticated API calls that I was creating. So, I wrote code that was very similar to this:

[HttpGet("~/peteonsoftware")]
public async void CreateUser()
{
    var user = new ApplicationUser()
    {
        Email = "me@myserver.com",
        UserName = "me@myserver.com"
    };
    var result = await _userManager.CreateAsync(user, "SomePasswordThatIUsed,YouKnowHowItIs...");
}

When I started it up and made a call to http://localhost:56617/peteonsoftware, I got an error that read:

System.ObjectDisposedException occurred
  HResult=0x80131622
  Message=Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

I could not figure this out. I would debug and stop on the line. My dependency injection was working and my _userManager was populated via dependency injection and I reviewed documentation and what I was calling should work. I lost a lot of time to this. It turns out that I was the victim of some optimization that .Net is doing for me. Notice that my method is async. Notice also that my method returns void. So, as far as .Net is concerned, it can go ahead and return from my method as soon as it fires off that CreateAsync() call because it doesn’t care about the result and it isn’t returning anything anyway.

I naively thought that my await would keep everything holding on until the method returned. NOPE! I found through research that my method was returning before it was done and everything started cleaning up and disposing. Therefore, when the method went to work, everything was disposed, resulting in my error. When I made the small change of no longer returning void, everything worked.

[HttpGet("~/peteonsoftware")]
public async Task CreateUser()
{
    var user = new ApplicationUser()
    {
        Email = "me@myserver.com",
        UserName = "me@myserver.com"
    };
    var result = await _userManager.CreateAsync(user, "SomePasswordThatIUsed,YouKnowHowItIs...");

    // Yes, I know I could just return above, but I like it to be separate sometimes, don't judge me!
    return result;
}

Now when I call, I get back

{"succeeded":true,"errors":[]}

So, lesson to learn… async void is BAD! Lots of unexpected consequences. Always return something from an async method to ensure that nothing gets cleaned up early.

Code Tips

C# MemberwiseClone

Clone Trooper - Creative Commons License from https://c2.staticflickr.com/4/3484/3796528975_e8c7faaed2_z.jpg?zz=1

If you’ve ever needed to make a copy of an object in C#, you might have come across the MemberwiseClone() method. This can save you a lot of hassle of left-hand/right-hand property matching, but it does come with some “gotchas” that might not be readily apparent if you haven’t carefully read the documentation.

Let’s start with a class that looks like this. Notice that it has a ShallowCopy method that just returns a MemberwiseClone of the object.

public class Person
    {
        public string Name { get; set; }
        public Person Boss { get; set; }

        public Person ShallowCopy()
        {
            return (Person)this.MemberwiseClone();
        }
    }

Now, let’s create some objects and make a shallow copy of the worker and see if the objects are the same:

Person bigBoss = new Person() { Name = "Tony", Boss = null };
Person boss = new Person() { Name = "Silvio", Boss = bigBoss };
Person worker = new Person() { Name = "Paulie", Boss = boss };

Person cloneWorker = worker.ShallowCopy();
Console.WriteLine("Are the workers the same? {0}", worker.Equals(cloneWorker));
Console.WriteLine("Are the bosses the same? {0}", worker.Boss.Equals(cloneWorker.Boss));

This gives us the following results:

Are the workers the same? False
Are the bosses the same? True

“So what?” you might ask. Well, what that means is that if I change a property on the Boss of either object, it automatically changes in the other object (since only the reference was copied, and that reference points to the same memory address in both cases).

worker.Boss.Name = "Chuck";
Console.WriteLine("Worker's Boss' Name: {0}.", worker.Boss.Name);
Console.WriteLine("Clone Worker's Boss' Name: {0}.", cloneWorker.Boss.Name);

This gives us the output:

Worker's Boss' Name: Chuck.
Clone Worker's Boss' Name: Chuck.

It is possible that you may be okay with this happening. However, if you don’t want this to happen, you can implement a DeepCopy on your object instead. In the DeepCopy, you take a MemberwiseClone and then you call for a deep copy on every reference type in the object. In our example, I’d add this to our Person class:

public Person DeepCopy()
{
    Person copy = (Person)this.MemberwiseClone();

    if (this.Boss != null)
    {
        copy.Boss = this.Boss.DeepCopy();
    }

    return copy;
}

Now, when I check on the objects, they aren’t the same. And, when we change the property on the boss, it doesn’t automatically change in both places because they are completely separate objects.

Are the workers the same? False
Are the bosses the same? False

Worker's Boss' Name: Chuck.
Clone Worker's Boss' Name: Silvio.

That’s all there is to it. I have wrapped up the code for this blog post into a small console project and put it on GitHub. If you have any questions, let me know in the comments.

Code Tips

Why Salt Your Hashes?

Note: Post has been updated below

SaltSalted hashes? Have I decided to blog about breakfast?

No. By “Hash”, I mean “cryptographic hashes” and by “Salt”, I mean “additional input added to a one way hashing function”. Back in Episode 4 of my Podcast, I talked about a system that was written from the ground up to manage users, passwords, and permissions. During my little rant, I talk about storing passwords as the result of a one-way hashed value, but I didn’t really elaborate.

I realize that many of my regular readers may know this information, but I’ve been surprised at how many that I’ve found who do not. Hopefully, I can shed some light to those who don’t know and also become a viable source in search engine results for when the question is asked.

Let’s get the easy part out of the way first. We KNOW not to store plain text passwords, right? Some people know that and choose instead to store the passwords via two-way cryptography, meaning they can encrypt and then decrypt the password to compare it or email it you. That is also a terrible idea. Now, your entire system is only as secure as the security around your decryption key or decryption certificate. You’ve just made an attacker’s job very easy.

The better way to store passwords is to only store the result of a one-way hash. Then, when someone presents their password for authentication, you just hash the input and compare that to what you have stored in the database. However, even though this is good, it is still not right.

Take this for instance. Here is a sample table with hashed passwords.

user password
pete b68fe43f0d1a0d7aef123722670be50268e15365401c442f8806ef83b612976b
bill 59dea5f67aea4662c26a5ac6452233e783407d55c4f96d6c4df6f0d7c06c58af
jeff b68fe43f0d1a0d7aef123722670be50268e15365401c442f8806ef83b612976b
andy b6642c42bd670b0c070dd45d087877a4bc8d6ee29c88df59273ea48ed72b76c4
ron b68fe43f0d1a0d7aef123722670be50268e15365401c442f8806ef83b612976b

Right away, you should be able to see a problem. The hashes for pete, jeff, and ron are all the same. A common attack against hashed passwords is a rainbow table. In that case, dictionary words (or common known phrases) are pre-hashed and those hashes can then be compared against a compromised database. Let’s take a look.

password SHA-3 (256) Value
password b68fe43f0d1a0d7aef123722670be50268e15365401c442f8806ef83b612976b
letmein ceaa5fd0a764ad8202f43f2efc860d8c7472911ca9d1ccea2dc232713ae1fc0d
blink182 aadfce5bdba224673c168fb861f45cdd6ebf4e34d35001ae933bd53b7f6b337f
password1 abbe6325ea0d23629e7199100ba1e9ba2278c0a33a9c4bfc6cd091e5a2608f1a

Now, by comparing, we can see that the password for pete is the word password. That means that the password for jeff and ron are also “password”. By only cracking one hash, we gain access to two other accounts. This is not good.

The fix is to “salt” the password before hashing it. You want that salt to be a unique value. Some people create a random value and then store the salt alongside the password in another database column. Others derive the salt from something like the row’s primary key, etc. Either way is fine (as long as your derived value won’t change).

Now, let’s examine our user table.

user salt password
pete I7Yrs9THQyLxpVllSwbf 9b7ec6d82075a9e7d8227897e8919785031b9a7cdab5750dea044390d1fd1f46
bill K0kJJCQcVVqfLzykcpbP 297d00ae29ff3c32fe874c00d0154085ac862a154b061c17cd465de7f1cdee9a
jeff NwV7PdmPUKY6GgScEUqu c2936d36583d0513980e496005872e4954d142ed823b7b0b1abf28211efc538f
andy GpHrXjbQRTjObZWM7jbd 0338bd60f7d761ce9c8922087e87c9ccb7936bb5f9c5c28d72fd28f4d8708e6b
ron iHh8SX7fQEF2WFUOfxEp 07f459276c9be7d63aa8d57dac7468c8b16dd4367e91615fb9972543a707c403

We notice right away that none of the user’s hashes are the same. I didn’t change the passwords, but the salt values made the passwords unique so that they all hashed differently. We can no longer tell whose passwords are identical. Also, our plain dictionary attack no longer works. Even though we’ve telegraphed to the attacker what salt to use, the attacker would have to generate rainbow tables across their entire dictionary for each individual salt.

This isn’t 100% secure (nothing is), but this is a best practice and certainly will slow the attackers down. This method of storage, combined with strong passwords should keep your data as safe as it can be.

Thoughts? Disagreements? Share them in the comments section below.

EDIT (5/16/2014): I talked on my podcast referenced above about how easy it is to get behind or to overlook things if you do your own security as yet another reason NOT to do it. I recommended just using existing products or frameworks that have already been hardened over rolling your own. As a perfect example, I talked about doing all of this, but forgot about bcrypt (and others) that are much more secure, salt the value for you, and already have libraries in all of the major languages.

Code Tips

Sql Power Architect Java Heap Space Error

Sql Power ArchitectThis is definitely going to be one of those posts where I’m posting this not only for others to find while they are Binging and Googling, but for future Pete to come back and re-figure out how to do something that took him some time to figure out in the first place. I’ve had several posts like that (this gem chief among them), and this sort of situation is a very good reason to have a blog. Blogs are good places for a brain dump.

My issue this time was with a tool called Sql Power Architect. Sql Power Architect is a data modeling tool that I was using kind of as an Erwin-lite due to Erwin’s super high price tag and Architect’s free community edition.

I was trying to make a diagram of a database that I was being asked to examine for issues. I was able to reverse engineer the database and lay it out like so:

Sql Power Architect Test Database Diagram

However, when I tried to generate the PDF of this diagram, I got this error:

Sql Power Architect Java Heapspace Error

So, I did some searching and I wanted to increase the Java heap size, but only for that application if possible. I don’t run that many Java programs on my machine and I definitely didn’t want to upset the delicate balance of the Android environment that I have set up on the Windows side (which, incidentally is way more “picky” that the Android environment on the Mac side).

What I found is the Xmx switch for the java command line. I navigated to the Sql Power Architect install folder and figured out that architect.exe probably just called architect.java under the covers, so I executed this command below:

java -Xmx1024m -jar architect.jar

Sql Power Architect With Xmx Switch

That fired up the program with a 1 gig heap size. After that, I loaded my diagram and was able to export it to PDF without any issues.

The finished PDF:
Sql Power Architect Pdf Success

As I said, hopefully this post can be helpful to some poor soul in the future (even if that soul is me).

Code Tips

Git Error : (does not point to a valid object)

A friend of mine IMed me the other day to ask if I had ever seen an error like the one below:

error: unable to find e291a84831b445ba982539cc63a418126f0b5364
error: refs/heads/master does not point to a valid object!
fatal: Couldn't find remote ref master
fatal: The remote end hung up unexpectedly

I had not, but it seemed plain enough. It appeared that the head of the master branch was pointing to a commit that didn’t actually exist in the repository. I don’t know for sure how this happened, but my friend’s team suspected a disrupted internet connection on push as one theory.

I Googled the error and found suggestions like “make a new remote” and “clone to a new branch, push, delete master, rename new branch”. This seemed like just too much work. There had to be an easier solution.

I was unable to clone the remote to my own machine (I got that same error on trying) and the team was in another state, so – short of a screensharing session – I couldn’t easily work with them on the problem.

I had the developer who had done the last known valid commit before this error send me the most recent 5 items output from the “git log” command and got the following (edited for privacy):

commit b65f24a64e78b38d193aa545d7b184fe26330a4c
Author: Joe Developer <joed@somewhere.com>
Date:   Fri Jul 27 10:05:53 2012 -0400

    Moved foo.jar to libs folder

commit 32b15424509881760667a77b615cc91e8e31afb9
Author: Joe Developer <joed@somewhere.com>
Date:   Thu Jul 26 21:45:46 2012 -0400

    Load swf files

commit bfac8d86c20ebbcac22af4e599e5815b0586f3d0
Author: Joe Developer <joed@somewhere.com>
Date:   Thu Jul 26 19:18:25 2012 -0400

    Navigation bug fixes

commit 60c5ff87435861157e56d948e09c63ad2f4db520
Author: Jane Developer <janed@somewhere.com>
Date:   Thu Jul 26 15:52:36 2012 -0400

    post merge

commit 1a97d137a51c6cd34825e4c9bc705620dfff7712
Author: Jane Developer <janed@somewhere.com>
Date:   Thu Jul 26 15:24:40 2012 -0400

    initial commit

Because Git is based in the file system, I could literally navigate to the remote file system and go to the ProjectName.git folder and into the refs/heads/ folder and find the master file (no extension). Inside was one string, the offending e291a84831b445ba982539cc63a418126f0b5364. I just replaced that string with the hash of the latest valid commit – b65f24a64e78b38d193aa545d7b184fe26330a4c – and then saved.

After that, I could clone the repo and the developers could pull, merge, and push their own changes. They were using DropBox in this instance as a “poor man’s remote” and upon further reflection, I have to wonder if that is what caused the conflict. Perhaps there was a problem with DropBox syncing all of the files and maybe a race condition at some point that resulted in a corruption? I know DropBox isn’t a perfect “remote server” solution, but a lot of people use it for certain circumstances, so this might be something to look out for.

If anyone else has seen this error and has a better fix than the one described here, then please leave a comment and let me know.