What you need to know about AllowUnsafeUpdates (Part 2) [Reproduced]

Source: Internet
Author: User

Original article address: SharePoint Internals-Hristo Pavlov's Blog

In short here is how to dealAllowUnsafeUpdates:

1) Don't update SharePoint objects from your code behind on GET requests as if you do so your code will be exploitable via a cross-site scripting. if you understand the consequences of doing this and still want to do it then see the first part of this article about how to useAllowUnsafeUpdatesProperty.

2) If your code is processing a POST request then make sure you call SPUtility. validateFormDigest () before you do anything else. this will ensure that the post request is validated (that it is not a cross-site scripting attack) and after that you will not have to worry aboutAllowUnsafeUpdates, Because its default value will be"True"After the form digest is validated. To find out more about this read below.

So you have probably noticed from part one of the article that the internal method that setsAllowUnsafeUpdatesProperty had quite an interesting name:SetIgnoreCanary (). CanaryIs something that refers to a method of protecting from stack overflow attacks. the terminology is a reference to the historic practice of using canaries in coal mines, since they wocould be affected by toxic gases earlier than the miners, thus providing a biological warning system. in SharePoint the request canary is a unique pseudo-random value that protects you from cross-site scripting attacks. if you have ever examined the HTML source of your SharePoint pages you have probably noticed_ REQUESTDIGESTHidden field. This is what is referred to asCanaryOrForm DigestAnd is used to verify that the request is genuine.

<Input

Type = "hidden"

Name = "_ REQUESTDIGEST"

Id = "_ REQUESTDIGEST"

Value = "0x5DC31993EF285644A7C48F ........... BFA2E6FB719CD7E9DB0922A329E97, 19 May 2008 23:37:22-0000 "/>

As you see this is nothing more than a hidden field set by the server and verified back by the server when the page is submitted. As your ented by Microsoft:The purpose of form digest validation is to help prevent security attacks where a user is tricked into posting data unknowingly to a server.

The place whereForm DigestValue is set is the WebPartPage. FormOnLoad () method:

Private void FormOnLoad (object sender, EventArgs e)

{

If (HttpContext. Current! = Null)

{

SPWebcontextWeb = SPControl. GetContextWeb (HttpContext. Current );

If (contextWeb! = Null)

{

SPWebPartManager. RegisterOWSScript (this, contextWeb );

If (this. Page. Items ["FormDigestRegistered"] = null)

{

StringbstrUrl = SPGlobal. GetVTIRequestUrl (this. Context. Request, null). ToString ();

SPStringCallback pFormCallback = new SPStringCallback ();

ContextWeb. Request. RenderFormDigest (bstrUrl, pFormCallback );

Base. ClientScript. RegisterHiddenField ("_ REQUESTDIGEST", SPHttpUtility. NoEncode (pFormCallback. StringResult ));

FormDigest. RegisterDigestUpdateClientScriptBlockIfNeeded (this );

This. Page. Items ["FormDigestRegistered"] = true;

}

}

}

}

The actual value of_ REQUESTDIGESTField is generated by the COM objects inOWSSVR. dll.After that another method is called: FormDigest. RegisterDigestUpdateClientScriptBlockIfNeeded ()

Public static void RegisterDigestUpdateClientScriptBlockIfNeeded (Page page)

{

DoubletotalMilliseconds;

If (SPContext. Current. Site. WebApplication. FormDigestSettings. Enabled)

{

TotalMilliseconds = SPContext. Current. Site. WebApplication. FormDigestSettings. Timeout. TotalMilliseconds;

If (totalMilliseconds & gt; 2147483647.0)

{

TotalMilliseconds = 2147483647.0;

}

}

Else

{

Return;

}

Int num2 = Convert. ToInt32 (double) (totalMilliseconds * 0.8 ));

If (! Page. ClientScript. IsOnSubmitStatementRegistered (typeof (FormDigest), "SPFormDigestUpdaterSubmitHandler "))

{

Page. ClientScript. RegisterOnSubmitStatement (

Typeof (FormDigest ),

"SPFormDigestUpdaterSubmitHandler ",

"UpdateFormDigest ('" + response code. ScriptEncode (SPContext. Current. Web. ServerRelativeUrl) + "'," + num2.ToString (CultureInfo. InvariantCulture) + ");");

ScriptLink. Register (page, "init. js", true, false );

}

}

There are a couple of interesting pieces of information in the code above. FirstlyForm DigestValue generated by the server can expire. By default this happens in 30 min. SecondlySPWebApplication. FormDigestSettingsProperty can be used to change the form digest settings per web application. Those settings are persisted in the configuration database if you call SPWebApplication. Update (). The information provided in MSDN for the"Enabled"Property is however not completely correct. MSDN says that:Enabled gets or sets a value that determines whether security validation is supported with all form pages.But my SharePoint code examination and code tests showed thatForm DigestWill be always passed ded regardless ofEnabledValue. The value of"False"Means that when the digest expires (by default in 30 min) the user will not be able to submit the form and will get a security validation timeout exception trying to do so. further test however showed that settingEnabledToFalseWill indeed disable the security validation and you will not be getting the"The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."Exception even thatAllowUnsafeUpdatesWill have a valueFalse.

Looking into the code of FormDigest. RegisterDigestUpdateClientScriptBlockIfNeeded () we see that it registers a client script that calltheUpdateFormDigest ()JavaScript function when the form is submitted. This JavaScript function calltheGetUpdatedFormDigest ()Method of_ Vti_bin/sites. asmxWebService and updates the form digest field value on the fly before the form is submitted back to the server. According to the preliminary documentation of the Sites Web Service Protocol released by Microsoft on 4 Apr 2008:TheGetUpdatedFormDigestIs used to request renewal of an expired security validation, also known as a message digest. the purpose of form digest validation is to help prevent security attacks where a user is tricked into posting data unknowingly to a server.To generate the new digest the web service simply creates a new instance ofFormDigestControl and returns itsDigestValueProperty value. So if the function is not called andForm DigestIs not updated a security timeout exception will occur and users will have to refresh a page before they can submitt it.

So the next question is where isForm DigestValidated? This is actually done in the SPWeb. ValidateFormDigest () method:

Public bool ValidateFormDigest ()

{

HttpContext current = HttpContext. Current;

If (current! = Null)

{

If (HttpContext. Current. Items ["FormDigestValidated"] = null)

{

If (! This. Request. ValidateFormDigest (this. Url, null ))

{

Return false;

}

Current. Items ["FormDigestValidated"] = true;

Return true;

}

Return true;

}

Return true;

}

And as the code above shows the validation is done only once per web request and is then cached in the HTTPContext. Furthermore when a newSPWebOrSPSiteObject is created they also create an internal SPRequest object from the HTTPRequest. And within the life time of a single HTTP request to your web part or a web page, ifForm DigestHas been successfully validated once thenAllowUnsafeUpdatesProperty will now have a default value of true for all freshly created objects and the updates will be considered safe by SharePoint which also means you don't have to setAllowUnsafeUpdatesTo do your job.

For some reason sometimes SharePoint doesn' t always callValidateFormDigest ()Method and this is why a workaround with settingAllowUnsafeUpdatesTo true Is used. but a much better and safer solution is if you call this method yourself. the best way to do it is to call the SPUtility. validateFormDigest () method somewhere at the beginning of your POST request code behind.

And finally if you use in SharePoint you custom built ASPX pages which don't inherit from a WebPartPage you can insert a FormDigest control in them which will insertForm DigestFor you automatically and will protect you from cross-site scripting. Just make sure to callValidateFormDigest ()And DON't touchAllowUnsafeUpdates.

I hope that my investigation was more useful than confusing to you. Knowing more about how things work is always a key to building better and more secure applications.

Happy coding.

 

Technorati tags: sharepoint, moss

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.