viewStateEncryptionMode="Always" not encrypting - asp.net

Due to some security concerns i need to enable View State Encryption. I have viewstate & viewstateMAC turned off but i need to encrypt the "control state" string that is included in the __VIEWSTATE form parameter.
Currently my web.config looks like:
<pages enableViewState="false" enableViewStateMac="false">
When i set the following, in cassini, my viewstate is encrypted:
<pages enableViewState="false" enableViewStateMac="false" viewStateEncryptionMode="Always">
When i make the same change on my IIS 6 server, nothing happens.
I see the app domain recycle(Event: Application '/LM/W3SVC/...' located in 'C:...' initialized for domain '...'). when i touch web.config but i do not get encrypted viewstate as with cassini. I have tried Site Stop/Start, IIS Reset Stop/Start, Clear ASP.NET Temporary file cache. Anyone have any suggestions on what needs to be done to configure this?

I ran into a similar problem with this and it came down to the fact that if you pre-compile your site the web.config node for pages is ignored. You have to set those settings at compile to get it working. I know this is year late, but I figure if someone else comes here looking for solution to the problem this might be useful information.
A little blurb about this: http://blogs.msdn.com/b/asiatech/archive/2011/07/19/pages-settings-don-t-work-for-pre-compiled-asp-net-applications.aspx
(Link dead - blog pointed to this documentation: ASP.NET Web Site Project Precompilation Overview )
My customer had a viewstate MAC
validation problem. As a workaround, he wanted to disable the
viewstate MAC validation before find out the final solution. However,
he was still seeing the problems after added follow settings in the
configuration files.
Customer’s application is a pre-compiled ASP.Net application with
updatable option disabled. Looking at the code generated by compiler
with above settings, we found these settings are hard coded. So, this
means simply add the above setting into web.config doesn’t affect a
pre-compiled application. To make this taking affect, the application
has to be re-compiled.
[DebuggerNonUserCode]
private void __BuildControlTree(default_aspx __ctrl)
{
__ctrl.EnableViewStateMac = false;
__ctrl.EnableEventValidation = false;
__ctrl.ViewStateEncryptionMode = ViewStateEncryptionMode.Never;
This is a by-design behavior.

Related

ConfigurationManager.AppSettings("IsDebugMode") is returning null

Background: I'm developing a website in ASP.NET with VB.NET backend, .net framework is 4.0. It's actually a redesign of an existing site, and everything works on the old version, and in fact the settings are the same there...
So I've got a master page for the admin section of my website which requires RSA authentication, however I want to skip that part of it obviously when I just hit f5 and run in debug on my local machine. So at the beginning of the page load event I do a check for...
If NOT ConfigurationManager.AppSettings("IsDebugMode") then
here's my code for authentication...
else
return true 'user automatically authenticated
end if
however, when I hit f5, it keeps throwing the error "Object reference not set to an instance of an object." I've googled it, and it looks like this syntax is correct, and like I said, the code is copy/pasted from the existing site, which functions the same in this area, and works just fine.
Is there a setting somewhere that I need to "turn on" this feature? I've never used the configuration manager before, so I'm not sure if it is requiring more than I've built so far. Anyone familiar with this?
Find and open web.config file, it's usually in the root directory of your web application, locate the appSettings section, add in an entry like:
<add key="IsDebugMode" value="true" />

Can I see a log of IIS loading (or not loading) a .net httpmodule?

I have a site that uses a .net security module to secure certain areas of the website. It's not working, the pages that should be password protected are not. Other than that, the site doesn't throw any errors.
I don't have access to the code, and the module doesn't seem to log anything.
Is there an IIS or .Net log of loading/calling httpModules? I feel like it's not loading/calling it, and it's just not telling me.
My web.config has this snippet, which loads the module:
<httpModules>
<add name="MyApp.SecurityModule" type="MyApp.Host.Security.WebForms.SecurityModule" />
</httpModules>
You can use Modules property in global.asax class to inspect the http modules that are loaded and associated with the application - use any request event such as BeginRequest or PostMapRequestHandler.
However, I don't think this would be an problem - if you are configured the module in the web.config then it would be loaded. If there are any issues then the ASP.NET will report an error. Most probably, http module code must be working in a certain way or needs certain per-conditions that are not being met.
Use tools such as Reflector or ILSpy to inspect & de-compile your application assemblies - check the code for the said type (MyApp.Host.Security.WebForms.SecurityModule) - frankly speaking, in the absence of documentation/commented code, it would be the only option to figure out how exactly your module is supposed to run (and then trouble-shoot accordingly).
Have you thought about using something like Glimpse: http://getglimpse.com/
If may help you debug the issue a little better.

"Validation of viewstate MAC failed. If this application is hosted by a Web Far..."

i am facing the dreaded:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Error.
Ok so i looking it up and found that it can be caused by two things, viewState which can not be verified by the page, and/or events that can not be validated.
I put
<pages enableEventValidation="false" enableViewStateMac="false" viewStateEncryptionMode="Never">
In my web.config to stop the problem, but that hardly seems like a fix to me.
The thing is, i never even used viewState in my application. I know that asp.net uses viewstate by default to store some things, but i doubt the default values stored here will cause any errors.
I noticed that the problem seems to happen when i postBack and the page has not finished loading yet.
Thanks
Edit: Please, can someone test my website www.vittoriosaStarsNursery.com and see if you get the error i got above? I dont get it locally but people keep telling me they are getting it.
Isnt this just a case of putting a one liner in your web.config
<machineKey decryptionKey="A4B12CCDD50E95F8GB9GFH6JKAT4Y0U0I2OF2DF2AAFE5AB46189C,IsolateApps" validation="AES" validationKey="480CDF2AS9S9AS5CFDGF0GHFH9JJH4KHKAKLJ2L9F3SAS82A6C16911A29EF48903783F94529C21570AACB72766FB38CD4CE7B85B0ACE3149DC5FC1CCF1AA1CECE3579659996593B06,IsolateApps"/>
One thing I have come across that causes this issue has to do with the recycling intervals of the app-pools on the webserver.
I found this by looking at the event information in Eventviewer/Application logs and the "Task Category" called "Web Event". Then for the time period that this event took place I looked to see if there were any recycled events that took place just before that (Eventviewer/System logs and the "Source" called "WAS".
By default an app-pool will recycle every 1740 minutes (29 hours). If this recycle happened while a user is busy on the site and send post back to the server, the server no longer recognizes the session/viewstate and rejects what is being posted back.
To overcome this from our perspective is to set the recycle event to happen at a specific time of the day when we don't expect activity on the site. In our case 3am in the morning.
Hope that helps someone out there.
You're not going to like my answer. This error is basically unavoidable in webforms. My solution was to leave webforms for MVC3 and razor.
I noticed that the problem seems to happen when i postBack and the
page has not finished loading yet.
this is one of the easiest ways to cause this error. In ASP.NET 3.5 (or 4.0) there's a setting that you can make sure viewstate gets loaded very early in the page to try to help diminish it. It still doesn't solve it.
Chunking the viewstate doesn't solve it.
There is just something inherently wrong to the way webforms works that this error will plague your application at random times forever.
At my site, this meta tag were causing the error:
<base href="http://www.SITEURL.COM" />
I have a dropdown, I update on another dropdowns changed selection. So when the postback happened (dropdown #2 changed index), I got the exception.
I've tried everything else from applying machinekey to web.config and setting theese attributes at the page
EnableViewState="false" EnableViewStateMac="false"
I am using VS 2010 against a Windows Web Server 2008 and what I eventually found was that I had two keys set for the same service in the appSettings section of webconfig. I went to IIS and checked the Application Settings on the virtual directory and got an error, fixed it in the WebConfig and the problem resolved. I did create a machine key but that did not fix the problem. Nor did the
pages (...) validateRequest="false" enableEventValidation="false"
enableViewStateMac="false" viewStateEncryptionMode ="Never"/
Settings. FWIW ...
I used this Microsoft article to create my own machineKey validationkey and decryptionKey. As others have stated, this can be placed within the system.web section of web.config, though there are security concerns if other people get hold of the key.
Well, yes i suppose disabling encrypted viewstate solves the problem but i have never tested it nor do I advise it. Viewstate stores the state of controls and is also very convenient for storing persistent variables.
Take for example you work for a garage and have a list of jobs. You go to a page that lists the jobs. Now you click a job which goes to another page appending the jobid (eg. job.aspx?id=1). On that page, there is a checkbox which marks the job as complete. Once you tick that checkbox, it posts data back to same page and writes to the database that the job is complete. But how does the server know which job to mark as complete because you have only posted back true or false from the checkbox. However, if the first time you load the job details page you record the job id in Viewstate, then when you post pack the checkbox, you can read in the jobid from the viewstate.
Why is it not good to use unencrypted viewstate?
Imagine what the server has to do to mark the job as complete. It probably has to run an sql command to update the database. Something like UPDATE jobs SET completed=GETDATE() WHERE id=1.
If your viewstate wasnt encrypted and i could add my own job id, I would put something like '; DELETE FROM jobs;' which would then cancel out the initial UPDATE command and delete ALL your jobs... not very good for the garage :)

Global.asax not firing for .aspx pages in IIS7

We run a link redirection service which can handle links thrown at it in various formats. One of these formats is to append the destination URL to the end of the link, for example
http://url.fwd/abcd/http://www.mydomain.com/page.aspx
This was working on a Windows Server 2003 / IIS6 box for the last two years, but now we're trying to move to a Windows Server 2008 / IIS7 setup and its not working anymore.
I've read about the problem with colons in the URL but it doesn't affect pages not ending in '.aspx'. For instance,
http://url.fwd/abcd/http://www.mydomain.com/page.php
would redirect fine.
http://url.fwd/abcd/http//www.mydomain.com/page.aspx
also works fine (note the lack of a second colon). Despite being the wrong URL, it does get handled by our URL forwarding system, which uses a custom 404 page. On the old system, we had a similar problem, so a method was written in Global.asax > Application_Error specifically to handle the '.aspx' case, and it worked fine.
On our new server, the Application_Error never gets thrown in Global.asax. Instead, I get a System.NotSupportedException - "The given path's format is not supported". This System.NotSupportedException is the exact case we handle in the Global.asax page, so it's definitely not being fired.
I've changed the registry keys indicated in several forum posts,
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET VerificationCompatibility=1
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP|Parameters AllowRestrictedChars=1
I've tried changing the Handler Mappings settings for .aspx.
I've tried setting the App pool to use classic mode instead of integrated, but this causes a completely different error where static content such as images and CSS do not display at all. I've checked that static content is enabled in the windows features, and it is.
Under classic mode, the '.aspx' request throws two Bad Request errors with absolutely no information whatsoever. The code of the error page I get is literally
Bad Request<html><body>Bad Request</body></html>
UPDATE: I've changed the static file Handler Mapping to the form found in this page
http://improve.dk/blog/2006/12/11/making-url-rewriting-on-iis7-work-like-iis6
However, as the author rightly points out, this is a hack and not the correct way of doing things under IIS7. It also only fixes the static file problem in classic mode. '.aspx' pages still throw an error under classic mode.
Any thoughts or input would be greatly appreciated at this point.
IIS 7 Solution
The easy solution in IIS 7 is to add a setting in your web.config file to tell IIS to process all requests through your Global.asax events. Just add or change this section in your web.config to enable requests:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
In my case, I was publish my site in production and I miss copy to server App_global.asax.compiled file. For this reason was not fire the Events inside Global.asax.
Hope anyelse help this tips, I lost 8 hours seeking.

Editing Web.config programmatically

What is a good way to edit a Web.config file programmatically?
I looked into System.Xml but couldn't find any obvious answers.
This fellow shows sample code if you still want to do it after all the caveats:
protected void EditConfigButton(object sender, EventArgs e)
{
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["test"].Value = "newvalueFromCode";
objConfig.Save();
}
}
One valid reason for editing a web.config is to encrypt it, which is what that article is about.
You can use the WebConfigurationManager to read specific configuration sections. This will return a ConfigurationSection object. You can use this to read/modify the ConfigurationElements in the section. Once you have updated them, you can Save the ConfigurationSection and it will update the file with your changes.
I use this to automatically encrypt the appSettings and connectionStrings on Application_Start if they aren't already encrypted. I haven't actually changed any settings this way, but it seems like you ought to be able to do so.
Saving the updated configuration file may cause the app to recycle depending on how it is built.
Depending on what you are doing, the method is really a bit different in each situation. However the most robust method is to load it as an XmlDocument and modify it as needed via that method, but you MUST be careful to only modify it in the needed manner.
In theory; you could just generate a web config file programmatically and with some templating to make it easy.
However, if you're trying to edit your web.config from within the site; it's highly recommended you don't. At the very least; you'd trigger an app reset every time you updated it; which would be especially bad if you're using in-process sessions.
As Anders asked, what is it you're trying to do?
Yes I agree with Josh. I have tried this before and I've had two negative effects:
Slow loading if the current page after postback because ASP.NET is loading the web.config and all related resources
If you change the web.config early enough in the load cycle (e.g. global.asax events) the site may never load or fail in unpredictable ways
Agree with others, editing the webconfig is achievable, but has knock on effects are just to dangerous / risk involved
If its a value that is application specific, then it should be in an application specific config file
Lot of time you want to modify application specific settings after deployment like say when something is wrong e.g. switching the database connection in case current DB goes down. Moreover sometimes you want to create your own XML based configuration file which you want o modify programatically.
Try XML Webpad - http://xmlwebpad.codeplex.com/
Its a framework to view an edit XML files. Once you integrate it with your web app, editing web.config ill be as simple as viewing the web.config page, making the required changes and hitting the save button (all from within your application).

Resources