Blog | G5 Cyber Security

Secure ASP.NET MachineKey

TL;DR

Your ASP.NET application’s MachineKey is vital for protecting sensitive data like session information and view state. This guide shows you how to securely configure it, rotate it regularly, and protect it from compromise.

Understanding the MachineKey

The MachineKey is used by ASP.NET to encrypt and decrypt data. If an attacker gets hold of your MachineKey, they can steal session cookies, impersonate users, and potentially access sensitive information. It’s stored in either the web.config file (less secure) or Windows Server’s encryption store (more secure).

How to Secure Your MachineKey

  1. Store the MachineKey in the Windows Encryption Store: This is *much* safer than storing it directly in your web.config file.
    • Open IIS Manager.
    • Select your server at the top level.
    • Double-click ‘Server Certificates’.
    • In the Actions pane (right side), click ‘MachineKey’.
    • Follow the wizard to generate a new key or import an existing one. Choose a strong password!
  2. Configure web.config: After storing in the encryption store, update your web.config file.
    <system.web>
      <machineKey storage="String" decryptionKey="YourDecryptionKey" validationKey="YourValidationKey" algorithm="AES" />
    </system.web>

    Important: Replace YourDecryptionKey and YourValidationKey with the values generated by the IIS Manager wizard. The ‘algorithm’ can be AES, DES, or TripleDES; AES is generally preferred for its strength.

  3. Regular Key Rotation: Don’t use the same key forever! Rotate it at least every 90 days (or more frequently if your security requirements are high).
    • Repeat step 1 to generate a new key.
    • Update your web.config file with the new keys.
    • Restart your application pool after changing the keys.
  4. Protect Access to IIS Manager: Limit who can access IIS Manager, as this is where the key can be managed.
    • Use strong passwords for all administrator accounts.
    • Enable multi-factor authentication (MFA) if possible.
    • Regularly review user permissions.
  5. Monitor for Suspicious Activity: Keep an eye on your server logs for any unusual activity that might indicate a compromise.
    • Look for failed login attempts to IIS Manager.
    • Check for unexpected changes to the web.config file.
  6. Consider using Data Protection API: For more complex scenarios, explore the .NET Data Protection API which offers greater flexibility and control over key management.
    using Microsoft.AspNetCore.DataProtection;
    
    // Example (simplified)
    var provider = DataProtectionProvider.Create(new DirectoryInfo("/path/to/keyring"));
    byte[] key = provider.GetKey();

Troubleshooting

Exit mobile version