Handling Request too large and identify limits in ASP.NET

For security reasons request sizes are limited by default. This is configurable in the web.config file through the httpRuntime sections maxRequestLength attribute. The value is an integer and it’s default value is 4096 (KB) and therefor is 4,153,344 bytes or 4 MB. The configured values can easily be read using the .NET configuration API: If an request is larger than this value a HttpException is thrown when the HttpRequest properties Forms, Files or InputStream are accessed. The HttpException class has a property named WebEventCode which contains a value of the WebEventCodes lookup class: RuntimeErrorPostTooLarge which is an integer with the value 3004. If you catch this exception you can handle the error in your application code and for instance return a custom error message. But… When hosted in Internet Information Services (IIS) there might be another barrier: The request filtering module. This also has a section to configure the maximal length of a request using the requestLimits section and its maxAllowedContentLength property. By default this is set to 30,000,000 (bytes) and therefore is 29.297 KB or 28.61 MB. If this limit is hit IIS will return a HTTP error 404 with sub status code 13 with the reason phrase “Content Length Too Large”. The .NET configuration API refuses to load this section. And even if accessed raw using the system.webServer sections SectionInformation property and its GetRawXml method the possible inheritance is not reflected. So values configured on server and not on site level divergent from the default cannot be found here. IIS at startup create a configuration file located at *{windows drive}\inetpub\temp\appPools\{appPoolName}\{appPoolName}.config. The IIS application pool identity (the account running our web application) of course has read access to the file. To build up the path we need to get the application pool name at runtime. There is a server variable called APP_POOL_ID that will provide the neccessary information. The following code get the local overwritten values from the web.config, the server level configured, the default value or null if request filtering is not installed: At application startup the configuration can now be validated – request filtering schould always have a bigger value when you want to handle these kind of errors in your application code – and the values of a maximal request length can be read and possibly displayed.

Using credentials based on a SecureString that is disposed

Today I was building a credential store API. One implementation against the Windows Credentials Manager (CredMan), the other one persisting information in a database. Of course the data is not persisted in clear text. I use either the MachineKey functionality or a RSA certificate based encryption.So far so good, but I want the passwords to be secure in memory to. The .NET Framework already has a Type built in for that purpose: SecureStringThe SecureString class implements the IDisposable interface and having a property in a class of that type means losing control of the destruction.The implementation will return ICredentials instances to authenticate mostly web requests or provide proxy authentication. So I created a test to figure out how the combination of NetworkCredential and SecureString behaves. All green – It’s possible to use a NetworkCredential object that is constructed with a SecureString even after the SecureString has been disposed. Looking inside the credential object using redgate's Reflector reveals that NetworkCredential internally uses the copy method to clone the SecureString. When a normal string is passed to the constructor it is wrapped into a SecureString also.Sadly the NetworkCredential class does not implement IDisposable. So the issue is carried out to the user code.Keep in mind: When using NetworkCredential to call SecurePassword.Dispose() after the credentials aren’t required any more!

.NET Licensing - ode to monolithic applications?

The Microsoft .NET Framework has a built in licensing technology. It can be found in the namespace System.ComponentModel and System.ComponentModel.Design. Here is a small sample implementation of the minimal required classes: A lot of component producers use this licensing model – so does Tx Text Control – the component that I wanted to use. As a user you just create a *.licx-file, include it into the project as “embedded resource” and add the components that should be licensed by their fully qualified type names – one per line: During the build the LC-Task executes the license compiler (LC.exe). The license compiler is part of the .NET SDK that is part of the Windows SDK. If you have the Windows SDK 8.1 or Visual Studio 2013 installed it can be found at “C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\”. The result is the “Licensing.dll.licenses” file that is embedded by the C#-Compiler (Csc.exe) in the next step. During runtime the LicenseProvider-attribute is evaluated and the defined license provider is handed over to the System.ComponentModel.LicenseManager’s Validate method. This call forwards to the internal method ValidateInternalRecursive which then calls the GetLicense method of the LicenseProvider. The first argument of the GetLicenseCall is of type LicenseContext and at runtime filled with the static held instance of the internal class RuntimeLicenseContext. To resolve the license key the method GetSavedLicenseKey is called on the LicenseContext. The implemention offers two options to resolve the key: Resolve from URI: new Uri(new Uri(AppDomain.CurrentDomain.SetupInformation.ApplicationBase), AppDomain.CurrentDomain.SetupInformation.LicenseFile) Resolve from Embedded Resource: The lookup on references/loaded assemblies is only processed, if there is NO entry assembly - for instance within ASP.NET that is the case. But my intend was to create a build task for MsBuild that converts Microsoft Word’s DOCX files into PDF documents. So I have an entry assembly (MsBuild.exe). The entry assembly knows nothing about TX TextControl – and that is a good thing! I have no control over the entry assembly (MsBuild.exe). A situation I guess to find in every composite UI/modular desktop application. No wonder the monolith is often the preferred architecture especially on the desktop! After an intense debugging session through the framework sources (supported by red gate’s Reflector) I wrote a small helper class. WARNING: I use reflection to access internal types and private fields and modify their values – this means: If Microsoft decides to change their internal implementation it might not work anymore. But as we as can see the code was written for .NET 1.0 and has not been updated in the last 10 years: It’s not very likely that changes will happen. Now I just need to call LicenseLoader.LoadLicensesFromCallingAssembly() before the Tx Text Control component is instantiated the first time and everything works as expected. HTH

Disabling Registry-System-Redirection on 64bit

x64 view from x86: using Microsoft.Win32; using(var registryKey = RegistryKey.OpenBaseKey( RegistryHive.LocalMachine, RegistryView.Registry64 ).OpenSubKey(@"Software\Microsoft\InetStp\Components")) { var value = registryKey.GetValue(@"WMICompatibility"); } x86 view from x64: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft

Disabling File-System-Redirection on 64bit

The following call disables File-System-Redirection on 64bit Windows in WOW mode (e.g. Accessing Program Files and ending up in Program Files (x86)): // Minimum client Windows XP Professional x64 Edition or higher // Minimum server Windows Server 2003 with SP1 or higher NativeMethods.Kernel32.Wow64DisableWow64FsRedirection(pt1);