Why do I lose my key container when I reboot?

4

For many years we have kept our strong name key in a key container. Visual Studio doesn't directly support that but, it works fine if you just edit the .csproj file and add:

<KeyContainerName>MyKeyName</KeyContainerName>

We install the key into the key store by doing:

sn -m Y
sn -i MyKeyFile.snk MyKeyName

We can then remove MyKeyFile.snk from that machine and the key is a little more secure.

Recently, this has become a problem after reboots. We suspect the issue was introduced by VS 2015 but, it might be caused by Windows 8 and/or 10. We install the key into the key container and everything works. Then, we reboot that machine and builds fail with:

CSC : error CS7028: Error signing output with public key from container 'MyKeyName' -- Keyset does not exist (Exception from HRESULT: 0x80090016)

It looks like the key container was lost in the reboot but, if we do:

sn -m Y
sn -i MyKeyFile.snk MyKeyName

It fails with:

Failed to install key pair -- Object already exists.

We have to delete the key container with sn -d and then add it back and Visual Studio is happy.

What is going on here? Why can't Visual Studio see our key container after a reboot when sn can see it? Where are key containers actually stored?

visual-studio
cryptography
cryptoapi
asked on Stack Overflow Sep 23, 2015 by John Vottero

1 Answer

6

First, you need to be careful when using the "sn -m" command to switch between machine based keys and user based keys. The command is case sensitive and invalid values are handled as if a value was not specified, the current setting is displayed. So, "sn -m Y" does NOT enable machine based keys, you have to say "sn -m y" (lowercase y or n).

The current version of CSC.exe seems to only use machine based keys. I don't know if that is a recent change but, that was the behavior that I observed when using .NET V4.6 and VS 2015.

Machine keys are kept in C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys. When you execute "sn -i file.snk name" to install a key, a file is created in that directory. The file is named with a couple of GUIDs so you will have to look at the modification dates to figure out which one was just created.

If you check the Properties of the new file and look at the "Security" tab, you will see a "LogonSessionId_n_nnn" entry. That entry in the ACL grants your logon session access but, if you reboot, you get a different logon session so that entry no longer grants you access. That is why we could install the strong name keys and use them until we rebooted. It also explains why the key needed to be deleted before it could be reinstalled, the key was still there but, we didn't have access to it.

You can edit the ACL of that file and grant yourself "Read, Read & Execute" access with an AD username or group and the strong name key will work even after a reboot.

answered on Stack Overflow Oct 20, 2015 by John Vottero

User contributions licensed under CC BY-SA 3.0