Cryptographicexception: Padding Is Invalid and Cannot Be Removed and Validation of Viewstate MAC Failed

CryptographicException: Padding is invalid and cannot be removed and Validation of viewstate MAC failed

First of all lets start from the fact, that this error of view state happens on PostBack.

Also I must say that I have done all the things that every one suggest to do to avoid this problem. And I have single machine, but 2 pools that run the same Pages.

So someone do an action, ether a man, ether some other search machine by 'clicking' on your pages, or some hacker try to check your system for problems...

I have similar problems (rare but existing ones), and I finally found that people try to hack-test my pages. (from the same IP I have and dos attacks)

I modify the function LoadPageStateFromPersistenceMedium() that translate the viewstate, and see by logging what exactly was the input, and from what IPs... then I started monitor these results and see that the view state was changed by hand - or was totally empty.

On error I just redirect him to the same page...

Here is what I did...

public abstract class BasePage : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
try
{
.. return the base, or make here your decompress, or what ever...
return base.LoadPageStateFromPersistenceMedium();
}
catch (Exception x)
{
string vsString = Request.Form[__VIEWSTATE];
string cThePage = Request.RawUrl;

...log the x.ToString() error...
...log the vsString...
...log the ip coming from...
...log the cThePage...

// check by your self for local errors
Debug.Fail("Fail to load view state ! Reason:" + x.ToString());
}

// if reach here, then have fail, so I reload the page - maybe here you
// can place somthing like ?rnd=RandomNumber&ErrorId=1 and show a message
Responce.Redirect(Request.RawUrl, true);

// the return is not used after the redirect
return string.Empty;
}
}

Second Reason

Now there is one more reason why this can happen, and the reason is because some one click on your page before the __EVENTVALIDATION is loaded.

This eventValidation is placed on the last button-even that asp.net found, and if you have some of them on many place on the page, or near the button, then this go to the end of the page.

So even if you see the viewstate on the top of the page, where is the Validation ??? maybe this never loaded - page corrupt ?, too fast user click on page ?

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" ... >

To avoid this kind of problem I made a simple javascript that I do not let it press the button unless this input have been loaded !!!.

One more comment, the __EVENTVALIDATION is not always presents ! so is maybe safer not to search for this field if you make a general solution, but to make a javascript trick to just check if the full page is loaded, or something else that you think.

Here is my final solution with jQuery: (note that I check on PageLoad if eventvalidation exist !). I have this placed on my MasterPages.

<script language="javascript" type="text/javascript">
function AllowFormToRun()
{
var MyEventValidation = $("#__EVENTVALIDATION");

if(MyEventValidation.length == 0 || MyEventValidation.val() == ""){
alert("Please wait for the page to fully loaded.");
return false;
}

return true;
}
</script>

protected void Page_Load(object sender, EventArgs e)
{
// I do not know if Page can be null - just in case I place it.
if (Page != null && Page.EnableEventValidation)
{
Form.Attributes["onsubmit"] = "return AllowFormToRun();";
}
}

You can test by placing near the button of your page a delay.

<% System.Threading.Thread.Sleep(5000); %>

Update

Today I see in log this message again for WebResource and what I discover is that a bot getting the pages and make all the character on the links in lower case, including the parameters, so this was one more reason to not getting the correct encoded string, and throw a message like Padding is invalid and cannot be removed.

Hope this help you more.

Validation of viewstate MAC failed

Modify your web.config with this element:

<pages validateRequest="false" 
enableEventValidation="false"
viewStateEncryptionMode ="Never" />

Any more info required, refer to the ASP.NET Forums topic

Padding is Invalid and cannot be removed exception on WebResource.axd

The error is because your appdomain was recycled/restarted. When that happens the application and the machine key is set to auto, it changes. That affects the decryption of the info in the url of the resources urls (.axd). Setting up a fixed machine key will prevent it from ever happening again.

Please check this for more info on a similar case (the explanation is with an issue with viewstate validation, but the cause is the same one): http://www.developmentnow.com/blog/InvalidViewstate+Or+Unable+To+Validate+Data+Error.aspx

I also had been wondering about it for quite a while. After I saw this question it got me on it again: Is this an attempt to break my ASP.Net site's security? ... which I just answered with very much the same. I had the feeling it was around some restart of something, because when we published something that recycled the application the error showed in the log, but I didn't have any other source stating its relation (today I found that case on invalidviewstate because of the machinekey change :))

Ps. above finally explains it on single server :)

Padding is invalid and cannot be removed. error with a twist

If this is happens on page with out post back then probably your proxy is convertting the url in lowercase chars and break the code.

I have one more bigger answer here with a trick to log the error and see whats really get on your page:

CryptographicException: Padding is invalid and cannot be removed and Validation of viewstate MAC failed

machine key not working - viewstate mac failed

One of our servers was behind on Windows updates and after running those updates the problem appears to be gone. I've re-run the exact tests that consistently invoked this exception before and it's not having any issues.

ViewStateUserKey + shared hosting + ViewStateMac validation failure

from the moment that is play on local host and not on server then is seems to me that you have some issues with the session, and the sessionID is change/expire fast on your server, faster than the authentication expires.

And for that reason from the time the user see the page, to the post it, the session has expired or change before the Authentication change, so the sessionID is diferent and so you get this error.

Other thinks that you can look is that you have set the machineKey on web.config.

Update

Compare your code with the Scott you have make a different. Scott use the user name, that is not change at all, and you use the sessionid, that can change as I say.

For me, ether use what Scott suggest, the user name, ether some other value that is not change also, like the cookie of the user for example, that is not change so easy.

So from Scott http://www.hanselman.com/blog/ViewStateUserKeyMakesViewStateMoreTamperresistant.aspx

void Page_Init (Object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
ViewStateUserKey = User.Identity.Name;
}

And this the reason that scott check if the user is Authenticated, because is gets his name. If you go with sessionid, or the cookie of the user, you do not need to check if is authenticated.

Now if you use the cookie to set them on viewstateuserkey, for all users then the one that not permit cookie, and try to make any post it will get error. So think a solution like that to handle them

https://stackoverflow.com/a/2551810/159270



Related Topics



Leave a reply



Submit