<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Shaneinsweden</id>
		<title>OWASP - User contributions [en]</title>
		<link rel="self" type="application/atom+xml" href="https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Shaneinsweden"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Shaneinsweden"/>
		<updated>2026-04-21T13:26:35Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Deserialization_Cheat_Sheet&amp;diff=242984</id>
		<title>Deserialization Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Deserialization_Cheat_Sheet&amp;diff=242984"/>
				<updated>2018-08-29T22:42:49Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: Added a .Net section with some .Net tips and .Net references and tools-&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot; style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
This article is focused on providing clear, actionable guidance for safely deserializing untrusted data in your applications.&lt;br /&gt;
&lt;br /&gt;
=What is Deserialization?=&lt;br /&gt;
&lt;br /&gt;
Serialization is the process of turning some object into a data format that can be restored later. People often serialize objects in order to save them to storage, or to send as part of communications. Deserialization is the reverse of that process -- taking data structured from some format, and rebuilding it into an object. Today, the most popular data format for serializing data is JSON. Before that, it was XML.&lt;br /&gt;
&lt;br /&gt;
However, many programming languages offer a native capability for serializing objects. These native formats usually offer more features than JSON or XML, including customizability of the serialization process. Unfortunately, the features of these native deserialization mechanisms can be repurposed for malicious effect when operating on untrusted data. Attacks against deserializers have been found to allow denial-of-service, access control, and remote code execution attacks.&lt;br /&gt;
&lt;br /&gt;
=Guidance on Deserializing Objects Safely=&lt;br /&gt;
The following language-specific guidance attempts to enumerate safe methodologies for deserializing data that can't be trusted. &lt;br /&gt;
&lt;br /&gt;
==PHP==&lt;br /&gt;
===WhiteBox Review===&lt;br /&gt;
Check the use of 'unserialize()' and review how the external parameters are accepted.&lt;br /&gt;
Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.&lt;br /&gt;
Please also refer to to http://php.net/manual/en/function.unserialize.php&lt;br /&gt;
&lt;br /&gt;
==Python==&lt;br /&gt;
===BlackBox Review===&lt;br /&gt;
If the traffic data contains the symbol dot  .  at the end, it's very likely that the data was sent in serialization.&lt;br /&gt;
&lt;br /&gt;
===WhiteBox Review===&lt;br /&gt;
The following API in Python will be vulnerable to serialization attack. Search code for the pattern below.&lt;br /&gt;
&lt;br /&gt;
1. The uses of pickle/c_pickle/_pickle with load/loads&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  import pickle&lt;br /&gt;
  data = &amp;quot;&amp;quot;&amp;quot; cos.system(S'dir')tR. &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
  pickle.loads(data) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. Uses of PyYAML with load&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   import yaml&lt;br /&gt;
   document = &amp;quot;!!python/object/apply:os.system ['ipconfig']&amp;quot;&lt;br /&gt;
   print(yaml.load(document))&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
3. Uses of jsonpickle with encode or store methods&lt;br /&gt;
&lt;br /&gt;
==Java==&lt;br /&gt;
The following techniques are all good for preventing attacks against deserialization against [http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html Java's Serializable format].&lt;br /&gt;
&lt;br /&gt;
Implementation: In your code, override the ObjectInputStream#resolveClass() method to prevent arbitrary classes from being deserialized. This safe behavior can be wrapped in a library like SerialKiller.&lt;br /&gt;
Implementation: Use a safe replacement for the generic readObject() method as seen here. Note that this addresses &amp;quot;billion laughs&amp;quot; type attacks by checking input length and number of objects deserialized.&lt;br /&gt;
&lt;br /&gt;
===WhiteBox Review ===&lt;br /&gt;
Be aware of the following Java API uses for potential serilization vulnerability.&lt;br /&gt;
  1. 'XMLdecoder' with external user defined parameters&lt;br /&gt;
  2. XStream with fromXML method. (xstream version &amp;lt;= v1.46 is vulnerable to the serialization issue.)&lt;br /&gt;
  3. 'ObjectInputSteam' with 'readObject'&lt;br /&gt;
  4. Uses of 'readObject' 'readObjectNodData' 'readResolve' 'readExternal'&lt;br /&gt;
  5. 'ObjectInputStream.readUnshared'&lt;br /&gt;
  6. 'Serializable'&lt;br /&gt;
&lt;br /&gt;
=== BlackBox Review ===&lt;br /&gt;
If the captured traffic data include the following patterns may suggest that the data was sent in Java serialization streams&lt;br /&gt;
* &amp;quot;AC ED 00 05&amp;quot; in Hex&lt;br /&gt;
* &amp;quot;''rO0&amp;quot;  in Base64''&lt;br /&gt;
* Content-type = '&amp;lt;nowiki/&amp;gt;''application/x-java-serialized-object'''&lt;br /&gt;
&lt;br /&gt;
===Prevent Data Leakage and Trusted Field Clobbering===&lt;br /&gt;
If there are data members of an object that should never be controlled by end users during deserialization or exposed to users during serialization, they should be declared as [https://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html#6250 the &amp;lt;code&amp;gt;transient&amp;lt;/code&amp;gt; keyword].&lt;br /&gt;
&lt;br /&gt;
For a class that defined as Serializable, the sensitive information variable should be declared as 'private transient'.&lt;br /&gt;
For example, the class myAccount, the variable 'profile' and 'margin' were declared as transient to avoid to be serialized.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class myAccount implements Serializable&lt;br /&gt;
{&lt;br /&gt;
    private transient double profit; // declared transient&lt;br /&gt;
    &lt;br /&gt;
    private transient double margin; // declared transient&lt;br /&gt;
    ....&lt;br /&gt;
    ....&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Prevent Deserialization of Domain Objects===&lt;br /&gt;
Some of your application objects may be forced to implement Serializable due to their hierarchy. To guarantee that your application objects can't be deserialized, a &amp;lt;code&amp;gt;readObject()&amp;lt;/code&amp;gt; should be declared (with a &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; modifier) which always throws an exception.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;private final void readObject(ObjectInputStream in) throws java.io.IOException {&lt;br /&gt;
   throw new java.io.IOException(&amp;quot;Cannot be deserialized&amp;quot;);&lt;br /&gt;
}&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Harden Your Own java.io.ObjectInputStream===&lt;br /&gt;
The &amp;lt;code&amp;gt;java.io.ObjectInputStream&amp;lt;/code&amp;gt; class is used to deserialize objects. It's possible to harden its behavior by subclassing it. This is the best solution if:&lt;br /&gt;
&lt;br /&gt;
* You can change the code that does the deserialization&lt;br /&gt;
* You know what classes you expect to deserialize&lt;br /&gt;
&lt;br /&gt;
The general idea is to override [http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#resolveClass(java.io.ObjectStreamClass) &amp;lt;code&amp;gt;ObjectInputStream.html#resolveClass()&amp;lt;/code&amp;gt;] in order to restrict which classes are allowed to be deserialized. Because this call happens before a &amp;lt;code&amp;gt;readObject()&amp;lt;/code&amp;gt; is called, you can be sure that no deserialization activity will occur unless the type is one that you wish to allow.  A simple example of this shown here, where the the LookAheadObjectInputStream class is guaranteed not to deserialize any other type besides the Bicycle class:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;public class LookAheadObjectInputStream extends ObjectInputStream {&lt;br /&gt;
&lt;br /&gt;
    public LookAheadObjectInputStream(InputStream inputStream) throws IOException {&lt;br /&gt;
        super(inputStream);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /**&lt;br /&gt;
     * Only deserialize instances of our expected Bicycle class&lt;br /&gt;
     */&lt;br /&gt;
    @Override&lt;br /&gt;
    protected Class&amp;lt;?&amp;gt; resolveClass(ObjectStreamClass desc) throws IOException,&lt;br /&gt;
            ClassNotFoundException {&lt;br /&gt;
        if (!desc.getName().equals(Bicycle.class.getName())) {&lt;br /&gt;
            throw new InvalidClassException(&lt;br /&gt;
                    &amp;quot;Unauthorized deserialization attempt&amp;quot;,&lt;br /&gt;
                    desc.getName());&lt;br /&gt;
        }&lt;br /&gt;
        return super.resolveClass(desc);&lt;br /&gt;
    }&lt;br /&gt;
}&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
More complete implementations of this approach have been proposed by various community members:&lt;br /&gt;
&lt;br /&gt;
* [https://github.com/ikkisoft/SerialKiller NibbleSec] - a library that allows whitelisting and blacklisting of classes that are allowed to be deserialized&lt;br /&gt;
* [https://www.ibm.com/developerworks/library/se-lookahead/ IBM] - the seminal protection, written years before the most devastating exploitation scenarios were envisioned.&lt;br /&gt;
&lt;br /&gt;
===Harden All java.io.ObjectInputStream Usage with an Agent===&lt;br /&gt;
As mentioned above, the &amp;lt;code&amp;gt;java.io.ObjectInputStream&amp;lt;/code&amp;gt; class is used to deserialize objects. It's possible to harden its behavior by subclassing it. However, if you don't own the code or can't wait for a patch, using an agent to weave in hardening to &amp;lt;code&amp;gt;java.io.ObjectInputStream&amp;lt;/code&amp;gt; is the best solution.&lt;br /&gt;
&lt;br /&gt;
Globally changing ObjectInputStream is only safe for blacklisting known malicious types, because it's not possible to know for all applications what the expected classes to be deserialized are. Fortunately, there are very few classes needed in the blacklist to be safe from all the known attack vectors, today. It's inevitable that more &amp;quot;gadget&amp;quot; classes will be discovered that can be abused. However, there is an incredible amount of vulnerable software&lt;br /&gt;
exposed today, in need of a fix. In some cases, &amp;quot;fixing&amp;quot; the vulnerability may involve re-architecting messaging systems and breaking backwards compatibility as developers move towards not accepting serialized objects.&lt;br /&gt;
&lt;br /&gt;
To enable these agents, simply add a new JVM parameter:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;-javaagent:name-of-agent.jar&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Agents taking this approach have been released by various community members:&lt;br /&gt;
* [https://github.com/gocd/invoker-defender Invoker Defender by Go-CD]&lt;br /&gt;
* [https://github.com/Contrast-Security-OSS/contrast-rO0 rO0 by Contrast Security]&lt;br /&gt;
&lt;br /&gt;
A similar, but less scalable approach would be to manually patch and bootstrap your JVM's ObjectInputStream. Guidance on this approach is available [https://github.com/wsargent/paranoid-java-serialization here].&lt;br /&gt;
&lt;br /&gt;
==.Net C#==&lt;br /&gt;
&lt;br /&gt;
=== WhiteBox Review ===&lt;br /&gt;
Search the source code for the following terms&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# TypeNameHandling&lt;br /&gt;
# JavaScriptTypeResolver&lt;br /&gt;
&lt;br /&gt;
Look for any serializers where the type is set by a user controlled variable.&lt;br /&gt;
&lt;br /&gt;
=== BlackBox Review ===&lt;br /&gt;
Search for the following base64 encoded content that starts with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;AAEAAAD/////&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Search for content with the following text:&lt;br /&gt;
# &amp;quot;TypeObject&amp;quot;&lt;br /&gt;
# &amp;quot;$type&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
=== General Precautions ===&lt;br /&gt;
&lt;br /&gt;
Don't allow the datastream to define the type of object that the stream will be deserialized to. You can prevent this by for example using the '''DataContractSerializer''' or '''XmlSerializer''' if at all possible.&lt;br /&gt;
&lt;br /&gt;
Where '''JSON.Net''' is being used make sure the '''TypeNameHandling''' is only set to '''None'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;TypeNameHandling = TypeNameHandling.None&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If '''JavaScriptSerializer''' is to be used do not use it with a '''JavaScriptTypeResolver'''	&lt;br /&gt;
&lt;br /&gt;
If you must deserialise data streams that define their own type, then restrict the types that are allowed to be deserialized. One should be aware that this is still risky as many native .Net types potentially dangerous in themselves. e.g.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;System.IO.FileInfo&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
FileInfo objects that reference files actually on the server can when deserialized, change the properties of those files e.g. to read-only, creating a potential denial of service attack.&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Even if you have limited the types that can be deserialised remember that some types have properties that are risky. '''System.ComponentModel.DataAnnotations.ValidationException''', for example has a property '''Value''' of type '''Object'''. if this type is the type allowed for deserialization then an attacker can set the '''Value''' property to any object type they choose.&lt;br /&gt;
&lt;br /&gt;
Attackers should be prevented from steering the type that will be instantiated. If this is possible then even '''DataContractSerializer''' or '''XmlSerializer''' can be subverted e.g.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
var typename = GetTransactionTypeFromDatabase();  // &amp;lt;-- this is dangerous if the attacker can change the data in the database&lt;br /&gt;
&lt;br /&gt;
var serializer = new DataContractJsonSerializer(Type.GetType(typename)); &lt;br /&gt;
&lt;br /&gt;
var obj = serializer.ReadObject(ms);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Execution can occur within certain .Net types during deserialization. Creating a control such as the one shown below is ineffective.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
var suspectObject = myBinaryFormatter.Deserialize(untrustedData);&lt;br /&gt;
&lt;br /&gt;
if (suspectObject is SomeDangerousObjectType) //Too late! Execution may have already occurred.&lt;br /&gt;
{&lt;br /&gt;
    //generate warnings and dispose of suspectObject&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For '''BinaryFormatter''' and '''JSON.Net''' it is possible to create a safer form of white list control useing a custom '''SerializationBinder'''.&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Try to keep up-to-date on known .Net insecure deserialization gadgets and pay special attention where such types can be created by your deserialization processes. A deserializer can only only instantiate types that it knows about. Try to keep any code that might create potential gagdets separate from any code that Vas internet connectivity. As an example '''System.Windows.Data.ObjectDataProvider''' used in WPF applications is a known gadget that allows arbitrary method invocation. It would be risky to have this a reference to this assembly in a REST service project that deserializes untrusted data.&lt;br /&gt;
&lt;br /&gt;
=== Known .NET RCE Gadgets ===&lt;br /&gt;
System.Configuration.Install.AssemblyInstaller&lt;br /&gt;
* System.Activities.Presentation.WorkflowDesigner&lt;br /&gt;
* System.Windows.ResourceDictionary&lt;br /&gt;
* System.Windows.Data.ObjectDataProvider&lt;br /&gt;
* System.Windows.Forms.BindingSource&lt;br /&gt;
* Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSettingsProvider&lt;br /&gt;
* System.Data.DataViewManager, System.Xml.XmlDocument/XmlDataDocument&lt;br /&gt;
* System.Management.Automation.PSObject&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Language-Agnostic Methods for Deserializing Safely =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Using Alternative Data Formats==&lt;br /&gt;
A great reduction of risk is achieved by avoiding native (de)serialization formats. By switching to a pure data format like JSON or XML, you lessen the chance of custom deserialization logic being repurposed towards malicious ends.&lt;br /&gt;
&lt;br /&gt;
Many applications rely on a [https://en.wikipedia.org/wiki/Data_transfer_object data-transfer object pattern] that involves creating a separate domain of objects for the explicit purpose data transfer. Of course, it's still possible that the application will make security mistakes after a pure data object is parsed.&lt;br /&gt;
&lt;br /&gt;
==Only Deserialize Signed Data==&lt;br /&gt;
If the application knows before deserialization which messages will need to be processed, they could sign them as part of the serialization process. The application could then to choose not to deserialize any message which didn't have an authenticated signature.&lt;br /&gt;
&lt;br /&gt;
= Mitigation Tools/Libraries =&lt;br /&gt;
* Java secure deserialization library https://github.com/ikkisoft/SerialKiller&lt;br /&gt;
&lt;br /&gt;
* SWAT (Serial Whitelist Application Trainer) https://github.com/cschneider4711/SWAT&lt;br /&gt;
* NotSoSerial https://github.com/kantega/notsoserial&lt;br /&gt;
&lt;br /&gt;
= Detection Tools =&lt;br /&gt;
* [https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet Java deserialization cheat sheet aimed at pen testers]&lt;br /&gt;
&lt;br /&gt;
* [https://github.com/frohoff/ysoserial A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.]&lt;br /&gt;
* Java De-serialization toolkits https://github.com/brianwrf/hackUtils&lt;br /&gt;
* Java de-serialization tool https://github.com/frohoff/ysoserial&lt;br /&gt;
* .Net payload generator https://github.com/pwntester/ysoserial.net&lt;br /&gt;
* Java de-serialization detection by DNS  https://github.com/GoSeecure/break-fast-serial&lt;br /&gt;
* Burp Suite extension https://github.com/federicodotta/Java-Deserialization-Scanner/releases&lt;br /&gt;
* Java secure deserialization library https://github.com/ikkisoft/SerialKiller&lt;br /&gt;
* Serianalyzer is a static bytecode analyzer for deserialization https://github.com/mbechler/serianalyzer&lt;br /&gt;
* Payload generator https://github.com/mbechler/marshalsec&lt;br /&gt;
* Android Java Deserialization Vulnerability Tester https://github.com/modzero/modjoda&lt;br /&gt;
* Burp Suite Extension &lt;br /&gt;
** JavaSerialKiller https://github.com/NetSPI/JavaSerialKiller&lt;br /&gt;
** Java Deserialization Scanner https://github.com/federicodotta/Java-Deserialization-Scanner&lt;br /&gt;
** Burp-ysoserial https://github.com/summitt/burp-ysoserial&lt;br /&gt;
** SuperSerial https://github.com/DirectDefense/SuperSerial&lt;br /&gt;
** SuperSerial-Active https://github.com/DirectDefense/SuperSerial-Active&lt;br /&gt;
&lt;br /&gt;
= References = &lt;br /&gt;
* https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet&lt;br /&gt;
* [[Deserialization of untrusted data]]&lt;br /&gt;
* [[Media:GOD16-Deserialization.pdf|Java Deserialization Attacks - German OWASP Day 2016]]&lt;br /&gt;
* [http://www.slideshare.net/frohoff1/appseccali-2015-marshalling-pickles AppSecCali 2015 - Marshalling Pickles]&lt;br /&gt;
* [http://foxglovesecurity.com/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your-application-have-in-common-this-vulnerability/#websphere FoxGlove Security - Vulnerability Announcement]&lt;br /&gt;
* [https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet Java deserialization cheat sheet aimed at pen testers]&lt;br /&gt;
* [https://github.com/frohoff/ysoserial A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.]&lt;br /&gt;
* Java De-serialization toolkits https://github.com/brianwrf/hackUtils&lt;br /&gt;
* Java de-serialization tool https://github.com/frohoff/ysoserial&lt;br /&gt;
* Java de-serialization detection by DNS  https://github.com/GoSeecure/break-fast-serial&lt;br /&gt;
* Burp Suite extension https://github.com/federicodotta/Java-Deserialization-Scanner/releases&lt;br /&gt;
* Java secure deserialization library https://github.com/ikkisoft/SerialKiller&lt;br /&gt;
* Serianalyzer is a static bytecode analyzer for deserialization https://github.com/mbechler/serianalyzer&lt;br /&gt;
* Payload generator https://github.com/mbechler/marshalsec&lt;br /&gt;
* Android Java Deserialization Vulnerability Tester https://github.com/modzero/modjoda&lt;br /&gt;
* Burp Suite Extension &lt;br /&gt;
** JavaSerialKiller https://github.com/NetSPI/JavaSerialKiller&lt;br /&gt;
** Java Deserialization Scanner https://github.com/federicodotta/Java-Deserialization-Scanner&lt;br /&gt;
** Burp-ysoserial https://github.com/summitt/burp-ysoserial&lt;br /&gt;
** SuperSerial https://github.com/DirectDefense/SuperSerial&lt;br /&gt;
** SuperSerial-Active https://github.com/DirectDefense/SuperSerial-Active&lt;br /&gt;
* .Net&lt;br /&gt;
** Alvaro Muñoz: .NET Serialization: Detecting and defending vulnerable endpoints https://www.youtube.com/watch?v=qDoBlLwREYk&lt;br /&gt;
** James Forshaw - Black Hat USA 2012 - Are You My Type? Breaking .net Sandboxes Through Serialization https://www.youtube.com/watch?v=Xfbu-pQ1tIc&lt;br /&gt;
** Jonathan Birch BlueHat v17 || Dangerous Contents - Securing .Net Deserialization https://www.youtube.com/watch?v=oxlD8VWWHE8&lt;br /&gt;
** Alvaro Muñoz &amp;amp; Oleksandr Mirosh - Friday the 13th: Attacking JSON - AppSecUSA 2017 Https://www.youtube.com/watch?v=NqHsaVhlxAQ&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors =&lt;br /&gt;
&lt;br /&gt;
Arshan Dabirsiaghi - arshan [at] contrastsecurity dot org&amp;lt;br /&amp;gt;&lt;br /&gt;
Tony Hsu (Hsiang-Chih)&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;br /&gt;
|}&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224933</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224933"/>
				<updated>2017-01-12T08:21:39Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* ASP.NET MVC Guidance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
* Use [https://msdn.microsoft.com/en-us/library/mt163865.aspx Always Encrypted] where possible for sensitive data (SQL Server 2016 and SQL Azure),&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
* For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use parameterized queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
    var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
    context.Database.ExecuteSqlCommand(&lt;br /&gt;
       sql,&lt;br /&gt;
       new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
       new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO NOT: Store encrypted passwords.&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity that will survive a dictionary attack i.e. longer passwords that use the full character set (numbers, symbols and letters) to increase the entropy. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] or [https://github.com/Dionach/StripHeaders/ Dionach StripHeaders ] to remove Server tags&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before. Register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224932</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224932"/>
				<updated>2017-01-12T08:16:57Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* ASP.NET MVC Guidance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
* Use [https://msdn.microsoft.com/en-us/library/mt163865.aspx Always Encrypted] where possible for sensitive data (SQL Server 2016 and SQL Azure),&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
* For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use parameterized queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
    var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
    context.Database.ExecuteSqlCommand(&lt;br /&gt;
       sql,&lt;br /&gt;
       new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
       new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO NOT: Store encrypted passwords.&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity that will survive a dictionary attack i.e. longer passwords that use the full character set (numbers, symbols and letters) to increase the entropy. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] to remove Server tag&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224852</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224852"/>
				<updated>2017-01-09T22:36:42Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* ASP.NET MVC Guidance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
* Use [https://msdn.microsoft.com/en-us/library/mt163865.aspx Always Encrypted] where possible for sensitive data (SQL Server 2016 and SQL Azure),&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
* For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use parameterized queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
    var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
    context.Database.ExecuteSqlCommand(&lt;br /&gt;
       sql,&lt;br /&gt;
       new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
       new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity: Minimum 8 characters at least 1 upper case, lower case and number. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] to remove Server tag&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224851</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224851"/>
				<updated>2017-01-09T22:35:08Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* General */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
* Use [https://msdn.microsoft.com/en-us/library/mt163865.aspx Always Encrypted] where possible for sensitive data (SQL Server 2016 and SQL Azure),&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
* For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use paramaterized queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
    var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
    context.Database.ExecuteSqlCommand(&lt;br /&gt;
       sql,&lt;br /&gt;
       new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
       new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity: Minimum 8 characters at least 1 upper case, lower case and number. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] to remove Server tag&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224850</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224850"/>
				<updated>2017-01-09T22:32:11Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* .NET Framework Guidance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
* Use [https://msdn.microsoft.com/en-us/library/mt163865.aspx Always Encrypted] where possible for sensitive data (SQL Server 2016 and SQL Azure),&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use paramaterized queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
    var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
    context.Database.ExecuteSqlCommand(&lt;br /&gt;
       sql,&lt;br /&gt;
       new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
       new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity: Minimum 8 characters at least 1 upper case, lower case and number. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] to remove Server tag&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224849</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224849"/>
				<updated>2017-01-09T22:26:01Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* ASP.NET MVC Guidance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use paramaterized queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
    var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
    context.Database.ExecuteSqlCommand(&lt;br /&gt;
       sql,&lt;br /&gt;
       new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
       new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity: Minimum 8 characters at least 1 upper case, lower case and number. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] to remove Server tag&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224848</id>
		<title>.NET Security Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=.NET_Security_Cheat_Sheet&amp;diff=224848"/>
				<updated>2017-01-09T22:23:29Z</updated>
		
		<summary type="html">&lt;p&gt;Shaneinsweden: /* ASP.NET MVC Guidance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
== Introduction  ==&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This page intends to provide quick basic .NET security tips for developers.&lt;br /&gt;
&lt;br /&gt;
===The .NET Framework===&lt;br /&gt;
The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.&lt;br /&gt;
&lt;br /&gt;
===Updating the Framework===&lt;br /&gt;
The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at [http://windowsupdate.microsoft.com/ Windows Update] or from the Windows Update program on a Windows computer.&lt;br /&gt;
&lt;br /&gt;
Individual frameworks can be kept up to date using [http://nuget.codeplex.com/wikipage?title=Getting%20Started&amp;amp;referringTitle=Home NuGet]. As Visual Studio prompts for updates, build it into your lifecycle.&lt;br /&gt;
&lt;br /&gt;
Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.&lt;br /&gt;
&lt;br /&gt;
==.NET Framework Guidance==&lt;br /&gt;
&lt;br /&gt;
The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.&lt;br /&gt;
&lt;br /&gt;
=== Data Access ===&lt;br /&gt;
&lt;br /&gt;
* Use [http://msdn.microsoft.com/en-us/library/ms175528(v=sql.105).aspx Parameterized SQL] commands for all data access, without exception.&lt;br /&gt;
* Do not use [http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx SqlCommand] with a string parameter made up of a [http://msdn.microsoft.com/en-us/library/ms182310.aspx concatenated SQL String].&lt;br /&gt;
* Whitelist allowable values coming from the user. Use enums, [http://msdn.microsoft.com/en-us/library/f02979c7.aspx TryParse] or lookup values to assure that the data coming from the user is as expected.&lt;br /&gt;
** Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. [https://msdn.microsoft.com/en-us/library/system.enum.isdefined Enum.IsDefined] can validate whether the input value is valid within the list of defined constants.&lt;br /&gt;
* Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.&lt;br /&gt;
* Use of the [http://msdn.microsoft.com/en-us/data/ef.aspx Entity Framework] is a very effective [http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx SQL injection] prevention mechanism. Remember that building your own ''ad hoc'' queries in EF is just as susceptible to SQLi as a plain SQL query.&lt;br /&gt;
* When using SQL Server, prefer integrated authentication over SQL authentication.&lt;br /&gt;
&lt;br /&gt;
=== Encryption ===&lt;br /&gt;
* Never, ever write your own encryption.&lt;br /&gt;
* Use the [http://msdn.microsoft.com/en-us/library/ms995355.aspx Windows Data Protection API (DPAPI)] for secure local storage of sensitive data.&lt;br /&gt;
* The standard .NET framework libraries only offer unauthenticated encryption implementations.  Authenticated encryption modes such as AES-GCM based on the underlying newer, more modern Cryptography API: Next Generation are available via the [https://clrsecurity.codeplex.com/ CLRSecurity library].&lt;br /&gt;
* Use a strong hash algorithm. &lt;br /&gt;
** In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is [http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx System.Security.Cryptography.SHA512].&lt;br /&gt;
** In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as [http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx System.Security.Cryptography.Rfc2898DeriveBytes].&lt;br /&gt;
** In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as [https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2] which has several significant advantages over Rfc2898DeriveBytes.&lt;br /&gt;
** When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.&lt;br /&gt;
* Make sure your application or protocol can easily support a future change of cryptographic algorithms.&lt;br /&gt;
* Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
&lt;br /&gt;
* Lock down the config file. &lt;br /&gt;
** Remove all aspects of configuration that are not in use. &lt;br /&gt;
** Encrypt sensitive parts of the web.config using aspnet_regiis -pe&lt;br /&gt;
&lt;br /&gt;
==ASP.NET Web Forms Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.&lt;br /&gt;
&lt;br /&gt;
* Always use [http://support.microsoft.com/kb/324069 HTTPS].&lt;br /&gt;
* Enable [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.requiressl.aspx requireSSL] on cookies and form elements and [http://msdn.microsoft.com/en-us/library/system.web.configuration.httpcookiessection.httponlycookies.aspx HttpOnly] on cookies in the web.config.&lt;br /&gt;
* Implement [http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=VS.71).aspx customErrors].&lt;br /&gt;
* Make sure [http://www.iis.net/configreference/system.webserver/tracing tracing] is turned off.&lt;br /&gt;
* While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the [http://msdn.microsoft.com/en-us/library/ms972969.aspx#securitybarriers_topic2 ViewStateUserKey]:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
 protected override OnInit(EventArgs e) {&lt;br /&gt;
     base.OnInit(e); &lt;br /&gt;
     ViewStateUserKey = Session.SessionID;&lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.&lt;br /&gt;
&lt;br /&gt;
 private const string AntiXsrfTokenKey = &amp;quot;__AntiXsrfToken&amp;quot;;&lt;br /&gt;
 private const string AntiXsrfUserNameKey = &amp;quot;__AntiXsrfUserName&amp;quot;;&lt;br /&gt;
 private string _antiXsrfTokenValue;&lt;br /&gt;
 protected void Page_Init(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     // The code below helps to protect against XSRF attacks&lt;br /&gt;
     var requestCookie = Request.Cookies[AntiXsrfTokenKey];&lt;br /&gt;
     Guid requestCookieGuidValue;&lt;br /&gt;
     if (requestCookie != null &amp;amp;&amp;amp; Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))&lt;br /&gt;
     {&lt;br /&gt;
        // Use the Anti-XSRF token from the cookie&lt;br /&gt;
        _antiXsrfTokenValue = requestCookie.Value;&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Generate a new Anti-XSRF token and save to the cookie&lt;br /&gt;
        _antiXsrfTokenValue = Guid.NewGuid().ToString(&amp;quot;N&amp;quot;);&lt;br /&gt;
        Page.ViewStateUserKey = _antiXsrfTokenValue;&lt;br /&gt;
        var responseCookie = new HttpCookie(AntiXsrfTokenKey)&lt;br /&gt;
        {&lt;br /&gt;
           HttpOnly = true,&lt;br /&gt;
           Value = _antiXsrfTokenValue&lt;br /&gt;
        };&lt;br /&gt;
        if (FormsAuthentication.RequireSSL &amp;amp;&amp;amp; Request.IsSecureConnection)&lt;br /&gt;
        {&lt;br /&gt;
           responseCookie.Secure = true;&lt;br /&gt;
        }&lt;br /&gt;
        Response.Cookies.Set(responseCookie);&lt;br /&gt;
     }&lt;br /&gt;
     Page.PreLoad += master_Page_PreLoad;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 protected void master_Page_PreLoad(object sender, EventArgs e)&lt;br /&gt;
 {&lt;br /&gt;
     if (!IsPostBack)&lt;br /&gt;
     {&lt;br /&gt;
        // Set Anti-XSRF token&lt;br /&gt;
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;&lt;br /&gt;
        ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;&lt;br /&gt;
     }&lt;br /&gt;
     else&lt;br /&gt;
     {&lt;br /&gt;
        // Validate the Anti-XSRF token&lt;br /&gt;
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || &lt;br /&gt;
           (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))&lt;br /&gt;
        {&lt;br /&gt;
           throw new InvalidOperationException(&amp;quot;Validation of Anti-XSRF token failed.&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Consider [http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security HSTS] in IIS.&lt;br /&gt;
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.&lt;br /&gt;
** In the Home pane, double-click HTTP Response Headers.&lt;br /&gt;
** In the HTTP Response Headers pane, click Add... in the Actions pane.&lt;br /&gt;
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.&lt;br /&gt;
* Remove the version header.&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;httpRuntime enableVersionHeader=&amp;quot;false&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
* Also remove the Server header.&lt;br /&gt;
&lt;br /&gt;
    HttpContext.Current.Response.Headers.Remove(&amp;quot;Server&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
=== HTTP validation and encoding ===&lt;br /&gt;
&lt;br /&gt;
* Do not disable [http://www.asp.net/whitepapers/request-validation validateRequest] in the web.config or the page setup. This value enables the XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting.&lt;br /&gt;
* The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.&lt;br /&gt;
* Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.&lt;br /&gt;
* Validate the URI format using [http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx Uri.IsWellFormedUriString].&lt;br /&gt;
&lt;br /&gt;
=== Forms authentication ===&lt;br /&gt;
&lt;br /&gt;
* Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.&lt;br /&gt;
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.&lt;br /&gt;
* Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.&lt;br /&gt;
* If HTTPS is not used, slidingExpiration should be disabled.  Consider disabling slidingExpiration even with HTTPS. &lt;br /&gt;
* Always implement proper access controls.&lt;br /&gt;
** Compare user provided username with User.Identity.Name.&lt;br /&gt;
** Check roles against User.Identity.IsInRole.&lt;br /&gt;
* Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses [http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity ASP.NET Identity] instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP [[Password Storage Cheat Sheet]] for more information.&lt;br /&gt;
* Explicitly authorize resource requests.&lt;br /&gt;
* Leverage role based authorization using User.Identity.IsInRole.&lt;br /&gt;
&lt;br /&gt;
==ASP.NET MVC Guidance==&lt;br /&gt;
&lt;br /&gt;
ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.&lt;br /&gt;
&lt;br /&gt;
* A1 SQL Injection&lt;br /&gt;
&lt;br /&gt;
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.&lt;br /&gt;
&lt;br /&gt;
DO: Use paramterised queries where a direct sql query must be used. &lt;br /&gt;
&lt;br /&gt;
e.g. In entity frameworks:&lt;br /&gt;
&lt;br /&gt;
var sql = @&amp;quot;Update [User] SET FirstName = @FirstName WHERE Id = @Id&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
context.Database.ExecuteSqlCommand(&lt;br /&gt;
    sql,&lt;br /&gt;
    new SqlParameter(&amp;quot;@FirstName&amp;quot;, firstname),&lt;br /&gt;
    new SqlParameter(&amp;quot;@Id&amp;quot;, id));&lt;br /&gt;
&lt;br /&gt;
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.&lt;br /&gt;
&lt;br /&gt;
e.g&lt;br /&gt;
    string strQry = &amp;quot;SELECT * FROM Users WHERE UserName='&amp;quot; + txtUser.Text + &amp;quot;' AND Password='&amp;quot; + txtPassword.Text + &amp;quot;'&amp;quot;;&lt;br /&gt;
    EXEC strQry // SQL Injection vulnerability!&lt;br /&gt;
&lt;br /&gt;
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account&lt;br /&gt;
&lt;br /&gt;
* A2 Weak Account management&lt;br /&gt;
&lt;br /&gt;
Ensure cookies are sent via httpOnly:&lt;br /&gt;
&lt;br /&gt;
     CookieHttpOnly = true,&lt;br /&gt;
&lt;br /&gt;
Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:&lt;br /&gt;
&lt;br /&gt;
     ExpireTimeSpan = TimeSpan.FromMinutes(60),&lt;br /&gt;
     SlidingExpiration = false&lt;br /&gt;
&lt;br /&gt;
See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/App_Start/Startup.Auth.cs here] for full startup code snippet&lt;br /&gt;
&lt;br /&gt;
Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Require all custom cookies to travel via SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;httpCookies requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;authentication&amp;gt;&lt;br /&gt;
      &amp;lt;forms requireSSL=&amp;quot;true&amp;quot; xdt:Transform=&amp;quot;SetAttributes(requireSSL)&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;!-- SECURE: Authentication cookie should only be passed over SSL --&amp;gt;&lt;br /&gt;
    &amp;lt;/authentication&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.&lt;br /&gt;
&lt;br /&gt;
    [HttpPost]&lt;br /&gt;
    [AllowAnonymous]&lt;br /&gt;
    [ValidateAntiForgeryToken]&lt;br /&gt;
    '''[AllowXRequestsEveryXSecondsAttribute(Name = &amp;quot;LogOn&amp;quot;, Message = &amp;quot;You have performed this action more than {x} times in the last {n} seconds.&amp;quot;, Requests = 3, Seconds = 60)]'''&lt;br /&gt;
    public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Find [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/ThrottleAttribute.cs here] the code to prevent throttling&lt;br /&gt;
&lt;br /&gt;
DO NOT: Roll your own authentication or session management, use the one provided by .Net&lt;br /&gt;
&lt;br /&gt;
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* A3 XSS&lt;br /&gt;
&lt;br /&gt;
DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists&lt;br /&gt;
&lt;br /&gt;
You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:&lt;br /&gt;
&lt;br /&gt;
    Install-Package AntiXSS&lt;br /&gt;
&lt;br /&gt;
then set in config:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;system.web&amp;gt;&lt;br /&gt;
        &amp;lt;!-- SECURE: Don't disclose version header in each IIS response, encode ALL output including CSS, JavaScript etc, reduce max request length as mitigation against DOS --&amp;gt;&lt;br /&gt;
        &amp;lt;httpRuntime targetFramework=&amp;quot;4.5&amp;quot; enableVersionHeader=&amp;quot;false&amp;quot; encoderType=&amp;quot;Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary&amp;quot; maxRequestLength=&amp;quot;4096&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.&lt;br /&gt;
&lt;br /&gt;
* A4 Insecure Direct object references&lt;br /&gt;
&lt;br /&gt;
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there&lt;br /&gt;
&lt;br /&gt;
    // Insecure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            return View(&amp;quot;Details&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
    // Secure&lt;br /&gt;
    public ActionResult Edit(int id)&lt;br /&gt;
        {&lt;br /&gt;
            var user = _context.Users.FirstOrDefault(e =&amp;gt; e.Id == id);&lt;br /&gt;
            // Establish user has right to edit the details&lt;br /&gt;
            if (user.Id != _userIdentity.GetUserId())&lt;br /&gt;
            {&lt;br /&gt;
                HandleErrorInfo error = new HandleErrorInfo(new Exception(&amp;quot;INFO: You do not have permission to edit these details&amp;quot;));&lt;br /&gt;
                return View(&amp;quot;Error&amp;quot;, error);&lt;br /&gt;
            }&lt;br /&gt;
            return View(&amp;quot;Edit&amp;quot;, new UserViewModel(user);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
* A5 Security Misconfiguration&lt;br /&gt;
&lt;br /&gt;
Ensure debug and trace are off in production. This can be enforced using web.config transforms:&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure debug information is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;compilation xdt:Transform=&amp;quot;RemoveAttributes(debug)&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;!-- SECURE: Ensure trace is turned off in production --&amp;gt;&lt;br /&gt;
    &amp;lt;trace enabled=&amp;quot;false&amp;quot; xdt:Transform=&amp;quot;Replace&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DO NOT: Use default passwords&lt;br /&gt;
&lt;br /&gt;
* A6 Sensitive data exposure&lt;br /&gt;
&lt;br /&gt;
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations.&lt;br /&gt;
&lt;br /&gt;
DO: Enforce passwords with a minimum complexity: Minimum 8 characters at least 1 upper case, lower case and number. &lt;br /&gt;
&lt;br /&gt;
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.&lt;br /&gt;
&lt;br /&gt;
DO: Use TLS 1.2 for your entire site. Get a free certificate from [https://www.startssl.com/ StartSSL.com] or [https://letsencrypt.org/ LetsEncrypt.org].&lt;br /&gt;
DO NOT: Allow SSL, this is now obsolete&lt;br /&gt;
DO: Have a strong TLS policy (see [http://www.ssllabs.com/projects/best-practises/ SSL Best Practises]), use TLS 1.2 wherever possible. Then check the configuration using [https://www.ssllabs.com/ssltest/ SSL Test]&lt;br /&gt;
&lt;br /&gt;
DO: Ensure headers are not disclosing information about your application. See [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs HttpHeaders.cs] to remove Server tag&lt;br /&gt;
&lt;br /&gt;
* A7 Missing function level access control&lt;br /&gt;
&lt;br /&gt;
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize(Roles = &amp;quot;Admin&amp;quot;)]&lt;br /&gt;
     [HttpGet]&lt;br /&gt;
     public ActionResult Index(int page = 1)&lt;br /&gt;
&lt;br /&gt;
or better yet, at controller level:&lt;br /&gt;
&lt;br /&gt;
     [Authorize]&lt;br /&gt;
     public class UserController&lt;br /&gt;
&lt;br /&gt;
You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)&lt;br /&gt;
&lt;br /&gt;
* A8 Cross site request forgery&lt;br /&gt;
&lt;br /&gt;
DO: Send the anti-forgery token with every Post/Put request:&lt;br /&gt;
&lt;br /&gt;
    using (Html.BeginForm(&amp;quot;LogOff&amp;quot;, &amp;quot;Account&amp;quot;, FormMethod.Post, new { id = &amp;quot;logoutForm&amp;quot;, @class = &amp;quot;pull-right&amp;quot; }))&lt;br /&gt;
        {&lt;br /&gt;
        @Html.AntiForgeryToken()&lt;br /&gt;
        &amp;amp;lt;ul class=&amp;quot;nav nav-pills&amp;quot;&amp;amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;Logged on as @User.Identity.Name&amp;lt;/li&amp;gt;&lt;br /&gt;
            &amp;amp;lt;li role=&amp;quot;presentation&amp;quot;&amp;amp;gt;&amp;amp;lt;a href=&amp;quot;javascript:document.getElementById('logoutForm').submit()&amp;quot;&amp;amp;gt;Log off&amp;amp;lt;/a&amp;amp;gt;&amp;amp;lt;/li&amp;amp;gt;&lt;br /&gt;
        &amp;amp;lt;/ul&amp;amp;gt;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Then validate it at the method or preferably the controller level:&lt;br /&gt;
&lt;br /&gt;
        [HttpPost]&lt;br /&gt;
        '''[ValidateAntiForgeryToken]'''&lt;br /&gt;
        public ActionResult LogOff()&lt;br /&gt;
&lt;br /&gt;
NB: You will need to attach the anti-forgery token to Ajax requests.&lt;br /&gt;
&lt;br /&gt;
* A9 Using components with known vulnerabilities&lt;br /&gt;
&lt;br /&gt;
DO: Keep the .Net framework updated with the latest patches&lt;br /&gt;
DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [[https://www.owasp.org/index.php/OWASP_Dependency_Check OWASP Dependency Checker]]&lt;br /&gt;
&lt;br /&gt;
* A10 Unvalidated redirects and forwards&lt;br /&gt;
&lt;br /&gt;
A protection against this was introduced in Mvc 3 template. Here is the code:&lt;br /&gt;
&lt;br /&gt;
        public async Task&amp;lt;ActionResult&amp;gt; LogOn(LogOnViewModel model, string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (ModelState.IsValid)&lt;br /&gt;
            {&lt;br /&gt;
                var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);&lt;br /&gt;
                if (logonResult.Success)&lt;br /&gt;
                {&lt;br /&gt;
                    await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);                              &lt;br /&gt;
                    return RedirectToLocal(returnUrl);&lt;br /&gt;
        ....&lt;br /&gt;
&lt;br /&gt;
        private ActionResult RedirectToLocal(string returnUrl)&lt;br /&gt;
        {&lt;br /&gt;
            if (Url.IsLocalUrl(returnUrl))&lt;br /&gt;
            {&lt;br /&gt;
                return Redirect(returnUrl);&lt;br /&gt;
            }&lt;br /&gt;
            else&lt;br /&gt;
            {&lt;br /&gt;
                return RedirectToAction(&amp;quot;Landing&amp;quot;, &amp;quot;Account&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
Other advice:&lt;br /&gt;
&lt;br /&gt;
* Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security headers. Full details [https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/HttpHeaders.cs here]&lt;br /&gt;
* Protect against a man in the middle attack for a user who has never been to your site before register for [https://hstspreload.org/ HSTS preload]&lt;br /&gt;
* Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
&lt;br /&gt;
For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to [http://github.com/johnstaveley/SecurityEssentials/ Security Essentials Baseline project]&lt;br /&gt;
&lt;br /&gt;
==XAML Guidance==&lt;br /&gt;
&lt;br /&gt;
* Work within the constraints of Internet Zone security for your application.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Windows Forms Guidance== &lt;br /&gt;
&lt;br /&gt;
* Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.&lt;br /&gt;
* Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.&lt;br /&gt;
&lt;br /&gt;
==WCF Guidance==&lt;br /&gt;
&lt;br /&gt;
* Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.&lt;br /&gt;
* Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.&lt;br /&gt;
* Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.&lt;br /&gt;
* Test your WCF implementation with a fuzzer like the Zed Attack Proxy.&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Bill Sempf - bill.sempf(at)owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Troy Hunt - troyhunt(at)hotmail.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long - jeremy.long(at)owasp.org&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]][[Category:OWASP .NET Project]]&lt;/div&gt;</summary>
		<author><name>Shaneinsweden</name></author>	</entry>

	</feed>