From 7993ad196ba296190d5760b0740174ad0a7b9844 Mon Sep 17 00:00:00 2001 From: Paul Ming Date: Tue, 14 Jul 2020 17:05:30 +0000 Subject: [PATCH] Initial rules for DataSet / DataTable deserialization --- .../Microsoft.CodeAnalysis.FxCopAnalyzers.md | 143 +++--- ...icrosoft.CodeAnalysis.FxCopAnalyzers.sarif | 169 ++++++- ...ft.CodeAnalysis.VersionCheckAnalyzer.sarif | 2 +- .../Microsoft.CodeQuality.Analyzers.md | 4 +- .../Microsoft.CodeQuality.Analyzers.sarif | 14 +- .../Microsoft.NetCore.Analyzers.md | 129 ++--- .../Microsoft.NetCore.Analyzers.sarif | 149 +++++- .../Microsoft.NetFramework.Analyzers.sarif | 6 +- .../Core/AnalyzerReleases.Unshipped.md | 10 + .../MicrosoftNetCoreAnalyzersResources.resx | 40 +- .../Security/DataSetAnalyzer.cs | 208 --------- ...ormatterSerializableObjectGraphAnalyzer.cs | 133 ++++++ ...aTableInSerializableObjectGraphAnalyzer.cs | 302 ++++++++++++ ...aSetDataTableInSerializableTypeAnalyzer.cs | 159 +++++++ ...bleInWebSerializableObjectGraphAnalyzer.cs | 127 +++++ .../DoNotDisableHttpClientCRLCheck.cs | 1 - .../Security/DoNotInstallRootCert.cs | 1 - ...DoNotUseCreateEncryptorWithNonDefaultIV.cs | 1 - .../Security/DoNotUseDataSetReadXml.cs | 36 ++ ...ascriptSerializerWithSimpleTypeResolver.cs | 1 - ...nsecureDeserializerJsonNetWithoutBinder.cs | 1 - ...seInsecureDeserializerWithoutBinderBase.cs | 1 - .../DoNotUseInsecureSettingsForJsonNet.cs | 1 - ...NotUseWeakKDFInsufficientIterationCount.cs | 1 - .../InsecureDeserializationTypeDecider.cs | 440 ++++++++++++++++++ .../Helpers/InsecureObjectGraphResult.cs | 98 ++++ .../Security/Helpers/ObjectGraphOptions.cs | 152 ++++++ .../Security/Helpers/SecurityHelpers.cs | 27 ++ .../Helpers/XmlSerializationAttributeTypes.cs | 108 +++++ .../Security/SetHttpOnlyForHttpCookie.cs | 1 - .../Security/UseSecureCookiesASPNetCore.cs | 1 - .../MicrosoftNetCoreAnalyzersResources.cs.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.de.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.es.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.fr.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.it.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.ja.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.ko.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.pl.xlf | 64 ++- ...crosoftNetCoreAnalyzersResources.pt-BR.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.ru.xlf | 64 ++- .../MicrosoftNetCoreAnalyzersResources.tr.xlf | 64 ++- ...osoftNetCoreAnalyzersResources.zh-Hans.xlf | 64 ++- ...osoftNetCoreAnalyzersResources.zh-Hant.xlf | 64 ++- .../Microsoft.CodeAnalysis.NetAnalyzers.md | 140 +++--- .../Microsoft.CodeAnalysis.NetAnalyzers.sarif | 134 +++++- ...etDataTableInIFormatterObjectGraphTests.cs | 265 +++++++++++ .../DataSetDataTableInObjectGraphTests.cs | 424 +++++++++++++++++ ...DataSetDataTableInSerializableTypeTests.cs | 406 ++++++++++++++++ ...aTableInWebSerializableObjectGraphTests.cs | 132 ++++++ .../Security/DoNotUseDataSetReadXmlTests.cs | 111 +++++ ...rConstructedWithNoSecureResolutionTests.cs | 25 + ...eAnalysis.PerformanceSensitiveAnalyzers.md | 2 +- ...alysis.PerformanceSensitiveAnalyzers.sarif | 6 +- ...soft.CodeAnalysis.PublicApiAnalyzers.sarif | 4 +- .../Roslyn.Diagnostics.Analyzers.sarif | 14 +- .../CSharpCodeFixVerifier`2+Test.cs | 13 + .../CSharpSecurityCodeFixVerifier`2+Test.cs | 13 + .../PropertySetAnalysisTests.cs | 175 +------ .../Compiler/Analyzer.Utilities.projitems | 3 + .../Extensions/IOperationExtensions.cs | 32 ++ .../Compiler/Extensions/ISymbolExtensions.cs | 66 +++ .../Compiler/PooledObjects/PooledHashSet.cs | 1 - .../Compiler/PooledObjects/PooledSortedSet.cs | 63 +++ .../Compiler/SymbolByDisplayStringComparer.cs | 53 +++ .../Compiler/SymbolDisplayNameCache.cs | 51 ++ .../Compiler/SymbolDisplayStringCache.cs | 56 +++ .../TypeSymbolByMetadataNameComparer.cs | 38 ++ src/Utilities/Compiler/WellKnownTypeNames.cs | 22 + .../FlowAnalysis.Utilities.projitems | 2 - .../PropertySetAnalysis/ConstructorMapper.cs | 21 +- .../PropertySetAnalysis/InvocationMapper.cs | 110 ----- .../InvocationMapperCollection.cs | 93 ---- .../PropertySetAnalysis/PropertyMapper.cs | 4 +- .../PropertyMapperCollection.cs | 11 - .../PropertySetAbstractValue.cs | 10 +- ...sis.PropertySetDataFlowOperationVisitor.cs | 86 +--- .../PropertySetAnalysis.cs | 13 +- .../PropertySetAnalysisContext.cs | 11 - .../PropertySetCallbacks.cs | 11 - 80 files changed, 4752 insertions(+), 1167 deletions(-) delete mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetAnalyzer.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableObjectGraphAnalyzer.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeAnalyzer.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphAnalyzer.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXml.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureDeserializationTypeDecider.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureObjectGraphResult.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/ObjectGraphOptions.cs create mode 100644 src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/XmlSerializationAttributeTypes.cs create mode 100644 src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterObjectGraphTests.cs create mode 100644 src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInObjectGraphTests.cs create mode 100644 src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeTests.cs create mode 100644 src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphTests.cs create mode 100644 src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXmlTests.cs create mode 100644 src/Utilities/Compiler/PooledObjects/PooledSortedSet.cs create mode 100644 src/Utilities/Compiler/SymbolByDisplayStringComparer.cs create mode 100644 src/Utilities/Compiler/SymbolDisplayNameCache.cs create mode 100644 src/Utilities/Compiler/SymbolDisplayStringCache.cs create mode 100644 src/Utilities/Compiler/TypeSymbolByMetadataNameComparer.cs delete mode 100644 src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapper.cs delete mode 100644 src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapperCollection.cs diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index 9ba958c75d..41a6ac1f3d 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -5,7 +5,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 2 | [CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001) | Types that own disposable fields should be disposable | Design | True | Warning | True | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. | 3 | [CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003) | Use generic event handler instances | Design | False | Warning | False | A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. | 4 | [CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008) | Enums should have zero value | Design | False | Warning | True | The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. | -5 | [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Collections should implement generic interface | Design | True | Warning | False | To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types. | +5 | [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Generic interface should also be implemented | Design | True | Warning | False | To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. | 6 | [CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012) | Abstract types should not have constructors | Design | False | Warning | True | Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. | 7 | [CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014) | Mark assemblies with CLSCompliant | Design | False | Warning | False | The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. | 8 | [CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016) | Mark assemblies with assembly version | Design | True | Warning | False | The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. | @@ -81,7 +81,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 78 | [CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819) | Properties should not return arrays | Performance | True | Warning | False | Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. | 79 | [CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820) | Test for empty strings using string length | Performance | True | Warning | True | Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. | 80 | [CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821) | Remove empty Finalizers | Performance | True | Warning | True | Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. | -81 | [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Warning | True | Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | +81 | [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Warning | True | Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | 82 | [CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823) | Avoid unused private fields | Performance | True | Warning | True | Private fields were detected that do not appear to be accessed in the assembly. | 83 | [CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824) | Mark assemblies with NeutralResourcesLanguageAttribute | Performance | True | Warning | False | The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. | 84 | [CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825) | Avoid zero-length array allocations. | Performance | True | Warning | True | Avoid unnecessary zero-length array allocations. Use {0} instead. | @@ -140,69 +140,76 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 137 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | 138 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | 139 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -140 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -141 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -142 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -143 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -144 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -145 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -146 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -147 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -148 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -149 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -150 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -151 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -152 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | -153 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Warning | False | Using XmlTextReader.Load(), creating an insecure XmlReaderSettings instance when invoking XmlReader.Create(), setting the InnerXml property of the XmlDocument and enabling DTD processing using XmlUrlResolver insecurely can lead to information disclosure. Replace it with a call to the Load() method overload that takes an XmlReader instance, use XmlReader.Create() to accept XmlReaderSettings arguments or consider explicitly setting secure values. The DataViewSettingCollectionString property of DataViewManager should always be assigned from a trusted source, the DtdProcessing property should be set to false, and the XmlResolver property should be changed to XmlSecureResolver or null.  | -154 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Warning | False | Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed if the input is known to be from a trusted source and external resource resolution from locations that are not known in advance must be supported. | -155 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Warning | False | Enabling DTD processing on all instances derived from XmlTextReader or  XmlDocument and using XmlUrlResolver for resolving external XML entities may lead to information disclosure. Ensure to set the XmlResolver property to null, create an instance of XmlSecureResolver when processing untrusted input, or use XmlReader.Create method with a secure XmlReaderSettings argument. Unless you need to enable it, ensure the DtdProcessing property is set to false.  | -156 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Warning | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | -157 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | -158 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | -159 | [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Do Not Use Unsafe Cipher Modes | Security | False | Warning | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -160 | [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | -161 | [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | -162 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | -163 | [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Do Not Refer Self In Serializable Class | Security | False | Warning | False | This can allow an attacker to DOS or exhaust the memory of the process. | -164 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | -165 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | -166 | [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | -167 | [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -168 | [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | -169 | [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | -170 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -171 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -172 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -173 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -174 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | -175 | [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -176 | [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | -177 | [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -178 | [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | -179 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | -180 | [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | -181 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -182 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -183 | [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -184 | [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -185 | [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | -186 | [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -187 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | -188 | [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -189 | [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -190 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -191 | [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | -192 | [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | -193 | [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -194 | [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -195 | [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | -196 | [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | -197 | [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -198 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -199 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -200 | [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -201 | [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -202 | [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -203 | [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -204 | [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | -205 | CA9999 | Analyzer version mismatch | Reliability | True | Warning | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | +140 | [CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350) | Do not use insecure deserialization with DataTable.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | +141 | [CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351) | Do not use insecure deserialization with DataSet.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | +142 | [CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352) | Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +143 | [CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353) | Unsafe DataSet or DataTable in serializable type | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +144 | [CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354) | Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +145 | [CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355) | Unsafe DataSet or DataTable type found in deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +146 | [CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356) | Unsafe DataSet or DataTable type in web deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +147 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +148 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +149 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +150 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | +151 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +152 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +153 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +154 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +155 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +156 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +157 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +158 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +159 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | +160 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Warning | False | Using XmlTextReader.Load(), creating an insecure XmlReaderSettings instance when invoking XmlReader.Create(), setting the InnerXml property of the XmlDocument and enabling DTD processing using XmlUrlResolver insecurely can lead to information disclosure. Replace it with a call to the Load() method overload that takes an XmlReader instance, use XmlReader.Create() to accept XmlReaderSettings arguments or consider explicitly setting secure values. The DataViewSettingCollectionString property of DataViewManager should always be assigned from a trusted source, the DtdProcessing property should be set to false, and the XmlResolver property should be changed to XmlSecureResolver or null.  | +161 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Warning | False | Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed if the input is known to be from a trusted source and external resource resolution from locations that are not known in advance must be supported. | +162 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Warning | False | Enabling DTD processing on all instances derived from XmlTextReader or  XmlDocument and using XmlUrlResolver for resolving external XML entities may lead to information disclosure. Ensure to set the XmlResolver property to null, create an instance of XmlSecureResolver when processing untrusted input, or use XmlReader.Create method with a secure XmlReaderSettings argument. Unless you need to enable it, ensure the DtdProcessing property is set to false.  | +163 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Warning | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | +164 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | +165 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | +166 | [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Review cipher mode usage with cryptography experts | Security | False | Warning | False | These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). | +167 | [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | +168 | [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | +169 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | +170 | [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Potential reference cycle in deserialized object graph | Security | False | Warning | False | Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. | +171 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | +172 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | +173 | [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | +174 | [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +175 | [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | +176 | [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | +177 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +178 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +179 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +180 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +181 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | +182 | [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +183 | [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | +184 | [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | +185 | [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | +186 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | +187 | [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | +188 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +189 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +190 | [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | +191 | [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | +192 | [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | +193 | [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | +194 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | +195 | [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +196 | [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +197 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +198 | [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | +199 | [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | +200 | [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +201 | [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +202 | [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | +203 | [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | +204 | [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +205 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +206 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +207 | [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +208 | [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +209 | [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | +210 | [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | +211 | [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | +212 | CA9999 | Analyzer version mismatch | Reliability | True | Warning | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif index 2a19b8f2b1..dabaec2179 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.VersionCheckAnalyzer", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -29,7 +29,7 @@ { "tool": { "name": "Microsoft.CodeQuality.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -76,8 +76,8 @@ }, "CA1010": { "id": "CA1010", - "shortDescription": "Collections should implement generic interface", - "fullDescription": "To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types.", + "shortDescription": "Generic interface should also be implemented", + "fullDescription": "To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1010", "properties": { @@ -1234,7 +1234,7 @@ "CA1822": { "id": "CA1822", "shortDescription": "Mark members as static", - "fullDescription": "Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code.", + "fullDescription": "Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1822", "properties": { @@ -1530,7 +1530,7 @@ { "tool": { "name": "Microsoft.CodeQuality.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -1727,7 +1727,7 @@ { "tool": { "name": "Microsoft.CodeQuality.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -1962,7 +1962,7 @@ { "tool": { "name": "Microsoft.NetCore.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -2819,6 +2819,139 @@ ] } }, + "CA2350": { + "id": "CA2350", + "shortDescription": "Do not use insecure deserialization with DataTable.ReadXml()", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2350", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataTableReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2351": { + "id": "CA2351", + "shortDescription": "Do not use insecure deserialization with DataSet.ReadXml()", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2351", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2352": { + "id": "CA2352", + "shortDescription": "Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2352", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2353": { + "id": "CA2353", + "shortDescription": "Unsafe DataSet or DataTable in serializable type", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2353", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2354": { + "id": "CA2354", + "shortDescription": "Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2354", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2355": { + "id": "CA2355", + "shortDescription": "Unsafe DataSet or DataTable type found in deserializable object graph", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2355", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2356": { + "id": "CA2356", + "shortDescription": "Unsafe DataSet or DataTable type in web deserializable object graph", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2356", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInWebSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA3001": { "id": "CA3001", "shortDescription": "Review code for SQL injection vulnerabilities", @@ -3118,8 +3251,8 @@ }, "CA5358": { "id": "CA5358", - "shortDescription": "Do Not Use Unsafe Cipher Modes", - "fullDescription": "These modes are vulnerable to attacks. Use only approved modes (CBC, CTS).", + "shortDescription": "Review cipher mode usage with cryptography experts", + "fullDescription": "These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS).", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5358", "properties": { @@ -3195,14 +3328,14 @@ }, "CA5362": { "id": "CA5362", - "shortDescription": "Do Not Refer Self In Serializable Class", - "fullDescription": "This can allow an attacker to DOS or exhaust the memory of the process.", + "shortDescription": "Potential reference cycle in deserialized object graph", + "fullDescription": "Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5362", "properties": { "category": "Security", "isEnabledByDefault": false, - "typeName": "DoNotReferSelfInSerializableClass", + "typeName": "PotentialReferenceCycleInDeserializedObjectGraph", "languages": [ "C#", "Visual Basic" @@ -4013,7 +4146,7 @@ { "tool": { "name": "Microsoft.NetCore.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -4152,7 +4285,7 @@ { "tool": { "name": "Microsoft.NetCore.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -4291,7 +4424,7 @@ { "tool": { "name": "Microsoft.NetFramework.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -4377,7 +4510,7 @@ { "tool": { "name": "Microsoft.NetFramework.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -4422,7 +4555,7 @@ { "tool": { "name": "Microsoft.NetFramework.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.sarif b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.sarif index 452826601c..c747453a7b 100644 --- a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.sarif +++ b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.VersionCheckAnalyzer", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md index a2d1050553..60685d6c0c 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md +++ b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md @@ -5,7 +5,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 2 | [CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001) | Types that own disposable fields should be disposable | Design | True | Warning | True | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. | 3 | [CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003) | Use generic event handler instances | Design | False | Warning | False | A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. | 4 | [CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008) | Enums should have zero value | Design | False | Warning | True | The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. | -5 | [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Collections should implement generic interface | Design | True | Warning | False | To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types. | +5 | [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Generic interface should also be implemented | Design | True | Warning | False | To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. | 6 | [CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012) | Abstract types should not have constructors | Design | False | Warning | True | Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. | 7 | [CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014) | Mark assemblies with CLSCompliant | Design | False | Warning | False | The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. | 8 | [CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016) | Mark assemblies with assembly version | Design | True | Warning | False | The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. | @@ -69,7 +69,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 66 | [CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815) | Override equals and operator equals on value types | Performance | True | Warning | True | For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. | 67 | [CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819) | Properties should not return arrays | Performance | True | Warning | False | Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. | 68 | [CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821) | Remove empty Finalizers | Performance | True | Warning | True | Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. | -69 | [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Warning | True | Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | +69 | [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Warning | True | Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | 70 | [CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823) | Avoid unused private fields | Performance | True | Warning | True | Private fields were detected that do not appear to be accessed in the assembly. | 71 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007) | Consider calling ConfigureAwait on the awaited task | Reliability | True | Warning | True | When an asynchronous method awaits a Task directly, continuation occurs in the same thread that created the task. Consider calling Task.ConfigureAwait(Boolean) to signal your intention for continuation. Call ConfigureAwait(false) on the task to schedule continuations to the thread pool, thereby avoiding a deadlock on the UI thread. Passing false is a good option for app-independent libraries. Calling ConfigureAwait(true) on the task has the same behavior as not explicitly calling ConfigureAwait. By explicitly calling this method, you're letting readers know you intentionally want to perform the continuation on the original synchronization context. | 72 | [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119) | Seal methods that satisfy private interfaces | Security | True | Warning | True | An inheritable public type provides an overridable method implementation of an internal (Friend in Visual Basic) interface. To fix a violation of this rule, prevent the method from being overridden outside the assembly. | diff --git a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif index df8dd861c4..3a3010c8a6 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif +++ b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Humanizer", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -14,7 +14,7 @@ { "tool": { "name": "Microsoft.CodeQuality.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -61,8 +61,8 @@ }, "CA1010": { "id": "CA1010", - "shortDescription": "Collections should implement generic interface", - "fullDescription": "To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types.", + "shortDescription": "Generic interface should also be implemented", + "fullDescription": "To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1010", "properties": { @@ -1219,7 +1219,7 @@ "CA1822": { "id": "CA1822", "shortDescription": "Mark members as static", - "fullDescription": "Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code.", + "fullDescription": "Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1822", "properties": { @@ -1515,7 +1515,7 @@ { "tool": { "name": "Microsoft.CodeQuality.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -1712,7 +1712,7 @@ { "tool": { "name": "Microsoft.CodeQuality.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index c16dc19198..87ece2670f 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -51,64 +51,71 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 48 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | 49 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | 50 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -51 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -52 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -53 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -54 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -55 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -56 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -57 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -58 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -59 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -60 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -61 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -62 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -63 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | -64 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | -65 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | -66 | [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Do Not Use Unsafe Cipher Modes | Security | False | Warning | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -67 | [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | -68 | [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | -69 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | -70 | [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Do Not Refer Self In Serializable Class | Security | False | Warning | False | This can allow an attacker to DOS or exhaust the memory of the process. | -71 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | -72 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | -73 | [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | -74 | [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -75 | [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | -76 | [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | -77 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -78 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -79 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -80 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -81 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | -82 | [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -83 | [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | -84 | [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -85 | [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | -86 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | -87 | [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | -88 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -89 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -90 | [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -91 | [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -92 | [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | -93 | [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -94 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | -95 | [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -96 | [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -97 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -98 | [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | -99 | [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | -100 | [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -101 | [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -102 | [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | -103 | [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | -104 | [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -105 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -106 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -107 | [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -108 | [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -109 | [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -110 | [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -111 | [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | +51 | [CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350) | Do not use insecure deserialization with DataTable.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | +52 | [CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351) | Do not use insecure deserialization with DataSet.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | +53 | [CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352) | Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +54 | [CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353) | Unsafe DataSet or DataTable in serializable type | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +55 | [CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354) | Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +56 | [CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355) | Unsafe DataSet or DataTable type found in deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +57 | [CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356) | Unsafe DataSet or DataTable type in web deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +58 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +59 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +60 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +61 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | +62 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +63 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +64 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +65 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +66 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +67 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +68 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +69 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +70 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | +71 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | +72 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | +73 | [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Review cipher mode usage with cryptography experts | Security | False | Warning | False | These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). | +74 | [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | +75 | [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | +76 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | +77 | [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Potential reference cycle in deserialized object graph | Security | False | Warning | False | Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. | +78 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | +79 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | +80 | [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | +81 | [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +82 | [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | +83 | [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | +84 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +85 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +86 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +87 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +88 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | +89 | [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +90 | [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | +91 | [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | +92 | [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | +93 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | +94 | [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | +95 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +96 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +97 | [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | +98 | [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | +99 | [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | +100 | [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | +101 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | +102 | [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +103 | [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +104 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +105 | [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | +106 | [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | +107 | [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +108 | [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +109 | [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | +110 | [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | +111 | [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +112 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +113 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +114 | [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +115 | [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +116 | [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | +117 | [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | +118 | [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index cf3af973f3..55a8930f0d 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Microsoft.NetCore.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -862,6 +862,139 @@ ] } }, + "CA2350": { + "id": "CA2350", + "shortDescription": "Do not use insecure deserialization with DataTable.ReadXml()", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2350", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataTableReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2351": { + "id": "CA2351", + "shortDescription": "Do not use insecure deserialization with DataSet.ReadXml()", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2351", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2352": { + "id": "CA2352", + "shortDescription": "Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2352", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2353": { + "id": "CA2353", + "shortDescription": "Unsafe DataSet or DataTable in serializable type", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2353", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2354": { + "id": "CA2354", + "shortDescription": "Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2354", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2355": { + "id": "CA2355", + "shortDescription": "Unsafe DataSet or DataTable type found in deserializable object graph", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2355", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2356": { + "id": "CA2356", + "shortDescription": "Unsafe DataSet or DataTable type in web deserializable object graph", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2356", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInWebSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA3001": { "id": "CA3001", "shortDescription": "Review code for SQL injection vulnerabilities", @@ -1161,8 +1294,8 @@ }, "CA5358": { "id": "CA5358", - "shortDescription": "Do Not Use Unsafe Cipher Modes", - "fullDescription": "These modes are vulnerable to attacks. Use only approved modes (CBC, CTS).", + "shortDescription": "Review cipher mode usage with cryptography experts", + "fullDescription": "These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS).", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5358", "properties": { @@ -1238,14 +1371,14 @@ }, "CA5362": { "id": "CA5362", - "shortDescription": "Do Not Refer Self In Serializable Class", - "fullDescription": "This can allow an attacker to DOS or exhaust the memory of the process.", + "shortDescription": "Potential reference cycle in deserialized object graph", + "fullDescription": "Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5362", "properties": { "category": "Security", "isEnabledByDefault": false, - "typeName": "DoNotReferSelfInSerializableClass", + "typeName": "PotentialReferenceCycleInDeserializedObjectGraph", "languages": [ "C#", "Visual Basic" @@ -2056,7 +2189,7 @@ { "tool": { "name": "Microsoft.NetCore.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -2195,7 +2328,7 @@ { "tool": { "name": "Microsoft.NetCore.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif b/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif index 3576590641..eac31cf307 100644 --- a/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif +++ b/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Microsoft.NetFramework.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -91,7 +91,7 @@ { "tool": { "name": "Microsoft.NetFramework.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -136,7 +136,7 @@ { "tool": { "name": "Microsoft.NetFramework.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md b/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md index e69de29bb2..aa57b6e22a 100644 --- a/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md +++ b/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md @@ -0,0 +1,10 @@ +### New Rules +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +CA2350 | Security | Disabled | DoNotUseDataTableReadXml, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2350) +CA2351 | Security | Disabled | DoNotUseDataSetReadXml, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2351) +CA2352 | Security | Disabled | DataSetDataTableInSerializableTypeAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2352) +CA2353 | Security | Disabled | DataSetDataTableInSerializableTypeAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2353) +CA2354 | Security | Disabled | DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2354) +CA2355 | Security | Disabled | DataSetDataTableInSerializableObjectGraphAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2355) +CA2356 | Security | Disabled | DataSetDataTableInWebSerializableObjectGraphAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2356) diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/MicrosoftNetCoreAnalyzersResources.resx b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/MicrosoftNetCoreAnalyzersResources.resx index 5fe4b51d91..008b879e74 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/MicrosoftNetCoreAnalyzersResources.resx +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/MicrosoftNetCoreAnalyzersResources.resx @@ -1218,16 +1218,40 @@ Do not use insecure deserialization with DataTable.ReadXml() - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable in serializable type - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable type in web deserializable object graph + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + Do not use insecure deserialization with DataSet.ReadXml() + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + Unsafe DataSet or DataTable type found in deserializable object graph + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks \ No newline at end of file diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetAnalyzer.cs deleted file mode 100644 index 3875737d46..0000000000 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetAnalyzer.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Text; -using Analyzer.Utilities; -using Analyzer.Utilities.Extensions; -using Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis; -using Analyzer.Utilities.PooledObjects; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; -using Microsoft.NetCore.Analyzers.Security.Helpers; - -namespace Microsoft.NetCore.Analyzers.Security -{ - [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] - public sealed class DataSetAnalyzer : DiagnosticAnalyzer - { - internal DiagnosticDescriptor DefinitelyNoReadXmlSchemaDescriptor = SecurityHelpers.CreateDiagnosticDescriptor( - "CA2351", - nameof(MicrosoftNetCoreAnalyzersResources.DataSetDefinitelyInsecureTitle), - nameof(MicrosoftNetCoreAnalyzersResources.DataSetDefinitelyInsecureMessage), - RuleLevel.Disabled, - isPortedFxCopRule: false, - isDataflowRule: true); - internal DiagnosticDescriptor MaybeNoReadXmlSchemaDescriptor = SecurityHelpers.CreateDiagnosticDescriptor( - "CA2352", - nameof(MicrosoftNetCoreAnalyzersResources.DataSetDefinitelyInsecureTitle), - nameof(MicrosoftNetCoreAnalyzersResources.DataSetDefinitelyInsecureMessage), - RuleLevel.Disabled, - isPortedFxCopRule: false, - isDataflowRule: true); - - public override ImmutableArray SupportedDiagnostics => - ImmutableArray.Create(DefinitelyNoReadXmlSchemaDescriptor, MaybeNoReadXmlSchemaDescriptor); - - private static readonly PropertyMapperCollection PropertyMappers = - new PropertyMapperCollection( - new PropertyMapper("...dummy", PropertySetCallbacks.AlwaysUnknown)); - private static readonly ConstructorMapper ConstructorMapper = - new ConstructorMapper(PropertySetAbstractValueKind.Flagged); - - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - - // Security analyzer - analyze and report diagnostics on generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); - - context.RegisterCompilationStartAction( - (CompilationStartAnalysisContext compilationStartAnalysisContext) => - { - if (!compilationStartAnalysisContext.Compilation.TryGetOrCreateTypeByMetadataName( - WellKnownTypeNames.SystemDataDataSet, - out INamedTypeSymbol? dataSetTypeSymbol)) - { - return; - } - - PooledHashSet<(IOperation Operation, ISymbol ContainingSymbol)> rootOperationsNeedingAnalysis = PooledHashSet<(IOperation, ISymbol)>.GetInstance(); - - compilationStartAnalysisContext.RegisterOperationBlockStartAction( - (OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) => - { - ISymbol owningSymbol = operationBlockStartAnalysisContext.OwningSymbol; - - // TODO: Handle case when exactly one of the below rules is configured to skip analysis. - if (owningSymbol.IsConfiguredToSkipAnalysis( - operationBlockStartAnalysisContext.Options, - DefinitelyNoReadXmlSchemaDescriptor, - operationBlockStartAnalysisContext.Compilation, - operationBlockStartAnalysisContext.CancellationToken) - && owningSymbol.IsConfiguredToSkipAnalysis( - operationBlockStartAnalysisContext.Options, - MaybeNoReadXmlSchemaDescriptor, - operationBlockStartAnalysisContext.Compilation, - operationBlockStartAnalysisContext.CancellationToken)) - { - return; - } - - operationBlockStartAnalysisContext.RegisterOperationAction( - (OperationAnalysisContext operationAnalysisContext) => - { - IObjectCreationOperation creationOperation = - (IObjectCreationOperation)operationAnalysisContext.Operation; - if (creationOperation.Type?.DerivesFrom(dataSetTypeSymbol) == true) - { - lock (rootOperationsNeedingAnalysis) - { - rootOperationsNeedingAnalysis.Add( - (operationAnalysisContext.Operation.GetRoot(), - operationAnalysisContext.ContainingSymbol)); - } - } - }, - OperationKind.ObjectCreation); - - operationBlockStartAnalysisContext.RegisterOperationAction( - (OperationAnalysisContext operationAnalysisContext) => - { - IInvocationOperation invocationOperation = - (IInvocationOperation)operationAnalysisContext.Operation; - if (invocationOperation.Type?.DerivesFrom(dataSetTypeSymbol) == true - && invocationOperation.TargetMethod.Name == "ReadXml") - { - lock (rootOperationsNeedingAnalysis) - { - rootOperationsNeedingAnalysis.Add( - (operationAnalysisContext.Operation.GetRoot(), - operationAnalysisContext.ContainingSymbol)); - } - } - }, - OperationKind.Invocation); - - operationBlockStartAnalysisContext.RegisterOperationAction( - (OperationAnalysisContext operationAnalysisContext) => - { - IMethodReferenceOperation methodReferenceOperation = - (IMethodReferenceOperation)operationAnalysisContext.Operation; - if (methodReferenceOperation.Instance?.Type.DerivesFrom(dataSetTypeSymbol) == true - && methodReferenceOperation.Method.MetadataName == "ReadXml") - { - lock (rootOperationsNeedingAnalysis) - { - rootOperationsNeedingAnalysis.Add( - (operationAnalysisContext.Operation.GetRoot(), - operationAnalysisContext.ContainingSymbol)); - } - } - }, - OperationKind.MethodReference); - }); - - compilationStartAnalysisContext.RegisterCompilationEndAction( - (CompilationAnalysisContext compilationAnalysisContext) => - { - PooledDictionary<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult>? allResults = null; - try - { - lock (rootOperationsNeedingAnalysis) - { - if (!rootOperationsNeedingAnalysis.Any()) - { - return; - } - - allResults = PropertySetAnalysis.BatchGetOrComputeHazardousUsages( - compilationAnalysisContext.Compilation, - rootOperationsNeedingAnalysis, - compilationAnalysisContext.Options, - this.DeserializerTypeMetadataName, - DoNotUseInsecureDeserializerWithoutBinderBase.ConstructorMapper, - propertyMappers, - InvocationMapperCollection.Empty, - hazardousUsageEvaluators, - InterproceduralAnalysisConfiguration.Create( - compilationAnalysisContext.Options, - SupportedDiagnostics, - defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive, - cancellationToken: compilationAnalysisContext.CancellationToken)); - } - - if (allResults == null) - { - return; - } - - foreach (KeyValuePair<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult> kvp - in allResults) - { - DiagnosticDescriptor descriptor; - switch (kvp.Value) - { - case HazardousUsageEvaluationResult.Flagged: - descriptor = this.BinderDefinitelyNotSetDescriptor!; - break; - - case HazardousUsageEvaluationResult.MaybeFlagged: - descriptor = this.BinderMaybeNotSetDescriptor!; - break; - - default: - Debug.Fail($"Unhandled result value {kvp.Value}"); - continue; - } - - RoslynDebug.Assert(kvp.Key.Method != null); // HazardousUsageEvaluations only for invocations. - compilationAnalysisContext.ReportDiagnostic( - Diagnostic.Create( - descriptor, - kvp.Key.Location, - kvp.Key.Method.ToDisplayString( - SymbolDisplayFormat.MinimallyQualifiedFormat))); - } - } - finally - { - rootOperationsNeedingAnalysis.Free(); - allResults?.Free(); - } - }); - }); - - } - } -} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer.cs new file mode 100644 index 0000000000..7584533272 --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.NetCore.Analyzers.Security.Helpers; + +namespace Microsoft.NetCore.Analyzers.Security +{ + /// + /// For detecting deserialization of or in an + /// IFormatter deserialized object graph. + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer : DiagnosticAnalyzer + { + internal static readonly DiagnosticDescriptor ObjectGraphContainsDangerousTypeDescriptor = + SecurityHelpers.CreateDiagnosticDescriptor( + "CA2354", + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInRceDeserializableObjectGraphTitle), + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInRceDeserializableObjectGraphMessage), + RuleLevel.Disabled, + isPortedFxCopRule: false, + isDataflowRule: false); + + public override ImmutableArray SupportedDiagnostics => + ImmutableArray.Create(ObjectGraphContainsDangerousTypeDescriptor); + + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + + // Security analyzer - analyze and report diagnostics on generated code. + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + + context.RegisterCompilationStartAction( + (CompilationStartAnalysisContext compilationStartAnalysisContext) => + { + Compilation? compilation = compilationStartAnalysisContext.Compilation; + WellKnownTypeProvider wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation); + + if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataSet, + out INamedTypeSymbol? dataSetTypeSymbol) + || !wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataTable, + out INamedTypeSymbol? dataTableTypeSymbol)) + { + return; + } + + INamedTypeSymbol? serializableAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemSerializableAttribute); + INamedTypeSymbol? nonSerializedAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemSerializableAttribute); + INamedTypeSymbol? binaryFormatterTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationFormattersBinaryBinaryFormatter); + INamedTypeSymbol? netDataContractSerializerTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationNetDataContractSerializer); + INamedTypeSymbol? objectStateFormatterTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemWebUIObjectStateFormatter); + INamedTypeSymbol? soapFormatterTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationFormattersSoapSoapFormatter); + + if (serializableAttributeTypeSymbol == null + || (binaryFormatterTypeSymbol == null + && netDataContractSerializerTypeSymbol == null + && objectStateFormatterTypeSymbol == null + && soapFormatterTypeSymbol == null)) + { + return; + } + + InsecureDeserializationTypeDecider decider = InsecureDeserializationTypeDecider.GetOrCreate(compilation); + + compilationStartAnalysisContext.RegisterOperationAction( + (OperationAnalysisContext operationAnalysisContext) => + { + IInvocationOperation invocationOperation = + (IInvocationOperation)operationAnalysisContext.Operation; + string methodName = invocationOperation.TargetMethod.MetadataName; + if (!(((invocationOperation.Instance?.Type?.DerivesFrom(binaryFormatterTypeSymbol) == true + && SecurityHelpers.BinaryFormatterDeserializationMethods.Contains(methodName)) + || (invocationOperation.Instance?.Type?.DerivesFrom(netDataContractSerializerTypeSymbol) == true + && SecurityHelpers.NetDataContractSerializerDeserializationMethods.Contains(methodName)) + || (invocationOperation.Instance?.Type?.DerivesFrom(objectStateFormatterTypeSymbol) == true + && SecurityHelpers.ObjectStateFormatterDeserializationMethods.Contains(methodName)) + || (invocationOperation.Instance?.Type?.DerivesFrom(soapFormatterTypeSymbol) == true + && SecurityHelpers.SoapFormatterDeserializationMethods.Contains(methodName))) + && invocationOperation.Parent?.Kind == OperationKind.Conversion + && invocationOperation.Parent is IConversionOperation conversionOperation)) + { + return; + } + + ITypeSymbol deserializedType = conversionOperation.Type; + + ObjectGraphOptions options; + if (invocationOperation.Instance?.Type?.DerivesFrom(netDataContractSerializerTypeSymbol) == true) + { + options = ObjectGraphOptions.DataContractOptions; + } + else + { + options = ObjectGraphOptions.BinarySerializationOptions; + } + + if (decider.IsObjectGraphInsecure( + deserializedType, + options, + out ImmutableArray results)) + { + foreach (InsecureObjectGraphResult result in results) + { + operationAnalysisContext.ReportDiagnostic( + Diagnostic.Create( + ObjectGraphContainsDangerousTypeDescriptor, + invocationOperation.Parent.Syntax.GetLocation(), + result.InsecureType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + result.GetDisplayString())); + } + } + }, + OperationKind.Invocation); + }); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableObjectGraphAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableObjectGraphAnalyzer.cs new file mode 100644 index 0000000000..0d02b9a294 --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableObjectGraphAnalyzer.cs @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.NetCore.Analyzers.Security.Helpers; + +namespace Microsoft.NetCore.Analyzers.Security +{ + /// + /// For detecting deserialization of or in an + /// deserialized object graph for certain serializers. + /// + /// + /// Serializers: + /// - DataContractSerializer + /// - DataContractJsonSerializer + /// - JavaScriptSerializer + /// - XmlSerializer + /// - Newtonsoft Json.NET (partial) + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class DataSetDataTableInSerializableObjectGraphAnalyzer : DiagnosticAnalyzer + { + internal static readonly DiagnosticDescriptor ObjectGraphContainsDangerousTypeDescriptor = + SecurityHelpers.CreateDiagnosticDescriptor( + "CA2355", + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInDeserializableObjectGraphTitle), + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInDeserializableObjectGraphMessage), + RuleLevel.Disabled, + isPortedFxCopRule: false, + isDataflowRule: false); + + public override ImmutableArray SupportedDiagnostics => + ImmutableArray.Create(ObjectGraphContainsDangerousTypeDescriptor); + + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + + // Security analyzer - analyze and report diagnostics on generated code. + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + + context.RegisterCompilationStartAction( + (CompilationStartAnalysisContext compilationStartAnalysisContext) => + { + Compilation? compilation = compilationStartAnalysisContext.Compilation; + WellKnownTypeProvider wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation); + + if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataSet, + out INamedTypeSymbol? dataSetTypeSymbol) + || !wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataTable, + out INamedTypeSymbol? dataTableTypeSymbol)) + { + return; + } + + INamedTypeSymbol? dataContractSerializerTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationDataContractSerializer); + INamedTypeSymbol? dataContractJsonSerializerTypeSymbol = + wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationJsonDataContractJsonSerializer); + INamedTypeSymbol? javaScriptSerializerTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemWebScriptSerializationJavaScriptSerializer); + INamedTypeSymbol? typeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemType); + INamedTypeSymbol? xmlSerializerTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlSerializer); + INamedTypeSymbol? jsonNetJsonSerializerTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.NewtonsoftJsonJsonSerializer); + INamedTypeSymbol? jsonNetJsonConvertTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.NewtonsoftJsonJsonConvert); + + if (dataContractSerializerTypeSymbol == null + && dataContractJsonSerializerTypeSymbol == null + && javaScriptSerializerTypeSymbol == null + && xmlSerializerTypeSymbol == null + && jsonNetJsonSerializerTypeSymbol == null + && jsonNetJsonConvertTypeSymbol == null) + { + return; + } + + InsecureDeserializationTypeDecider decider = InsecureDeserializationTypeDecider.GetOrCreate(compilation); + + compilationStartAnalysisContext.RegisterOperationAction( + (OperationAnalysisContext operationAnalysisContext) => + { + IInvocationOperation invocationOperation = + (IInvocationOperation)operationAnalysisContext.Operation; + if (!IsDeserializationMethod( + invocationOperation, + out ObjectGraphOptions? optionsToUse, + out IEnumerable<(ITypeSymbol DeserializedTypeSymbol, IOperation OperationForLocation)>? deserializedTypes)) + { + return; + } + + RoslynDebug.Assert(optionsToUse != null); + RoslynDebug.Assert(deserializedTypes != null); + + ReportDiagnosticsForInsecureTypes(operationAnalysisContext, optionsToUse, deserializedTypes); + }, + OperationKind.Invocation); + + compilationStartAnalysisContext.RegisterOperationAction( + (OperationAnalysisContext operationAnalysisContext) => + { + IObjectCreationOperation objectCreationOperation = + (IObjectCreationOperation)operationAnalysisContext.Operation; + if (!IsDeserializationConstructor( + objectCreationOperation, + out ObjectGraphOptions? optionsToUse, + out IEnumerable<(ITypeSymbol DeserializedTypeSymbol, IOperation OperationForLocation)>? deserializedTypes)) + { + return; + } + + RoslynDebug.Assert(optionsToUse != null); + RoslynDebug.Assert(deserializedTypes != null); + + ReportDiagnosticsForInsecureTypes(operationAnalysisContext, optionsToUse, deserializedTypes); + }, + OperationKind.ObjectCreation); + + return; + + // Local functions. + + // Determines if the invoked method is for deserialization, and what type of deserialization. + bool IsDeserializationMethod( + IInvocationOperation invocationOperation, + out ObjectGraphOptions? optionsToUse, + out IEnumerable<(ITypeSymbol DeserializedTypeSymbol, IOperation OperationForLocation)>? deserializedTypes) + { + optionsToUse = null; + deserializedTypes = null; + + IMethodSymbol targetMethod = invocationOperation.TargetMethod; + if (invocationOperation.Instance?.Type?.DerivesFrom(javaScriptSerializerTypeSymbol) == true) + { + if (targetMethod.MetadataName == "DeserializeObject" + && invocationOperation.Parent?.Kind == OperationKind.Conversion + && invocationOperation.Parent is IConversionOperation javaScriptConversionOperation) + { + optionsToUse = ObjectGraphOptions.JavaScriptSerializerOptions; + deserializedTypes = new[] + { + (javaScriptConversionOperation.Type, (IOperation)javaScriptConversionOperation) + }; + } + else if (targetMethod.MetadataName == "Deserialize") + { + if (targetMethod.IsGenericMethod + && targetMethod.Arity == 1 + && targetMethod.Parameters.Length == 1) + { + optionsToUse = ObjectGraphOptions.JavaScriptSerializerOptions; + deserializedTypes = new[] + { + (targetMethod.TypeArguments[0], (IOperation)invocationOperation) + }; + } + else if (!targetMethod.IsGenericMethod + && targetMethod.Parameters.Length == 2 + && targetMethod.Parameters[1].Type.Equals(typeTypeSymbol) + && invocationOperation.HasArgument(out ITypeOfOperation? typeOfOperation)) + { + optionsToUse = ObjectGraphOptions.JavaScriptSerializerOptions; + deserializedTypes = new[] + { + (typeOfOperation.TypeOperand, (IOperation)typeOfOperation) + }; + } + } + } + else if (targetMethod.ContainingType.Equals(xmlSerializerTypeSymbol) + && targetMethod.IsStatic + && targetMethod.MetadataName == "FromTypes" + && targetMethod.Parameters.Length == 1 + && targetMethod.Parameters[0].Type is IArrayTypeSymbol arrayTypeSymbol + && arrayTypeSymbol.ElementType.Equals(typeTypeSymbol)) + { + optionsToUse = ObjectGraphOptions.XmlSerializerOptions; + deserializedTypes = + invocationOperation + .Arguments[0] + .Descendants() + .OfType() + .Select(t => (t.TypeOperand!, (IOperation)t)); + } + else if ((invocationOperation.Instance?.Type.DerivesFrom(jsonNetJsonSerializerTypeSymbol) == true + && targetMethod.MetadataName == "Deserialize") + || (targetMethod.ContainingType.Equals(jsonNetJsonConvertTypeSymbol) + && targetMethod.MetadataName == "DeserializeObject")) + { + if (targetMethod.IsGenericMethod && targetMethod.Arity == 1) + { + optionsToUse = ObjectGraphOptions.NewtonsoftJsonNetOptions; + deserializedTypes = new[] + { + (targetMethod.TypeArguments[0], (IOperation)invocationOperation) + }; + } + else if (targetMethod.Parameters.Length == 2 + && targetMethod.Parameters[1].Type.Equals(typeTypeSymbol) + && invocationOperation.HasArgument(out ITypeOfOperation? typeOfOperation)) + { + optionsToUse = ObjectGraphOptions.NewtonsoftJsonNetOptions; + deserializedTypes = new[] + { + (typeOfOperation.TypeOperand, (IOperation)typeOfOperation) + }; + } + else if (invocationOperation.Parent?.Kind == OperationKind.Conversion + && invocationOperation.Parent is IConversionOperation conversionOperation) + { + optionsToUse = ObjectGraphOptions.NewtonsoftJsonNetOptions; + deserializedTypes = new[] + { + (conversionOperation.Type, (IOperation)conversionOperation) + }; + } + } + + return optionsToUse != null && deserializedTypes != null; + } + + // Determines if the object instantiation is for deserialization, and the type of deserialization. + bool IsDeserializationConstructor( + IObjectCreationOperation objectCreationOperation, + out ObjectGraphOptions? optionsToUse, + out IEnumerable<(ITypeSymbol DeserializedTypeSymbol, IOperation OperationForLocation)>? deserializedTypes) + { + optionsToUse = null; + deserializedTypes = null; + + IMethodSymbol constructor = objectCreationOperation.Constructor; + if (objectCreationOperation.Type?.Equals(dataContractSerializerTypeSymbol) == true + || objectCreationOperation.Type?.Equals(dataContractJsonSerializerTypeSymbol) == true) + { + optionsToUse = ObjectGraphOptions.DataContractOptions; + deserializedTypes = + objectCreationOperation + .Arguments + .SelectMany(a => a.Descendants()) + .OfType() + .Select(t => (t.TypeOperand!, (IOperation)t)); + } + else if (objectCreationOperation.Type?.Equals(xmlSerializerTypeSymbol) == true) + { + optionsToUse = ObjectGraphOptions.XmlSerializerOptions; + deserializedTypes = + objectCreationOperation + .Arguments + .SelectMany(a => a.Descendants()) + .OfType() + .Select(t => (t.TypeOperand!, (IOperation)t)); + } + + return optionsToUse != null && deserializedTypes != null; + } + + // For each deserialized type, determine if its object graph potentially contains an insecure type, and if + // report a diagnostic if so. + void ReportDiagnosticsForInsecureTypes( + OperationAnalysisContext operationAnalysisContext, + ObjectGraphOptions optionsToUse, + IEnumerable<(ITypeSymbol DeserializedTypeSymbol, IOperation OperationForLocation)> deserializedTypes) + { + foreach ((ITypeSymbol deserializedTypeSymbol, IOperation operationForLocation) in deserializedTypes) + { + if (decider.IsObjectGraphInsecure( + deserializedTypeSymbol, + optionsToUse, + out ImmutableArray results)) + { + foreach (InsecureObjectGraphResult result in results) + { + operationAnalysisContext.ReportDiagnostic( + Diagnostic.Create( + ObjectGraphContainsDangerousTypeDescriptor, + operationForLocation.Syntax.GetLocation(), + result.InsecureType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + result.GetDisplayString())); + } + } + } + } + }); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeAnalyzer.cs new file mode 100644 index 0000000000..afde9602a9 --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeAnalyzer.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Concurrent; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.NetCore.Analyzers.Security.Helpers; + +namespace Microsoft.NetCore.Analyzers.Security +{ + /// + /// For detecting or deserializable members. + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class DataSetDataTableInSerializableTypeAnalyzer : DiagnosticAnalyzer + { + // At this time, treat IFormatter-based serializers differently, since they have different guidance and known impact. + internal static readonly DiagnosticDescriptor RceSerializableContainsDangerousType = + SecurityHelpers.CreateDiagnosticDescriptor( + "CA2352", + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInRceSerializableTypeTitle), + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInRceSerializableTypeMessage), + RuleLevel.Disabled, + isPortedFxCopRule: false, + isDataflowRule: false); + + internal static readonly DiagnosticDescriptor SerializableContainsDangerousType = + SecurityHelpers.CreateDiagnosticDescriptor( + "CA2353", + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInSerializableTypeTitle), + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInSerializableTypeMessage), + RuleLevel.Disabled, + isPortedFxCopRule: false, + isDataflowRule: false); + + public override ImmutableArray SupportedDiagnostics => + ImmutableArray.Create(RceSerializableContainsDangerousType, SerializableContainsDangerousType); + + [SuppressMessage("Style", "IDE0047:Remove unnecessary parentheses", Justification = "Group related conditions together.")] + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + + // Security analyzer - analyze and report diagnostics on generated code. + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + + context.RegisterCompilationStartAction( + (CompilationStartAnalysisContext compilationStartAnalysisContext) => + { + Compilation? compilation = compilationStartAnalysisContext.Compilation; + WellKnownTypeProvider wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation); + + if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataSet, + out INamedTypeSymbol? dataSetTypeSymbol) + || !wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataTable, + out INamedTypeSymbol? dataTableTypeSymbol)) + { + return; + } + + INamedTypeSymbol? serializableAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemSerializableAttribute); + + INamedTypeSymbol? generatedCodeAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemCodeDomCompilerGeneratedCodeAttribute); + + // For completeness, could also consider CollectionDataContractAttribute + INamedTypeSymbol? dataContractAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationDataContractAttribute); + INamedTypeSymbol? dataMemberAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationDataMemberAttribute); + INamedTypeSymbol? ignoreDataMemberTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationIgnoreDataMemberAttribute); + INamedTypeSymbol? knownTypeAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationKnownTypeAttribute); + + XmlSerializationAttributeTypes xmlSerializationAttributeTypes = new XmlSerializationAttributeTypes( + wellKnownTypeProvider); + if (serializableAttributeTypeSymbol == null + && (dataContractAttributeTypeSymbol == null || dataMemberAttributeTypeSymbol == null) + && ignoreDataMemberTypeSymbol == null + && knownTypeAttributeTypeSymbol == null + && !xmlSerializationAttributeTypes.Any) + { + return; + } + + InsecureDeserializationTypeDecider decider = InsecureDeserializationTypeDecider.GetOrCreate(compilation); + + ConcurrentDictionary visitedTypes = + new ConcurrentDictionary(); + + compilationStartAnalysisContext.RegisterSymbolAction( + (SymbolAnalysisContext symbolAnalysisContext) => + { + INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; + bool hasSerializableAttribute = namedTypeSymbol.HasAttribute(serializableAttributeTypeSymbol); + + // Assume that [GeneratedCode] means not used for serialization. + bool hasGeneratedCodeAttribute = namedTypeSymbol.HasAttribute(generatedCodeAttributeTypeSymbol); + bool hasDataContractAttribute = namedTypeSymbol.HasAttribute(dataContractAttributeTypeSymbol); + bool hasKnownTypeAttribute = namedTypeSymbol.HasAttribute(knownTypeAttributeTypeSymbol); + bool hasAnyIgnoreDataMemberAttribute = + namedTypeSymbol.GetMembers().Any(m => m.HasAttribute(ignoreDataMemberTypeSymbol)); + bool hasAnyXmlSerializationAttributes = + xmlSerializationAttributeTypes.HasAnyAttribute(namedTypeSymbol) + || namedTypeSymbol.GetMembers().Any(m => xmlSerializationAttributeTypes.HasAnyAttribute(m)); + if (!hasSerializableAttribute + && !hasDataContractAttribute + && !hasKnownTypeAttribute + && !hasAnyIgnoreDataMemberAttribute + && !hasAnyXmlSerializationAttributes) + { + // Don't have any attributes suggesting this class is serialized. + return; + } + + ObjectGraphOptions options = new ObjectGraphOptions( + recurse: false, + binarySerialization: hasSerializableAttribute, + dataContractSerialization: + hasDataContractAttribute + || hasAnyIgnoreDataMemberAttribute + || hasKnownTypeAttribute, + xmlSerialization: hasAnyXmlSerializationAttributes); + + if (decider.IsObjectGraphInsecure( + namedTypeSymbol, + options, + out ImmutableArray results)) + { + DiagnosticDescriptor diagnosticToReport = + hasSerializableAttribute + ? RceSerializableContainsDangerousType + : SerializableContainsDangerousType; + + foreach (InsecureObjectGraphResult result in results) + { + symbolAnalysisContext.ReportDiagnostic( + Diagnostic.Create( + diagnosticToReport, + result.GetLocation(), + result.InsecureType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + result.GetDisplayString())); + } + } + }, + SymbolKind.NamedType); + }); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphAnalyzer.cs new file mode 100644 index 0000000000..3f5042dcff --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphAnalyzer.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.NetCore.Analyzers.Security.Helpers; + +namespace Microsoft.NetCore.Analyzers.Security +{ + /// + /// For detecting deserialization of or in an + /// web API / WCF API serializable object graph. + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class DataSetDataTableInWebSerializableObjectGraphAnalyzer : DiagnosticAnalyzer + { + internal static readonly DiagnosticDescriptor ObjectGraphContainsDangerousTypeDescriptor = + SecurityHelpers.CreateDiagnosticDescriptor( + "CA2356", + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInWebDeserializableObjectGraphTitle), + nameof(MicrosoftNetCoreAnalyzersResources.DataSetDataTableInWebDeserializableObjectGraphMessage), + RuleLevel.Disabled, + isPortedFxCopRule: false, + isDataflowRule: false); + + public override ImmutableArray SupportedDiagnostics => + ImmutableArray.Create(ObjectGraphContainsDangerousTypeDescriptor); + + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + + // Security analyzer - analyze and report diagnostics on generated code. + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + + context.RegisterCompilationStartAction( + (CompilationStartAnalysisContext compilationStartAnalysisContext) => + { + Compilation? compilation = compilationStartAnalysisContext.Compilation; + WellKnownTypeProvider wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation); + + if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataSet, + out INamedTypeSymbol? dataSetTypeSymbol) + || !wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemDataDataTable, + out INamedTypeSymbol? dataTableTypeSymbol)) + { + return; + } + + INamedTypeSymbol? webMethodAttributeTypeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemWebServicesWebMethodAttribute); + INamedTypeSymbol? operationContractAttributeTypeSymbol = + wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemServiceModelOperationContractAttribute); + + if (webMethodAttributeTypeSymbol == null && operationContractAttributeTypeSymbol == null) + { + return; + } + + InsecureDeserializationTypeDecider decider = InsecureDeserializationTypeDecider.GetOrCreate(compilation); + + // Symbol actions for SymbolKind.Method don't seem to trigger on interface methods, so we'll do register + // for SymbolKind.NamedTypeSymbol instead. + compilationStartAnalysisContext.RegisterSymbolAction( + (SymbolAnalysisContext symbolAnalysisContext) => + { + INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; + if (namedTypeSymbol.TypeKind != TypeKind.Interface + && namedTypeSymbol.TypeKind != TypeKind.Class) + { + return; + } + + foreach (ISymbol? memberSymbol in namedTypeSymbol.GetMembers()) + { + if (!(memberSymbol is IMethodSymbol methodSymbol)) + { + continue; + } + + ObjectGraphOptions optionsToUse; + if (methodSymbol.HasAttribute(webMethodAttributeTypeSymbol)) + { + optionsToUse = ObjectGraphOptions.XmlSerializerOptions; + } + else if (methodSymbol.HasAttribute(operationContractAttributeTypeSymbol)) + { + optionsToUse = ObjectGraphOptions.DataContractOptions; + } + else + { + continue; + } + + foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) + { + if (decider.IsObjectGraphInsecure( + parameterSymbol.Type, + optionsToUse, + out ImmutableArray results)) + { + foreach (InsecureObjectGraphResult result in results) + { + symbolAnalysisContext.ReportDiagnostic( + Diagnostic.Create( + ObjectGraphContainsDangerousTypeDescriptor, + parameterSymbol.DeclaringSyntaxReferences.First().GetSyntax().GetLocation(), + result.InsecureType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + result.GetDisplayString())); + } + } + } + } + }, + SymbolKind.NamedType); + }); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotDisableHttpClientCRLCheck.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotDisableHttpClientCRLCheck.cs index ae1a9107c3..739160ea8d 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotDisableHttpClientCRLCheck.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotDisableHttpClientCRLCheck.cs @@ -192,7 +192,6 @@ public override void Initialize(AnalysisContext context) typeToTrackMetadataNames, ConstructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, HazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotInstallRootCert.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotInstallRootCert.cs index 2729c35dea..dc16acc994 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotInstallRootCert.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotInstallRootCert.cs @@ -180,7 +180,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.SystemSecurityCryptographyX509CertificatesX509Store, constructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, hazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseCreateEncryptorWithNonDefaultIV.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseCreateEncryptorWithNonDefaultIV.cs index 491e0503a8..c7a38877e0 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseCreateEncryptorWithNonDefaultIV.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseCreateEncryptorWithNonDefaultIV.cs @@ -155,7 +155,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.SystemSecurityCryptographySymmetricAlgorithm, ConstructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, HazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXml.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXml.cs new file mode 100644 index 0000000000..0ab3d10ee8 --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXml.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Analyzer.Utilities; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.NetCore.Analyzers.Security.Helpers; + +namespace Microsoft.NetCore.Analyzers.Security +{ + /// + /// For detecting deserialization with . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + internal class DoNotUseDataSetReadXml : DoNotUseInsecureDeserializerMethodsBase + { + internal static readonly DiagnosticDescriptor RealMethodUsedDescriptor = + SecurityHelpers.CreateDiagnosticDescriptor( + "CA2351", + nameof(MicrosoftNetCoreAnalyzersResources.DataSetReadXmlTitle), + nameof(MicrosoftNetCoreAnalyzersResources.DataSetReadXmlMessage), + RuleLevel.Disabled, + isPortedFxCopRule: false, + isDataflowRule: false); + + protected override string DeserializerTypeMetadataName => + WellKnownTypeNames.SystemDataDataSet; + + protected override ImmutableHashSet DeserializationMethodNames => + SecurityHelpers.DataSetDeserializationMethods; + + protected override DiagnosticDescriptor MethodUsedDescriptor => RealMethodUsedDescriptor; + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs index 617eac44fa..0eb69913b6 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs @@ -216,7 +216,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.SystemWebScriptSerializationJavaScriptSerializer, constructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, hazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJsonNetWithoutBinder.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJsonNetWithoutBinder.cs index 85a893219b..ca81d805f5 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJsonNetWithoutBinder.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJsonNetWithoutBinder.cs @@ -198,7 +198,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.NewtonsoftJsonJsonSerializer, ConstructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, HazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerWithoutBinderBase.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerWithoutBinderBase.cs index e79bf4025e..68231c28f7 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerWithoutBinderBase.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerWithoutBinderBase.cs @@ -187,7 +187,6 @@ public sealed override void Initialize(AnalysisContext context) this.DeserializerTypeMetadataName, DoNotUseInsecureDeserializerWithoutBinderBase.ConstructorMapper, propertyMappers, - InvocationMapperCollection.Empty, hazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureSettingsForJsonNet.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureSettingsForJsonNet.cs index f41990a427..52dbff9056 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureSettingsForJsonNet.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureSettingsForJsonNet.cs @@ -223,7 +223,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.NewtonsoftJsonJsonSerializerSettings, ConstructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, HazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseWeakKDFInsufficientIterationCount.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseWeakKDFInsufficientIterationCount.cs index c152baea1d..743c6a824f 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseWeakKDFInsufficientIterationCount.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseWeakKDFInsufficientIterationCount.cs @@ -175,7 +175,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes, constructorMapper, propertyMappers, - InvocationMapperCollection.Empty, hazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureDeserializationTypeDecider.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureDeserializationTypeDecider.cs new file mode 100644 index 0000000000..be8214e4fd --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureDeserializationTypeDecider.cs @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Analyzer.Utilities.PooledObjects; +using Microsoft.CodeAnalysis; + +namespace Microsoft.NetCore.Analyzers.Security.Helpers +{ + /// + /// Determines if a given type is insecure for deserialization, by seeing if it contain known dangerous types. + /// + internal sealed partial class InsecureDeserializationTypeDecider + { + private static readonly string[] InsecureTypeNames = + { + WellKnownTypeNames.SystemDataDataSet, + WellKnownTypeNames.SystemDataDataTable, + }; + + private static readonly BoundedCacheWithFactory BoundedCache = + new BoundedCacheWithFactory(); + + /// + /// Gets a cached for the given compilation. + /// + /// Compilation that the decider is for. + /// Cached decider. + public static InsecureDeserializationTypeDecider GetOrCreate(Compilation compilation) + { + return BoundedCache.GetOrCreateValue(compilation, Create); + + // Local functions. + static InsecureDeserializationTypeDecider Create(Compilation c) => new InsecureDeserializationTypeDecider(c); + } + + /// + /// Constructs. + /// + /// Compilation being analyzed. + private InsecureDeserializationTypeDecider(Compilation compilation) + { + foreach (string typeName in InsecureTypeNames) + { + if (compilation.TryGetOrCreateTypeByMetadataName(typeName, out INamedTypeSymbol? namedTypeSymbol)) + { + this.InsecureTypeSymbols.Add(namedTypeSymbol); + } + } + + this.SymbolByDisplayStringComparer = new SymbolByDisplayStringComparer(compilation); + this.WellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation); + + this.GeneratedCodeAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemCodeDomCompilerGeneratedCodeAttribute); + + this.SerializableAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemSerializableAttribute); + this.NonSerializedAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemSerializableAttribute); + + this.DataContractAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationDataContractAttribute); + this.DataMemberAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationDataMemberAttribute); + this.IgnoreDataMemberTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationIgnoreDataMemberAttribute); + this.KnownTypeAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemRuntimeSerializationKnownTypeAttribute); + this.XmlSerializationAttributeTypes = new XmlSerializationAttributeTypes( + this.WellKnownTypeProvider); + this.JsonIgnoreAttributeTypeSymbol = this.WellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.NewtonsoftJsonJsonIgnoreAttribute); + } + + /// + /// Doesn't construct. + /// + private InsecureDeserializationTypeDecider() + { + throw new NotSupportedException(); + } + + /// + /// Comparer for the compilation's TypeSymbols. + /// + public SymbolByDisplayStringComparer SymbolByDisplayStringComparer { get; } + + /// + /// Type cache. + /// + private WellKnownTypeProvider WellKnownTypeProvider { get; } + + /// + /// Set of type symbols for types that are insecure if deserialized. + /// + private HashSet InsecureTypeSymbols { get; } = new HashSet(); + + private INamedTypeSymbol? GeneratedCodeAttributeTypeSymbol { get; } + private INamedTypeSymbol? SerializableAttributeTypeSymbol { get; } + private INamedTypeSymbol? NonSerializedAttributeTypeSymbol { get; } + private INamedTypeSymbol? DataContractAttributeTypeSymbol { get; } + private INamedTypeSymbol? DataMemberAttributeTypeSymbol { get; } + private INamedTypeSymbol? IgnoreDataMemberTypeSymbol { get; } + private INamedTypeSymbol? KnownTypeAttributeTypeSymbol { get; } + private XmlSerializationAttributeTypes XmlSerializationAttributeTypes { get; } + private INamedTypeSymbol? JsonIgnoreAttributeTypeSymbol { get; } + + // Cache results for IsTypeInsecure() + // Key: typeSymbol in IsTypeInsecure() + // Value: insecureTypeSymbol in IsTypeInsecure() + private readonly ConcurrentDictionary IsTypeInsecureCache = + new ConcurrentDictionary(); + + /// + /// Determines if the given type is insecure when deserialized, without looking at its child fields and properties. + /// + /// Type to check. + /// Insecure type, if the checked type is insecure. + /// True if insecure, false otherwise. + /// This only considers the type and its associated types (generic type arguments, base classes, etc), not + /// types of member fields and properties. + public bool IsTypeInsecure( + ITypeSymbol? typeSymbol, + [NotNullWhen(returnValue: true)] out ITypeSymbol? insecureTypeSymbol) + { + insecureTypeSymbol = null; + + if (typeSymbol == null || this.InsecureTypeSymbols.Count == 0) + { + return false; + } + + insecureTypeSymbol = this.IsTypeInsecureCache.GetOrAdd(typeSymbol, Compute(typeSymbol)); + return insecureTypeSymbol != null; + + // Local functions. + ITypeSymbol? Compute(ITypeSymbol typeSymbol) + { + // Sort type symbols by display string so that we get consistent results. + using PooledSortedSet associatedTypeSymbols = PooledSortedSet.GetInstance( + this.SymbolByDisplayStringComparer); + GetAssociatedTypes(typeSymbol, associatedTypeSymbols); + foreach (ITypeSymbol t in associatedTypeSymbols) + { + if (this.InsecureTypeSymbols.Contains(t)) + { + return t; + } + } + + return null; + } + } + + // Cache for IsObjectGraphInsecure results. + // Key: (rootType, options) arguments in IsObjectGraphInsecure() + // Value: results argument in IsObjectGraphInsecure(). + private readonly ConcurrentDictionary<(ITypeSymbol, ObjectGraphOptions), ImmutableArray> IsObjectGraphInsecureCache = + new ConcurrentDictionary<(ITypeSymbol, ObjectGraphOptions), ImmutableArray>(); + + /// + /// Determines if a type's object graph contains an insecure type, by walking through its serializable members. + /// + /// Type to check. + /// Options for the type of serialization. + /// List to populate results of which symbols (fields or properties) are an insecure + /// type. + /// True if are any insecure symbols, false otherwise. + [SuppressMessage("Style", "IDE0047:Remove unnecessary parentheses", Justification = "Group related conditions together.")] + public bool IsObjectGraphInsecure( + ITypeSymbol rootType, + ObjectGraphOptions options, + out ImmutableArray results) + { + options.ThrowIfInvalid(nameof(options)); + + if (this.InsecureTypeSymbols.Count == 0) + { + return false; + } + + results = this.IsObjectGraphInsecureCache.GetOrAdd((rootType, options), Compute); + return !results.IsEmpty; + + // Local functions. + ImmutableArray Compute((ITypeSymbol, ObjectGraphOptions) _) + { + ImmutableArray.Builder resultBuilder = + ImmutableArray.CreateBuilder(); + + using PooledHashSet visitedTypes = PooledHashSet.GetInstance(); + GetInsecureSymbol(rootType, visitedTypes, resultBuilder); + + return resultBuilder.ToImmutable(); + } + + void GetInsecureSymbol( + ITypeSymbol typeSymbol, + PooledHashSet visitedTypes, + ImmutableArray.Builder resultBuilder) + { + if (!visitedTypes.Add(typeSymbol)) + { + return; + } + + if (this.IsTypeInsecure(typeSymbol, out ITypeSymbol? typeInsecureTypeSymbol)) + { + resultBuilder.Add(new InsecureObjectGraphResult(typeSymbol, null, null, typeInsecureTypeSymbol)); + } + + bool[] hasAttributes = typeSymbol.HasAttributes( + this.GeneratedCodeAttributeTypeSymbol, + this.SerializableAttributeTypeSymbol, + this.DataContractAttributeTypeSymbol, + this.KnownTypeAttributeTypeSymbol); + int index = 0; + bool hasGeneratedCodeAttribute = hasAttributes[index++]; + bool hasSerializableAttribute = hasAttributes[index++]; + bool hasDataContractAttribute = hasAttributes[index++]; + bool hasKnownTypeAttribute = hasAttributes[index++]; + + bool hasAnyIgnoreDataMemberAttribute = + typeSymbol.GetMembers().Any(m => m.HasAttribute(this.IgnoreDataMemberTypeSymbol)); + + bool hasAnyXmlSerializationAttributes = + this.XmlSerializationAttributeTypes.HasAnyAttribute(typeSymbol) + || typeSymbol.GetMembers().Any(m => this.XmlSerializationAttributeTypes.HasAnyAttribute(m)); + + // Consider handling other Newtonsoft Json.NET member serialization modes other than its default. + + // Sort type symbols by display strings. + // Keep track of member types we see, and we'll recurse through those afterwards. + using PooledSortedSet typesToRecurse = PooledSortedSet.GetInstance( + this.SymbolByDisplayStringComparer); + foreach (ISymbol member in typeSymbol.GetMembers()) + { + switch (member) + { + case IFieldSymbol fieldSymbol: + if (!fieldSymbol.IsStatic + && !fieldSymbol.IsBackingFieldForProperty(out _) // Handle properties below. + && ((options.BinarySerialization + && hasSerializableAttribute + && !fieldSymbol.HasAttribute(this.NonSerializedAttributeTypeSymbol)) + || (options.DataContractSerialization + && ((hasDataContractAttribute && fieldSymbol.HasAttribute(this.DataMemberAttributeTypeSymbol)) + || (!hasDataContractAttribute && !fieldSymbol.HasAttribute(this.IgnoreDataMemberTypeSymbol)))) + || (options.XmlSerialization + && !fieldSymbol.HasAttribute( + this.XmlSerializationAttributeTypes.XmlIgnoreAttribute) + && fieldSymbol.DeclaredAccessibility == Accessibility.Public) + || (options.JavaScriptSerializer + && fieldSymbol.DeclaredAccessibility == Accessibility.Public) + || (options.NewtonsoftJsonNetSerialization + && fieldSymbol.DeclaredAccessibility == Accessibility.Public + && !fieldSymbol.HasAttribute(this.JsonIgnoreAttributeTypeSymbol) + && !fieldSymbol.HasAttribute(this.NonSerializedAttributeTypeSymbol)))) + { + if (this.IsTypeInsecure(fieldSymbol.Type, out ITypeSymbol? fieldInsecureTypeSymbol)) + { + resultBuilder.Add( + new InsecureObjectGraphResult( + fieldSymbol, + null, + null, + fieldInsecureTypeSymbol)); + } + else + { + typesToRecurse.Add(fieldSymbol.Type); + } + } + + break; + + case IPropertySymbol propertySymbol: + if (!propertySymbol.IsStatic + && ((options.BinarySerialization + && hasSerializableAttribute + && !propertySymbol.HasAttribute(this.NonSerializedAttributeTypeSymbol) + && propertySymbol.IsPropertyWithBackingField() + ) + || (options.DataContractSerialization + && ((hasDataContractAttribute && propertySymbol.HasAttribute(this.DataMemberAttributeTypeSymbol)) + || (!hasDataContractAttribute && !propertySymbol.HasAttribute(this.IgnoreDataMemberTypeSymbol))) + && propertySymbol.GetMethod != null + && propertySymbol.SetMethod != null) + || (options.XmlSerialization + && !propertySymbol.HasAttribute(this.XmlSerializationAttributeTypes.XmlIgnoreAttribute) + && propertySymbol.DeclaredAccessibility == Accessibility.Public + && propertySymbol.GetMethod != null + && propertySymbol.GetMethod.DeclaredAccessibility == Accessibility.Public + && propertySymbol.SetMethod != null + && propertySymbol.SetMethod.DeclaredAccessibility == Accessibility.Public) + || (options.JavaScriptSerializer + && propertySymbol.DeclaredAccessibility == Accessibility.Public + && propertySymbol.SetMethod != null + && propertySymbol.SetMethod.DeclaredAccessibility == Accessibility.Public) + || (options.NewtonsoftJsonNetSerialization + && propertySymbol.DeclaredAccessibility == Accessibility.Public + && !propertySymbol.HasAttribute(this.JsonIgnoreAttributeTypeSymbol) + && !propertySymbol.HasAttribute(this.NonSerializedAttributeTypeSymbol)))) + { + if (this.IsTypeInsecure(propertySymbol.Type, out ITypeSymbol? propertyInsecureTypeSymbol)) + { + resultBuilder.Add( + new InsecureObjectGraphResult( + propertySymbol, + null, + null, + propertyInsecureTypeSymbol)); + } + else + { + typesToRecurse.Add(propertySymbol.Type); + } + } + + break; + } + } + + if (options.DataContractSerialization) + { + // Look through [KnownType(typeof(Whatev))] attributes. + foreach (AttributeData knownTypeAttributeData in typeSymbol.GetAttributes(this.KnownTypeAttributeTypeSymbol)) + { + if (knownTypeAttributeData.AttributeConstructor.Parameters.Length != 1 + || knownTypeAttributeData.ConstructorArguments.Length != 1 + || !(knownTypeAttributeData.ConstructorArguments[0] is TypedConstant typedConstant) + || typedConstant.Kind != TypedConstantKind.Type // Not handling the string methodName overload + || !(typedConstant.Value is ITypeSymbol typedConstantTypeSymbol)) + { + continue; + } + + if (this.IsTypeInsecure(typedConstantTypeSymbol, out ITypeSymbol? knownTypeInsecureType)) + { + resultBuilder.Add( + new InsecureObjectGraphResult( + null, + knownTypeAttributeData, + typedConstant, + knownTypeInsecureType)); + } + else + { + typesToRecurse.Add(typedConstantTypeSymbol); + } + } + } + + if (options.XmlSerialization) + { + // Look through [XmlInclude(typeof(Whatev))] attributes. + foreach (AttributeData xmlIncludeAttributeData + in typeSymbol.GetAttributes(this.XmlSerializationAttributeTypes.XmlIncludeAttribute)) + { + if (xmlIncludeAttributeData.AttributeConstructor.Parameters.Length != 1 + || xmlIncludeAttributeData.ConstructorArguments.Length != 1 + || !(xmlIncludeAttributeData.ConstructorArguments[0] is TypedConstant typedConstant) + || typedConstant.Kind != TypedConstantKind.Type + || !(typedConstant.Value is ITypeSymbol typedConstantTypeSymbol)) + { + continue; + } + + if (this.IsTypeInsecure(typedConstantTypeSymbol, out ITypeSymbol? xmlIncludeInsecureType)) + { + resultBuilder.Add( + new InsecureObjectGraphResult( + null, + xmlIncludeAttributeData, + typedConstant, + xmlIncludeInsecureType)); + } + else + { + typesToRecurse.Add(typedConstantTypeSymbol); + } + } + } + + if (options.Recurse) + { + foreach (ITypeSymbol memberTypeSymbol in typesToRecurse) + { + GetInsecureSymbol(memberTypeSymbol, visitedTypes, resultBuilder); + } + } + } + } + + /// + /// Gets "associated" types, e.g. "List<Foo<Bar[]>>" means "List<T>", "Foo<T>", and "Bar". + /// + /// Type to get associated types for. + /// Set to populate with associated types. + private static void GetAssociatedTypes( + ITypeSymbol type, + PooledSortedSet results) + { + if (type == null || !results.Add(type)) + { + return; + } + + if (type is INamedTypeSymbol namedTypeSymbol) + { + // 1. Type arguments of generic type. + if (namedTypeSymbol.IsGenericType) + { + foreach (ITypeSymbol? arg in namedTypeSymbol.TypeArguments) + { + GetAssociatedTypes(arg, results); + } + } + + // 2. The type it constructed from. + GetAssociatedTypes(namedTypeSymbol.ConstructedFrom, results); + } + else if (type is IArrayTypeSymbol arrayTypeSymbol) + { + // 3. Element type of the array. + GetAssociatedTypes(arrayTypeSymbol.ElementType, results); + } + + // 4. Base type. + GetAssociatedTypes(type.BaseType, results); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureObjectGraphResult.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureObjectGraphResult.cs new file mode 100644 index 0000000000..2dc00e8ccf --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/InsecureObjectGraphResult.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.NetCore.Analyzers.Security.Helpers +{ + internal class InsecureObjectGraphResult + { + public InsecureObjectGraphResult( + ISymbol? insecureSymbol, + AttributeData? insecureAttribute, + TypedConstant? insecureAttributeTypedConstant, + ITypeSymbol insecureType) + { + if ((insecureSymbol == null && insecureAttribute == null) + || (insecureSymbol != null && insecureAttribute != null)) + { + throw new ArgumentException("Either insecureSymbol or insecureAttribute should be non-null"); + } + + if ((insecureAttribute == null && insecureAttributeTypedConstant != null) + || (insecureAttribute != null && insecureAttributeTypedConstant == null)) + { + throw new ArgumentException( + "Both insecureAttribute and insecureAttributeTypedConstant should be null or non-null"); + } + + InsecureSymbol = insecureSymbol; + InsecureAttribute = insecureAttribute; + InsecureAttributeTypedConstant = insecureAttributeTypedConstant; + InsecureType = insecureType ?? throw new ArgumentNullException(nameof(insecureType)); + } + + /// + /// The class / struct or its member field / property referencing an insecure type. + /// + public ISymbol? InsecureSymbol { get; } + + /// + /// Attribute referencing an insecure type. + /// + public AttributeData? InsecureAttribute { get; } + + /// + /// Typed constant in the attribute referencing an insecure type. + /// + public TypedConstant? InsecureAttributeTypedConstant { get; } + + /// + /// The insecure type being referenced. + /// + public ITypeSymbol InsecureType { get; } + + /// + /// Gets the of or . + /// + /// of or . + public Location GetLocation() + { + if (this.InsecureSymbol != null) + { + return this.InsecureSymbol.DeclaringSyntaxReferences.First().GetSyntax().GetLocation(); + } + else if (this.InsecureAttribute != null) + { + return this.InsecureAttribute.ApplicationSyntaxReference.GetSyntax().GetLocation(); + } + else + { + throw new NotImplementedException("Unhandled case"); + } + } + + /// + /// Gets the display string of or . + /// + /// Display string of or . + public string GetDisplayString() + { + if (this.InsecureSymbol != null) + { + return this.InsecureSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); + } + else if (this.InsecureAttributeTypedConstant != null) + { + TypedConstant t = (TypedConstant)this.InsecureAttributeTypedConstant!; + return t.ToCSharpString(); + } + else + { + throw new NotImplementedException("Unhandled case"); + } + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/ObjectGraphOptions.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/ObjectGraphOptions.cs new file mode 100644 index 0000000000..388a1e4b72 --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/ObjectGraphOptions.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.NetCore.Analyzers.Security.Helpers +{ + /// + /// Options for walking object graphs for . + /// + internal class ObjectGraphOptions + { + public ObjectGraphOptions( + bool recurse = false, + bool binarySerialization = false, + bool dataContractSerialization = false, + bool xmlSerialization = false, + bool javaScriptSerializer = false, + bool newtonsoftJsonNetSerialization = false) + { + Recurse = recurse; + BinarySerialization = binarySerialization; + DataContractSerialization = dataContractSerialization; + XmlSerialization = xmlSerialization; + JavaScriptSerializer = javaScriptSerializer; + NewtonsoftJsonNetSerialization = newtonsoftJsonNetSerialization; + } + + /// + /// Recurse into the types of fields and properties. + /// + public bool Recurse { get; private set; } + + /// + /// "Binary" serialization, like . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Type not referenced by assembly.")] + public bool BinarySerialization { get; private set; } + + /// + /// DataContract serialization. + /// + public bool DataContractSerialization { get; private set; } + + /// + /// .NET XML serialization with . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Type not referenced by assembly.")] + public bool XmlSerialization { get; private set; } + + /// + /// Serialization with . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Type not referenced by assembly.")] + public bool JavaScriptSerializer { get; private set; } + + /// + /// Serialization with Newtonsoft Json.NET. + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Type not referenced by assembly.")] + public bool NewtonsoftJsonNetSerialization { get; private set; } + + /// + /// Options for BinarySerialization and recursing into member types. + /// + public static ObjectGraphOptions BinarySerializationOptions = new ObjectGraphOptions() + { + Recurse = true, + BinarySerialization = true, + }; + + /// + /// Options for DataContract serialization and recursing into member types. + /// + public static ObjectGraphOptions DataContractOptions = new ObjectGraphOptions() + { + Recurse = true, + DataContractSerialization = true, + }; + + /// + /// Options for XML serialization (XmlSerializer) and recursing into member types. + /// + public static ObjectGraphOptions XmlSerializerOptions = new ObjectGraphOptions() + { + Recurse = true, + XmlSerialization = true, + }; + + /// + /// Options for JavaScriptSerializer serialization and recursing into member types. + /// + public static ObjectGraphOptions JavaScriptSerializerOptions = new ObjectGraphOptions() + { + Recurse = true, + JavaScriptSerializer = true, + }; + + /// + /// Options for Newtonsoft Json.NET and recursing into member types. + /// + public static ObjectGraphOptions NewtonsoftJsonNetOptions = new ObjectGraphOptions() + { + Recurse = true, + NewtonsoftJsonNetSerialization = true, + }; + + public override bool Equals(object obj) + { + return this.Equals(obj as ObjectGraphOptions); + } + + public bool Equals(ObjectGraphOptions? other) + { + return other != null + && this.Recurse == other.Recurse + && this.BinarySerialization == other.BinarySerialization + && this.DataContractSerialization == other.DataContractSerialization + && this.JavaScriptSerializer == other.JavaScriptSerializer + && this.NewtonsoftJsonNetSerialization == other.NewtonsoftJsonNetSerialization + && this.XmlSerialization == other.XmlSerialization; + } + + public override int GetHashCode() + { + return (this.Recurse ? 1 : 0) + | (this.BinarySerialization ? 2 : 0) + | (this.DataContractSerialization ? 4 : 0) + | (this.JavaScriptSerializer ? 8 : 0) + | (this.NewtonsoftJsonNetSerialization ? 16 : 0) + | (this.XmlSerialization ? 32 : 0); + } + + /// + /// Determines if this instance is a valid argument (at least one type of serialization is specified). + /// + /// Name of the ObjectGraphOptions parameter; used in the ArgumentException. + internal void ThrowIfInvalid(string parameterName) + { + if (this.BinarySerialization + || this.DataContractSerialization + || this.XmlSerialization + || this.JavaScriptSerializer + || this.NewtonsoftJsonNetSerialization) + { + return; + } + + throw new ArgumentException("ObjectGraphOptions should specify at least one type serialization", parameterName); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/SecurityHelpers.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/SecurityHelpers.cs index 32267b2021..99bf8cc813 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/SecurityHelpers.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/SecurityHelpers.cs @@ -112,6 +112,24 @@ public static DiagnosticDescriptor CreateDiagnosticDescriptor( "Deserialize", "DeserializeObject"); + /// + /// Deserialization methods for . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + public static readonly ImmutableHashSet ObjectStateFormatterDeserializationMethods = + ImmutableHashSet.Create( + StringComparer.Ordinal, + "Deserialize"); + + /// + /// Deserialization methods for . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + public static readonly ImmutableHashSet SoapFormatterDeserializationMethods = + ImmutableHashSet.Create( + StringComparer.Ordinal, + "Deserialize"); + private static readonly ImmutableDictionary ResourceManagerMapping = ImmutableDictionary.CreateRange( new[] @@ -160,6 +178,15 @@ public static DiagnosticDescriptor CreateDiagnosticDescriptor( StringComparer.Ordinal, "ReadXml"); + /// + /// Deserialization methods for . + /// + [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")] + public static readonly ImmutableHashSet DataSetDeserializationMethods = + ImmutableHashSet.Create( + StringComparer.Ordinal, + "ReadXml"); + /// /// Gets a from . /// diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/XmlSerializationAttributeTypes.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/XmlSerializationAttributeTypes.cs new file mode 100644 index 0000000000..5027a0487d --- /dev/null +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/Helpers/XmlSerializationAttributeTypes.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Linq; +using Analyzer.Utilities; +using Microsoft.CodeAnalysis; + +namespace Microsoft.NetCore.Analyzers.Security.Helpers +{ + /// + /// Just a common way to get s for attributes that affect XML serialization. + /// + /// + /// https://docs.microsoft.com/en-us/dotnet/standard/serialization/attributes-that-control-xml-serialization + /// + public class XmlSerializationAttributeTypes + { + /// + /// Indicates that at least one attribute is defined. + /// + public bool Any { get; private set; } + + public INamedTypeSymbol? XmlAnyAttributeAttribute { get; private set; } + public INamedTypeSymbol? XmlAnyElementAttribute { get; private set; } + public INamedTypeSymbol? XmlArrayAttribute { get; private set; } + public INamedTypeSymbol? XmlArrayItemAttribute { get; private set; } + public INamedTypeSymbol? XmlAttributeAttribute { get; private set; } + public INamedTypeSymbol? XmlChoiceIdentifierAttribute { get; private set; } + public INamedTypeSymbol? XmlElementAttribute { get; private set; } + public INamedTypeSymbol? XmlEnumAttribute { get; private set; } + public INamedTypeSymbol? XmlIgnoreAttribute { get; private set; } + public INamedTypeSymbol? XmlIncludeAttribute { get; private set; } + public INamedTypeSymbol? XmlRootAttribute { get; private set; } + public INamedTypeSymbol? XmlTextAttribute { get; private set; } + public INamedTypeSymbol? XmlTypeAttribute { get; private set; } + + /// + /// Constructs. + /// + /// The compilation's . + public XmlSerializationAttributeTypes(WellKnownTypeProvider wellKnownTypeProvider) + { + this.XmlAnyAttributeAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlAnyAttributeAttribute); + this.XmlAnyElementAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlAnyElementAttribute); + this.XmlArrayAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlArrayAttribute); + this.XmlArrayItemAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlArrayItemAttribute); + this.XmlAttributeAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlAttributeAttribute); + this.XmlChoiceIdentifierAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlChoiceIdentifierAttribute); + this.XmlElementAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlElementAttribute); + this.XmlEnumAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlEnumAttribute); + this.XmlIgnoreAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlIgnoreAttribute); + this.XmlIncludeAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlIncludeAttribute); + this.XmlRootAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlRootAttribute); + this.XmlTextAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlTextAttribute); + this.XmlTypeAttribute = wellKnownTypeProvider.GetOrCreateTypeByMetadataName( + WellKnownTypeNames.SystemXmlSerializationXmlTypeAttribute); + + this.Any = + this.XmlAnyAttributeAttribute != null + || this.XmlAnyElementAttribute != null + || this.XmlArrayAttribute != null + || this.XmlArrayItemAttribute != null + || this.XmlAttributeAttribute != null + || this.XmlChoiceIdentifierAttribute != null + || this.XmlElementAttribute != null + || this.XmlEnumAttribute != null + || this.XmlIgnoreAttribute != null + || this.XmlIncludeAttribute != null + || this.XmlRootAttribute != null + || this.XmlTextAttribute != null + || this.XmlTypeAttribute != null; + } + + /// + /// Determines if the given symbol has any XML serialization attributes on it. + /// + /// Symbol whose attributes to look through. + /// True if the symbol has an XML serialization attribute on it, false otherwise. + public bool HasAnyAttribute(ISymbol symbol) + { + return symbol.GetAttributes().Any(attributeData => + attributeData.AttributeClass.Equals(this.XmlAnyAttributeAttribute) + || attributeData.AttributeClass.Equals(this.XmlAnyElementAttribute) + || attributeData.AttributeClass.Equals(this.XmlArrayAttribute) + || attributeData.AttributeClass.Equals(this.XmlArrayItemAttribute) + || attributeData.AttributeClass.Equals(this.XmlAttributeAttribute) + || attributeData.AttributeClass.Equals(this.XmlChoiceIdentifierAttribute) + || attributeData.AttributeClass.Equals(this.XmlElementAttribute) + || attributeData.AttributeClass.Equals(this.XmlEnumAttribute) + || attributeData.AttributeClass.Equals(this.XmlIgnoreAttribute) + || attributeData.AttributeClass.Equals(this.XmlIncludeAttribute) + || attributeData.AttributeClass.Equals(this.XmlRootAttribute) + || attributeData.AttributeClass.Equals(this.XmlTextAttribute) + || attributeData.AttributeClass.Equals(this.XmlTypeAttribute)); + } + } +} diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/SetHttpOnlyForHttpCookie.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/SetHttpOnlyForHttpCookie.cs index 264536e66f..e503c267c2 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/SetHttpOnlyForHttpCookie.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/SetHttpOnlyForHttpCookie.cs @@ -161,7 +161,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.SystemWebHttpCookie, ConstructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, HazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/UseSecureCookiesASPNetCore.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/UseSecureCookiesASPNetCore.cs index 477062d681..f9e90dd4d8 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/UseSecureCookiesASPNetCore.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/UseSecureCookiesASPNetCore.cs @@ -175,7 +175,6 @@ public override void Initialize(AnalysisContext context) WellKnownTypeNames.MicrosoftAspNetCoreHttpCookieOptions, constructorMapper, PropertyMappers, - InvocationMapperCollection.Empty, hazardousUsageEvaluators, InterproceduralAnalysisConfiguration.Create( compilationAnalysisContext.Options, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf index 9dcd22b568..9a5adb8bea 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf @@ -157,24 +157,64 @@ Spolehlivost - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf index 36dad2ef34..d6b4d50a7f 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf @@ -157,24 +157,64 @@ Zuverlässigkeit - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf index a374401284..428b137b41 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf @@ -157,24 +157,64 @@ Fiabilidad - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf index 8e2a98f79b..ad46723e65 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf @@ -157,24 +157,64 @@ Fiabilité - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf index ea20a530be..831bcbfe94 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf @@ -157,24 +157,64 @@ Affidabilità - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf index cb864bfdf3..9300f87dd1 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf @@ -157,24 +157,64 @@ 信頼性 - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf index 1181287c98..5b6cfc9ac1 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf @@ -157,24 +157,64 @@ 안정성 - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf index 90d3a13e71..a2e8210b99 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf @@ -157,24 +157,64 @@ Niezawodność - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf index a043161e5b..33177cae4e 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf @@ -157,24 +157,64 @@ Confiabilidade - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf index cc1a200dfc..e9a1eee8a7 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf @@ -157,24 +157,64 @@ Надежность - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf index 863fac5ddc..1a1444febd 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf @@ -157,24 +157,64 @@ Güvenilirlik - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf index 4b08e93e03..d969e75cae 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf @@ -157,24 +157,64 @@ 可靠性 - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf index 8058ed3634..0b066f6985 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf @@ -157,24 +157,64 @@ 可靠性 - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data - Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data + + Unsafe DataSet or DataTable type found in deserializable object graph + Unsafe DataSet or DataTable type found in deserializable object graph - - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. - When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. - - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data - Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data + + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable in serializable type + Unsafe DataSet or DataTable in serializable type + + + + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + + + + Unsafe DataSet or DataTable type in web deserializable object graph + Unsafe DataSet or DataTable type in web deserializable object graph + + + + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. + + + + Do not use insecure deserialization with DataSet.ReadXml() + Do not use insecure deserialization with DataSet.ReadXml() diff --git a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md index 415fb9de75..4fb4a296d5 100644 --- a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md +++ b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md @@ -5,7 +5,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 2 | [CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001) | Types that own disposable fields should be disposable | Design | True | Hidden | True | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. | 3 | [CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003) | Use generic event handler instances | Design | False | Warning | False | A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. | 4 | [CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008) | Enums should have zero value | Design | False | Warning | True | The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. | -5 | [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Collections should implement generic interface | Design | True | Hidden | False | To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types. | +5 | [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Generic interface should also be implemented | Design | True | Hidden | False | To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. | 6 | [CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012) | Abstract types should not have constructors | Design | False | Warning | True | Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. | 7 | [CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014) | Mark assemblies with CLSCompliant | Design | False | Warning | False | The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. | 8 | [CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016) | Mark assemblies with assembly version | Design | True | Info | False | The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. | @@ -81,7 +81,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 78 | [CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819) | Properties should not return arrays | Performance | False | Warning | False | Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. | 79 | [CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820) | Test for empty strings using string length | Performance | False | Warning | True | Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. | 80 | [CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821) | Remove empty Finalizers | Performance | True | Warning | True | Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. | -81 | [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Info | True | Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | +81 | [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Info | True | Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | 82 | [CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823) | Avoid unused private fields | Performance | False | Warning | True | Private fields were detected that do not appear to be accessed in the assembly. | 83 | [CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824) | Mark assemblies with NeutralResourcesLanguageAttribute | Performance | True | Info | False | The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. | 84 | [CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825) | Avoid zero-length array allocations. | Performance | True | Info | True | Avoid unnecessary zero-length array allocations. Use {0} instead. | @@ -140,68 +140,74 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Descriptio 137 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | 138 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | 139 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | Warning | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -140 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -141 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -142 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -143 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -144 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -145 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -146 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -147 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -148 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -149 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -150 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -151 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -152 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | -153 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Warning | False | Using XmlTextReader.Load(), creating an insecure XmlReaderSettings instance when invoking XmlReader.Create(), setting the InnerXml property of the XmlDocument and enabling DTD processing using XmlUrlResolver insecurely can lead to information disclosure. Replace it with a call to the Load() method overload that takes an XmlReader instance, use XmlReader.Create() to accept XmlReaderSettings arguments or consider explicitly setting secure values. The DataViewSettingCollectionString property of DataViewManager should always be assigned from a trusted source, the DtdProcessing property should be set to false, and the XmlResolver property should be changed to XmlSecureResolver or null.  | -154 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Warning | False | Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed if the input is known to be from a trusted source and external resource resolution from locations that are not known in advance must be supported. | -155 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Warning | False | Enabling DTD processing on all instances derived from XmlTextReader or  XmlDocument and using XmlUrlResolver for resolving external XML entities may lead to information disclosure. Ensure to set the XmlResolver property to null, create an instance of XmlSecureResolver when processing untrusted input, or use XmlReader.Create method with a secure XmlReaderSettings argument. Unless you need to enable it, ensure the DtdProcessing property is set to false.  | -156 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Warning | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | -157 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | -158 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | -159 | [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Do Not Use Unsafe Cipher Modes | Security | False | Warning | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -160 | [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | -161 | [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | -162 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | -163 | [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Do Not Refer Self In Serializable Class | Security | False | Warning | False | This can allow an attacker to DOS or exhaust the memory of the process. | -164 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | -165 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | -166 | [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | -167 | [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -168 | [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | -169 | [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | -170 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -171 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -172 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -173 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -174 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | -175 | [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -176 | [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | -177 | [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -178 | [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | -179 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | -180 | [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | -181 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -182 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -183 | [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -184 | [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -185 | [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | -186 | [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -187 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | -188 | [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -189 | [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -190 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -191 | [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | -192 | [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | -193 | [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -194 | [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -195 | [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | -196 | [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | -197 | [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -198 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -199 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -200 | [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -201 | [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -202 | [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -203 | [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -204 | [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | +140 | [CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350) | Do not use insecure deserialization with DataTable.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | +141 | [CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351) | Do not use insecure deserialization with DataSet.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | +142 | [CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352) | Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data | Security | False | Warning | False | When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. | +143 | [CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353) | Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data | Security | False | Warning | False | When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure. | +144 | [CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354) | Unsafe DataSet/DataTable object declared in serializable type | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +145 | [CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355) | Unsafe DataSet/DataTable type in deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | +146 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +147 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +148 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +149 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | +150 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +151 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +152 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +153 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +154 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +155 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +156 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +157 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +158 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | +159 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Warning | False | Using XmlTextReader.Load(), creating an insecure XmlReaderSettings instance when invoking XmlReader.Create(), setting the InnerXml property of the XmlDocument and enabling DTD processing using XmlUrlResolver insecurely can lead to information disclosure. Replace it with a call to the Load() method overload that takes an XmlReader instance, use XmlReader.Create() to accept XmlReaderSettings arguments or consider explicitly setting secure values. The DataViewSettingCollectionString property of DataViewManager should always be assigned from a trusted source, the DtdProcessing property should be set to false, and the XmlResolver property should be changed to XmlSecureResolver or null.  | +160 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Warning | False | Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed if the input is known to be from a trusted source and external resource resolution from locations that are not known in advance must be supported. | +161 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Warning | False | Enabling DTD processing on all instances derived from XmlTextReader or  XmlDocument and using XmlUrlResolver for resolving external XML entities may lead to information disclosure. Ensure to set the XmlResolver property to null, create an instance of XmlSecureResolver when processing untrusted input, or use XmlReader.Create method with a secure XmlReaderSettings argument. Unless you need to enable it, ensure the DtdProcessing property is set to false.  | +162 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Warning | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | +163 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | +164 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | +165 | [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Review cipher mode usage with cryptography experts | Security | False | Warning | False | These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). | +166 | [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | +167 | [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | +168 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | +169 | [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Do Not Refer Self In Serializable Class | Security | False | Warning | False | This can allow an attacker to DOS or exhaust the memory of the process. | +170 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | +171 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | +172 | [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | +173 | [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +174 | [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | +175 | [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | +176 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +177 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +178 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +179 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +180 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | +181 | [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +182 | [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | +183 | [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | +184 | [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | +185 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | +186 | [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | +187 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +188 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +189 | [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | +190 | [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | +191 | [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | +192 | [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | +193 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | +194 | [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +195 | [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +196 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +197 | [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | +198 | [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | +199 | [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +200 | [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +201 | [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | +202 | [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | +203 | [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +204 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +205 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +206 | [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +207 | [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +208 | [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | +209 | [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | +210 | [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | diff --git a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif index 500ee4d946..2c2aaa9308 100644 --- a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif +++ b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Humanizer", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -14,7 +14,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.CSharp.NetAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -377,7 +377,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.NetAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -424,8 +424,8 @@ }, "CA1010": { "id": "CA1010", - "shortDescription": "Collections should implement generic interface", - "fullDescription": "To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types.", + "shortDescription": "Generic interface should also be implemented", + "fullDescription": "To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types.", "defaultLevel": "hidden", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1010", "properties": { @@ -1782,7 +1782,7 @@ "CA1822": { "id": "CA1822", "shortDescription": "Mark members as static", - "fullDescription": "Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code.", + "fullDescription": "Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1822", "properties": { @@ -2765,6 +2765,122 @@ ] } }, + "CA2350": { + "id": "CA2350", + "shortDescription": "Do not use insecure deserialization with DataTable.ReadXml()", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2350", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataTableReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2351": { + "id": "CA2351", + "shortDescription": "Do not use insecure deserialization with DataSet.ReadXml()", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2351", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2352": { + "id": "CA2352", + "shortDescription": "Do not use DataSet.ReadXml() without ReadXmlSchema() on untrusted data", + "fullDescription": "When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2352", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXmlWithoutReadXmlSchema", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Dataflow", + "Telemetry" + ] + } + }, + "CA2353": { + "id": "CA2353", + "shortDescription": "Ensure DataSet.ReadXmlSchema() is called before ReadXml() on untrusted data", + "fullDescription": "When deserializing untrusted input, DataSet.ReadXml() without first calling DataSet.ReadXmlSchema() is insecure.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2353", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXmlWithoutReadXmlSchema", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Dataflow", + "Telemetry" + ] + } + }, + "CA2354": { + "id": "CA2354", + "shortDescription": "Unsafe DataSet/DataTable object declared in serializable type", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2354", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2355": { + "id": "CA2355", + "shortDescription": "Unsafe DataSet/DataTable type in deserializable object graph", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2355", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableObjectGraphAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA3001": { "id": "CA3001", "shortDescription": "Review code for SQL injection vulnerabilities", @@ -3102,8 +3218,8 @@ }, "CA5358": { "id": "CA5358", - "shortDescription": "Do Not Use Unsafe Cipher Modes", - "fullDescription": "These modes are vulnerable to attacks. Use only approved modes (CBC, CTS).", + "shortDescription": "Review cipher mode usage with cryptography experts", + "fullDescription": "These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS).", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5358", "properties": { @@ -3997,7 +4113,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.VisualBasic.NetAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterObjectGraphTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterObjectGraphTests.cs new file mode 100644 index 0000000000..d1058456c3 --- /dev/null +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInIFormatterObjectGraphTests.cs @@ -0,0 +1,265 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Testing; +using Test.Utilities; +using Xunit; +using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< + Microsoft.NetCore.Analyzers.Security.DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace Microsoft.NetCore.Analyzers.Security.UnitTests +{ + public class DataSetDataTableInIFormatterObjectGraphTests + { + [Fact] + public async Task BinaryFormatter_Cast_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + + public BlahClass Method(MemoryStream ms) + { + BinaryFormatter bf = new BinaryFormatter(); + BlahClass bc = (BlahClass) bf.Deserialize(ms); + return bc; + } + } +}", + GetCSharpResultAt(17, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task NetDataContractSerializer_Cast_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + + public BlahClass Method(MemoryStream ms) + { + NetDataContractSerializer ndcs = new NetDataContractSerializer(); + BlahClass bc = (BlahClass) ndcs.Deserialize(ms); + return bc; + } + } +}", + GetCSharpResultAt(17, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task ObjectStateFormatter_Cast_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Web.UI; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + + public BlahClass Method(MemoryStream ms) + { + ObjectStateFormatter osf = new ObjectStateFormatter(); + BlahClass bc = (BlahClass) osf.Deserialize(ms); + return bc; + } + } +}", + GetCSharpResultAt(17, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task SoapFormatter_Cast_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Soap; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + + public BlahClass Method(MemoryStream ms) + { + SoapFormatter sf = new SoapFormatter(); + BlahClass bc = (BlahClass) sf.Deserialize(ms); + return bc; + } + } +}", + GetCSharpResultAt(17, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task BinaryFormatter_As_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + + public BlahClass Method(MemoryStream ms) + { + BinaryFormatter bf = new BinaryFormatter(); + BlahClass bc = bf.Deserialize(ms) as BlahClass; + return bc; + } + } +}", + GetCSharpResultAt(17, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task BinaryFormatter_As_PrivateAutoProperty_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + private DataSet DS { get; } + + public BlahClass Method(MemoryStream ms) + { + BinaryFormatter bf = new BinaryFormatter(); + BlahClass bc = bf.Deserialize(ms) as BlahClass; + return bc; + } + } +}", + GetCSharpResultAt(17, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task BinaryFormatter_Cast_ReferenceLoop_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + + public BlahClass Blah; + + public BlahClass Method(MemoryStream ms) + { + BinaryFormatter bf = new BinaryFormatter(); + BlahClass bc = (BlahClass) bf.Deserialize(ms); + return bc; + } + } +}", + GetCSharpResultAt(19, 28, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task BinaryFormatter_Cast_ReferenceIndirectLoop_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public FooClass Foo; + + public BlahClass Method(MemoryStream ms) + { + BinaryFormatter bf = new BinaryFormatter(); + BlahClass bc = (BlahClass) bf.Deserialize(ms); + return bc; + } + } + + [Serializable] + public class FooClass + { + private DataTable DT; + private BlahClass Blah; + } +}", + GetCSharpResultAt(17, 28, "DataTable", "DataTable FooClass.DT")); + } + + private static async Task VerifyCSharpAnalyzerAsync(string source, params DiagnosticResult[] expected) + { + System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences + .DefaultWithSerialization + .AddAssemblies(ImmutableArray.Create("System.Web", "System.Runtime.Serialization.Formatters.Soap")), + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments) + => VerifyCS.Diagnostic(DataSetDataTableInIFormatterSerializableObjectGraphAnalyzer.ObjectGraphContainsDangerousTypeDescriptor) + .WithLocation(line, column) + .WithArguments(arguments); + } +} diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInObjectGraphTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInObjectGraphTests.cs new file mode 100644 index 0000000000..8b4dacfe95 --- /dev/null +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInObjectGraphTests.cs @@ -0,0 +1,424 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Testing; +using Test.Utilities; +using Xunit; +using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< + Microsoft.NetCore.Analyzers.Security.DataSetDataTableInSerializableObjectGraphAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace Microsoft.NetCore.Analyzers.Security.UnitTests +{ + public class DataSetDataTableInSerializableObjectGraphTests + { + [Fact] + public async Task JavaScriptSerializer_Deserialize_Generic_Diagnostic() + { + await VerifyCSharpJssAsync(@" +using System; +using System.Data; +using System.Web.Script.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(string input) + { + JavaScriptSerializer jss = new JavaScriptSerializer(); + return jss.Deserialize(input); + } + } +}", + GetCSharpResultAt(15, 20, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task JavaScriptSerializer_Deserialize_Generic_NoDiagnostic() + { + await VerifyCSharpJssAsync(@" +using System; +using System.Web.Script.Serialization; + +namespace Blah +{ + public class BlahClass + { + public object NotADataTable; + + public BlahClass Method(string input) + { + JavaScriptSerializer jss = new JavaScriptSerializer(); + return jss.Deserialize(input); + } + } +}"); + } + + [Fact] + public async Task JavaScriptSerializer_Deserialize_NonGeneric_Diagnostic() + { + await VerifyCSharpJssAsync(@" +using System; +using System.Data; +using System.Web.Script.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(string input) + { + JavaScriptSerializer jss = new JavaScriptSerializer(); + return (BlahClass) jss.Deserialize(input, typeof(BlahClass)); + } + } +}", + GetCSharpResultAt(15, 55, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task JavaScriptSerializer_Deserialize_NonGeneric_OutOfOrderArguments_Diagnostic() + { + await VerifyCSharpJssAsync(@" +using System; +using System.Data; +using System.Web.Script.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(string input) + { + JavaScriptSerializer jss = new JavaScriptSerializer(); + return (BlahClass) jss.Deserialize(targetType: typeof(BlahClass), input: input); + } + } +}", + GetCSharpResultAt(15, 60, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task JavaScriptSerializer_DeserializeObject_As_Diagnostic() + { + await VerifyCSharpJssAsync(@" +using System; +using System.Data; +using System.Web.Script.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(string input) + { + JavaScriptSerializer jss = new JavaScriptSerializer(); + return jss.DeserializeObject(input) as BlahClass; + } + } +}", + GetCSharpResultAt(15, 20, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task DataContract_Type_Diagnostic() + { + await VerifyCSharpAsync(@" +using System; +using System.Data; +using System.Runtime.Serialization; +using System.Xml; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(XmlReader reader) + { + DataContractSerializer dcs = new DataContractSerializer(typeof(BlahClass)); + return (BlahClass) dcs.ReadObject(reader); + } + } +}", + GetCSharpResultAt(15, 69, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task DataContract_Type_Types_Diagnostic() + { + await VerifyCSharpAsync(@" +using System; +using System.Data; +using System.Runtime.Serialization; +using System.Xml; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(XmlReader reader) + { + DataContractSerializer dcs = new DataContractSerializer(typeof(BlahClass), new[] { typeof(BlahClass) }); + return (BlahClass) dcs.ReadObject(reader); + } + } +}", + GetCSharpResultAt(15, 69, "DataTable", "DataTable BlahClass.DT"), + GetCSharpResultAt(15, 96, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task XmlSerializer_Constructor_Diagnostic() + { + await VerifyCSharpAsync(@" +using System; +using System.Data; +using System.Xml; +using System.Xml.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(XmlReader reader) + { + XmlSerializer xs = new XmlSerializer(typeof(BlahClass)); + return (BlahClass) xs.Deserialize(reader); + } + } +}", + GetCSharpResultAt(15, 50, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task XmlSerializer_FromType_Diagnostic() + { + await VerifyCSharpAsync(@" +using System; +using System.Data; +using System.Xml; +using System.Xml.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(XmlReader reader) + { + XmlSerializer[] xs = XmlSerializer.FromTypes(new[] { typeof(BlahClass) }); + return (BlahClass) xs[0].Deserialize(reader); + } + } +}", + GetCSharpResultAt(15, 66, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task Newtonsoft_JsonSerializer_Deserialize_Casted_Diagnostic() + { + await VerifyCSharpNewtonsoftAsync(@" +using System; +using System.Data; +using Newtonsoft.Json; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public BlahClass Method(JsonReader reader) + { + JsonSerializer js = new JsonSerializer(); + return (BlahClass) js.Deserialize(reader); + } + } +}", + GetCSharpResultAt(15, 20, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task Newtonsoft_JsonSerializer_Deserialize_TypeSpecified_Diagnostic() + { + await VerifyCSharpNewtonsoftAsync(@" +using System; +using System.Data; +using Newtonsoft.Json; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public object Method(JsonReader reader) + { + JsonSerializer js = new JsonSerializer(); + return js.Deserialize(reader, typeof(BlahClass)); + } + } +}", + GetCSharpResultAt(15, 43, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task Newtonsoft_JsonSerializer_Deserialize_TypeSpecified_OutOfOrderArguments_Diagnostic() + { + await VerifyCSharpNewtonsoftAsync(@" +using System; +using System.Data; +using Newtonsoft.Json; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + public object Method(JsonReader reader) + { + JsonSerializer js = new JsonSerializer(); + return js.Deserialize(objectType: typeof(BlahClass), reader: reader); + } + } +}", + GetCSharpResultAt(15, 47, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task Newtonsoft_JsonSerializer_Deserialize_Casted_JsonIgnore_NoDiagnostic() + { + await VerifyCSharpNewtonsoftAsync(@" +using System; +using System.Data; +using Newtonsoft.Json; + +namespace Blah +{ + public class BlahClass + { + [JsonIgnore] + public DataTable DT; + + public BlahClass Method(JsonReader reader) + { + JsonSerializer js = new JsonSerializer(); + return (BlahClass) js.Deserialize(reader); + } + } +}"); + } + + [Fact] + public async Task Newtonsoft_JsonConvert_DeserializeObject_Generic_Diagnostic() + { + await VerifyCSharpNewtonsoftAsync(@" +using System; +using System.Data; +using Newtonsoft.Json; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT { get; set; } + + public BlahClass Method(string s) + { + return JsonConvert.DeserializeObject(s); + } + } +}", + GetCSharpResultAt(14, 20, "DataTable", "DataTable BlahClass.DT")); + } + + private static async Task VerifyCSharpAsync(string source, params DiagnosticResult[] expected) + { + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences + .DefaultWithSerialization, + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + /// + /// Tests code using JavaScriptSerializer. + /// + /// Source code to test. + /// Expected diagnostics. + /// Task of the test run. + private static async Task VerifyCSharpJssAsync(string source, params DiagnosticResult[] expected) + { + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences + .DefaultWithSystemWeb + .AddAssemblies(ImmutableArray.Create("System.Data")), + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + /// + /// Tests code using Newtonsoft Json.NET. + /// + /// Source code to test. + /// Expected diagnostics. + /// Task of the test run. + private static async Task VerifyCSharpNewtonsoftAsync(string source, params DiagnosticResult[] expected) + { + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences + .DefaultWithNewtonsoftJson + .AddAssemblies(ImmutableArray.Create("System.Data")), + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments) + => VerifyCS.Diagnostic(DataSetDataTableInSerializableObjectGraphAnalyzer.ObjectGraphContainsDangerousTypeDescriptor) + .WithLocation(line, column) + .WithArguments(arguments); + } +} diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeTests.cs new file mode 100644 index 0000000000..6306c19928 --- /dev/null +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInSerializableTypeTests.cs @@ -0,0 +1,406 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Testing; +using Test.Utilities; +using Xunit; +using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< + Microsoft.NetCore.Analyzers.Security.DataSetDataTableInSerializableTypeAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace Microsoft.NetCore.Analyzers.Security.UnitTests +{ + public class DataSetDataTableInSerializableTypeTests + { + [Fact] + public async Task Serializable_Field_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS; + } +}", + GetIFormatterCSharpResultAt(10, 24, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task DataContract_Field_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Runtime.Serialization; + +namespace Blah +{ + [DataContract] + public class BlahClass + { + [DataMember] + public DataSet DS; + } +}", + GetNonIFormatterCSharpResultAt(11, 24, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task IgnoreDataMemberOnDataTable_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Runtime.Serialization; + +namespace Blah +{ + public class BlahClass + { + [IgnoreDataMember] + public DataTable DT; + + public int I; + } +}"); + } + + [Fact] + public async Task IgnoreDataMemberOnNotDataTable_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Runtime.Serialization; + +namespace Blah +{ + public class BlahClass + { + public DataTable DT; + + [IgnoreDataMember] + public int I; + } +}", + GetNonIFormatterCSharpResultAt(9, 26, "DataTable", "DataTable BlahClass.DT")); + } + + [Fact] + public async Task DataContract_PrivateProperty_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Runtime.Serialization; + +namespace Blah +{ + [DataContract] + public class BlahClass + { + [DataMember] + private DataSet DS { get; set; } + } +}", + GetNonIFormatterCSharpResultAt(10, 9, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task DataContract_KnownType_DataTable_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Runtime.Serialization; + +namespace Blah +{ + [DataContract] + [KnownType(typeof(DataTable))] + public class BlahClass + { + [DataMember] + public object DT; + } +}", + GetNonIFormatterCSharpResultAt(8, 6, "DataTable", "typeof(System.Data.DataTable)")); + } + + [Fact] + public async Task DataContract_InheritedKnownType_DataTable_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Runtime.Serialization; + +namespace Blah +{ + [KnownType(typeof(DataTable))] + public class BlahBase + { + public object DT; + } + + [DataContract] + public class BlahClass : BlahBase + { + } +}", + GetNonIFormatterCSharpResultAt(7, 6, "DataTable", "typeof(System.Data.DataTable)")); + } + + [Fact] + public async Task Serializable_FieldDerivedClass_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + public class MyDataSet : DataSet + { + } + + [Serializable] + public class BlahClass + { + public MyDataSet DS; + } +}", + GetIFormatterCSharpResultAt(14, 26, "DataSet", "MyDataSet BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PrivateField_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + private DataSet DS; + } +}", + GetIFormatterCSharpResultAt(10, 25, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task Serializable_Property_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(10, 9, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PropertyDerived_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + public class MyDataSet : DataSet + { + } + + [Serializable] + public class BlahClass + { + public MyDataSet DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(14, 9, "DataSet", "MyDataSet BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PropertyList_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Collections.Generic; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public List DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(11, 9, "DataSet", "List BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PropertyListListList_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Collections.Generic; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public List>> DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(11, 9, "DataSet", "List>> BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PropertyArray_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet[] DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(10, 9, "DataSet", "DataSet[] BlahClass.DS")); + } + + [Fact] + public async Task Serializable_Property2DArray_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet[,] DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(10, 9, "DataSet", "DataSet[,] BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PropertyArrayArray_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet[][] DS { get; set; } + } +}", + GetIFormatterCSharpResultAt(10, 9, "DataSet", "DataSet[][] BlahClass.DS")); + } + + [Fact] + public async Task Serializable_PropertyNoExplicitSetter_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System; +using System.Data; + +namespace Blah +{ + [Serializable] + public class BlahClass + { + public DataSet DS { get; } + } +}", + GetIFormatterCSharpResultAt(10, 9, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task XmlElement_Property_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Xml.Serialization; + +namespace Blah +{ + public class BlahClass + { + [XmlElement] + public DataSet DS { get; set; } + } +}", + GetNonIFormatterCSharpResultAt(9, 9, "DataSet", "DataSet BlahClass.DS")); + } + + [Fact] + public async Task XmlIgnore_Property_Diagnostic() + { + await VerifyCSharpAnalyzerAsync(@" +using System.Data; +using System.Xml.Serialization; + +namespace Blah +{ + [XmlRoot] + public class BlahClass + { + [XmlIgnore] + public DataSet DS { get; set; } + } +}"); + } + + private static async Task VerifyCSharpAnalyzerAsync(string source, params DiagnosticResult[] expected) + { + System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithSerialization, + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + private static DiagnosticResult GetNonIFormatterCSharpResultAt(int line, int column, params string[] arguments) + => VerifyCS.Diagnostic(DataSetDataTableInSerializableTypeAnalyzer.SerializableContainsDangerousType) + .WithLocation(line, column) + .WithArguments(arguments); + + private static DiagnosticResult GetIFormatterCSharpResultAt(int line, int column, params string[] arguments) + => VerifyCS.Diagnostic(DataSetDataTableInSerializableTypeAnalyzer.RceSerializableContainsDangerousType) + .WithLocation(line, column) + .WithArguments(arguments); + } +} diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphTests.cs new file mode 100644 index 0000000000..690dfeaf50 --- /dev/null +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DataSetDataTableInWebSerializableObjectGraphTests.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Testing; +using Test.Utilities; +using Xunit; +using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< + Microsoft.NetCore.Analyzers.Security.DataSetDataTableInWebSerializableObjectGraphAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace Microsoft.NetCore.Analyzers.Security.UnitTests +{ + public class DataSetDataTableInWebSerializableObjectGraphTests + { + [Fact] + public async Task WebServiceDirectlyReferences() + { + await VerifyWebServicesCSharpAsync(@" +using System; +using System.Data; +using System.Web.Services; + +[WebService(Namespace = ""http://contoso.example.com/"")] +public class MyService : WebService +{ + [WebMethod] + public string MyWebMethod(DataTable dataTable) + { + return null; + } +} +", + GetCSharpResultAt(10, 31, "DataTable", "DataTable")); + } + + [Fact] + public async Task WebServiceIndirectlyReferences() + { + await VerifyWebServicesCSharpAsync(@" +using System; +using System.Data; +using System.Web.Services; + +[WebService(Namespace = ""http://contoso.example.com/"")] +public class MyService : WebService +{ + [WebMethod] + public string MyWebMethod(MyType boo) + { + return null; + } +} + +public class MyType +{ + public DataSet DS { get; set; } +} +", + GetCSharpResultAt(10, 31, "DataSet", "DataSet MyType.DS")); + } + + [Fact] + public async Task OperationContract() + { + await VerifyServiceModelCSharpAsync(@" +using System; +using System.Data; +using System.ServiceModel; + +[ServiceContract(Namespace = ""http://contoso.example.com/"")] +public interface IMyContract +{ + [OperationContract] + string MyMethod(DataTable dataTable); + [OperationContract] + string MyOtherMethod(MyClass data); +} + +public class MyClass +{ + // Property of type DataSet, automatically serialized and + // deserialized as part of the overall MyClass payload. + public DataSet MyDataSet { get; set; } +} +", + GetCSharpResultAt(10, 21, "DataTable", "DataTable"), + GetCSharpResultAt(12, 26, "DataSet", "DataSet MyClass.MyDataSet")); + } + + private static async Task VerifyServiceModelCSharpAsync(string source, params DiagnosticResult[] expected) + { + System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default.AddAssemblies( + ImmutableArray.Create("System.Data", "System.ServiceModel")), + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + private static async Task VerifyWebServicesCSharpAsync(string source, params DiagnosticResult[] expected) + { + System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; + var csharpTest = new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default.AddAssemblies( + ImmutableArray.Create("System.Data", "System.Web.Services")), + TestState = + { + Sources = { source }, + } + }; + + csharpTest.ExpectedDiagnostics.AddRange(expected); + + await csharpTest.RunAsync(); + } + + private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments) + => VerifyCS.Diagnostic(DataSetDataTableInWebSerializableObjectGraphAnalyzer.ObjectGraphContainsDangerousTypeDescriptor) + .WithLocation(line, column) + .WithArguments(arguments); + } +} diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXmlTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXmlTests.cs new file mode 100644 index 0000000000..ca6e0022ff --- /dev/null +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/DoNotUseDataSetReadXmlTests.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Testing; +using Xunit; +using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< + Microsoft.NetCore.Analyzers.Security.DoNotUseDataSetReadXml, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace Microsoft.NetCore.Analyzers.Security.UnitTests +{ + public class DoNotUseDataSetReadXmlTests + { + [Fact] + public async Task ReadXml_Diagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System.IO; +using System.Data; + +namespace Blah +{ + public class Program + { + public void Unsafe(Stream s) + { + DataSet dataSet = new DataSet(); + dataSet.ReadXml(s); + } + } +}", + GetCSharpResultAt(12, 13, "XmlReadMode DataSet.ReadXml(Stream stream)")); + } + + [Fact] + public async Task DerivedReadXml_Diagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System.IO; +using System.Data; + +namespace Blah +{ + public class Program + { + public void Unsafe(string s) + { + MyDataSet dataSet = new MyDataSet(); + dataSet.ReadXml(s); + } + } + + public class MyDataSet : DataSet + { + } +}", + GetCSharpResultAt(12, 13, "XmlReadMode DataSet.ReadXml(string fileName)")); + } + + [Fact] + public async Task DerivedReadXmlEvenWithReadXmlSchema_Diagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System.IO; +using System.Data; + +namespace Blah +{ + public class Program + { + public void Unsafe(string s) + { + MyDataSet dataSet = new MyDataSet(); + dataSet.ReadXmlSchema(""""); + dataSet.ReadXml(s); + } + } + + public class MyDataSet : DataSet + { + } +}", + GetCSharpResultAt(13, 13, "XmlReadMode DataSet.ReadXml(string fileName)")); + } + + [Fact] + public async Task RejectChanges_NoDiagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System.IO; +using System.Data; + +namespace Blah +{ + public class Program + { + public void Safe(Stream s) + { + DataSet dataSet = new DataSet(); + dataSet.RejectChanges(); + } + } +}"); + } + + private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments) + => VerifyCS.Diagnostic(DoNotUseDataSetReadXml.RealMethodUsedDescriptor) + .WithLocation(line, column) + .WithArguments(arguments); + } +} diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingXmlTextReaderConstructedWithNoSecureResolutionTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingXmlTextReaderConstructedWithNoSecureResolutionTests.cs index f0fa119fdf..60d7bb794f 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingXmlTextReaderConstructedWithNoSecureResolutionTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingXmlTextReaderConstructedWithNoSecureResolutionTests.cs @@ -1280,6 +1280,31 @@ End Class ); } + [Fact] + public async Task ConstructXmlTextReaderOnlySetDtdProcessingProhibitTargetFx451ShouldNotGenerateDiagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System; +using System.Reflection; +using System.Xml; + +[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute("".NETFramework,Version=v4.5.1"", FrameworkDisplayName = "".NET Framework 4.5.1"")] + +namespace TestNamespace +{ + public class TestClass + { + public void TestMethod(string path) + { + XmlTextReader reader = new XmlTextReader(path); + reader.DtdProcessing = DtdProcessing.Prohibit; + } + } +} +" + ); + } + [Fact] public async Task ConstructXmlTextReaderOnlySetDtdProcessingProhibitTargetFx46ShouldNotGenerateDiagnostic() { diff --git a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md index ef4cae4542..195e058e4c 100644 --- a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md +++ b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md @@ -1,7 +1,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | --------|---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -1 | HAA0101 | Array allocation for params parameter | Performance | True | Warning | False | This call site is calling into a function with a 'params' parameter. This results in an array allocation even if no parameter is passed in for the params parameter | +1 | HAA0101 | Array allocation for params parameter | Performance | True | Warning | False | This call site is calling into a function with a 'params' parameter. This results in an array allocation | 2 | HAA0102 | Non-overridden virtual method call on value type | Performance | True | Warning | False | Non-overridden virtual method call on a value type adds a boxing or constrained instruction | 3 | [HAA0201](http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.110).aspx) | Implicit string concatenation allocation | Performance | True | Warning | False | Considering using StringBuilder | 4 | [HAA0202](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx) | Value type to reference type conversion allocation for string concatenation | Performance | True | Warning | False | Value type ({0}) is being boxed to a reference type for a string concatenation. | diff --git a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif index 33686ef21f..f5c6dd9653 100644 --- a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif +++ b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif @@ -5,14 +5,14 @@ { "tool": { "name": "Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { "HAA0101": { "id": "HAA0101", "shortDescription": "Array allocation for params parameter", - "fullDescription": "This call site is calling into a function with a 'params' parameter. This results in an array allocation even if no parameter is passed in for the params parameter", + "fullDescription": "This call site is calling into a function with a 'params' parameter. This results in an array allocation", "defaultLevel": "warning", "properties": { "category": "Performance", @@ -184,7 +184,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.sarif b/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.sarif index e3993fb428..3e16a7bad0 100644 --- a/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.sarif +++ b/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.PublicApiAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -147,7 +147,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.PublicApiAnalyzers.CodeFixes", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.sarif b/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.sarif index 58f7b81164..7825bf9bc3 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.sarif +++ b/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.sarif @@ -5,7 +5,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.BannedApiAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -14,7 +14,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.CSharp.BannedApiAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -76,7 +76,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.PublicApiAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -218,7 +218,7 @@ { "tool": { "name": "Microsoft.CodeAnalysis.VisualBasic.BannedApiAnalyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -280,7 +280,7 @@ { "tool": { "name": "Roslyn.Diagnostics.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -379,7 +379,7 @@ { "tool": { "name": "Roslyn.Diagnostics.CSharp.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { @@ -473,7 +473,7 @@ { "tool": { "name": "Roslyn.Diagnostics.VisualBasic.Analyzers", - "version": "2.9.9", + "version": "2.9.10", "language": "en-US" }, "rules": { diff --git a/src/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs b/src/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs index ee9d07bcd0..5b648e458d 100644 --- a/src/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs +++ b/src/Test.Utilities/CSharpCodeFixVerifier`2+Test.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Net; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; @@ -14,6 +15,18 @@ public static partial class CSharpCodeFixVerifier { public class Test : CSharpCodeFixTest { + static Test() + { + // If we have outdated defaults from the host unit test application targeting an older .NET Framework, use more + // reasonable TLS protocol version for outgoing connections. +#pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols + if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls)) +#pragma warning restore CA5364 // Do Not Use Deprecated Security Protocols + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + } + } + public Test() { ReferenceAssemblies = AdditionalMetadataReferences.Default; diff --git a/src/Test.Utilities/CSharpSecurityCodeFixVerifier`2+Test.cs b/src/Test.Utilities/CSharpSecurityCodeFixVerifier`2+Test.cs index ffed12c8cd..be0eaa1532 100644 --- a/src/Test.Utilities/CSharpSecurityCodeFixVerifier`2+Test.cs +++ b/src/Test.Utilities/CSharpSecurityCodeFixVerifier`2+Test.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; +using System.Net; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; @@ -15,6 +16,18 @@ public static partial class CSharpSecurityCodeFixVerifier { public class Test : CSharpCodeFixVerifier.Test { + static Test() + { + // If we have outdated defaults from the host unit test application targeting an older .NET Framework, use more + // reasonable TLS protocol version for outgoing connections. +#pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols + if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls)) +#pragma warning restore CA5364 // Do Not Use Deprecated Security Protocols + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + } + } + public Test() { // These analyzers run on generated code by default. diff --git a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs index 41f69ce379..3e19e4633d 100644 --- a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs +++ b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs @@ -32,24 +32,17 @@ public class PropertySetAnalysisTests /// private class PropertySetAnalysisParameters { - public PropertySetAnalysisParameters( - string typeToTrack, - ConstructorMapper constructorMapper, - PropertyMapperCollection propertyMapperCollection, - InvocationMapperCollection invocationMapperCollection, - HazardousUsageEvaluatorCollection hazardousUsageEvaluatorCollection) + public PropertySetAnalysisParameters(string typeToTrack, ConstructorMapper constructorMapper, PropertyMapperCollection propertyMapperCollection, HazardousUsageEvaluatorCollection hazardousUsageEvaluatorCollection) { TypesToTrack = new string[] { typeToTrack }.ToImmutableHashSet() ?? throw new ArgumentNullException(nameof(typeToTrack)); ConstructorMapper = constructorMapper ?? throw new ArgumentNullException(nameof(constructorMapper)); PropertyMapperCollection = propertyMapperCollection ?? throw new ArgumentNullException(nameof(propertyMapperCollection)); - InvocationMapperCollection = invocationMapperCollection ?? throw new ArgumentNullException(nameof(invocationMapperCollection)); HazardousUsageEvaluatorCollection = hazardousUsageEvaluatorCollection ?? throw new ArgumentNullException(nameof(hazardousUsageEvaluatorCollection)); } public ImmutableHashSet TypesToTrack { get; } public ConstructorMapper ConstructorMapper { get; } public PropertyMapperCollection PropertyMapperCollection { get; } - public InvocationMapperCollection InvocationMapperCollection { get; } public HazardousUsageEvaluatorCollection HazardousUsageEvaluatorCollection { get; } } @@ -58,7 +51,7 @@ public PropertySetAnalysisParameters( /// /// C# source code, with /*<bind>*/ and /*</bind>*/ around the method block to be analyzed. /// PropertySetAnalysis parameters. - /// Expected hazardous usages (MethodName = null => return statement / initialization). + /// Expected hazardous usages (MethodName = null => return statement). private void VerifyCSharp( string source, PropertySetAnalysisParameters propertySetAnalysisParameters, @@ -95,7 +88,6 @@ private void VerifyCSharp( propertySetAnalysisParameters.TypesToTrack, propertySetAnalysisParameters.ConstructorMapper, propertySetAnalysisParameters.PropertyMapperCollection, - propertySetAnalysisParameters.InvocationMapperCollection, propertySetAnalysisParameters.HazardousUsageEvaluatorCollection, InterproceduralAnalysisConfiguration.Create( new AnalyzerOptions(ImmutableArray.Empty), @@ -180,14 +172,6 @@ public class TestTypeToTrack public void Method() { } - - public void MakeSafe() - { - } - - public void AnotherMethod() - { - } } public class TestTypeToTrackWithConstructor : TestTypeToTrack @@ -249,7 +233,6 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) _ => PropertySetAbstractValueKind.Unknown, }; })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", @@ -447,7 +430,6 @@ void TestMethod() _ => PropertySetAbstractValueKind.Unknown, }; })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( "Method", @@ -547,7 +529,6 @@ void TestMethod() { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, v => v.Equals(0)); })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", @@ -621,7 +602,6 @@ void TestMethod() { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, v => v.Equals(0)); })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", @@ -695,7 +675,6 @@ void TestMethod() { return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, v => v.Equals(2)); })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( "Method", @@ -883,7 +862,6 @@ void TestMethod() return kind; })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", @@ -988,7 +966,6 @@ void TestMethod() valueContentAbstractValue, v => (v as string)?.StartsWith("A", StringComparison.Ordinal) == true); })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrackWithConstructor.Method() is invoked, need to evaluate its state. "Method", @@ -1071,7 +1048,6 @@ TestTypeToTrackWithConstructor GetTestType() _ => PropertySetAbstractValueKind.Unknown, }; })), - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( HazardousUsageEvaluatorKind.Return, @@ -1190,7 +1166,6 @@ object TestMethod() }; }, propertyIndex: 0)), // Both AString and AnObject point to index 0. - InvocationMapperCollection.Empty, new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. "Method", @@ -1293,152 +1268,6 @@ void TestMethod() TestTypeToTrack_HazardousIfStringObjectIsNonNull); } - /// - /// Parameters for PropertySetAnalysis to flag hazardous usage when calling its Method() method unless its MakeUnsafe() - /// method was called before. - /// - private readonly PropertySetAnalysisParameters TestTypeToTrack_HazardousUnlessMakeSafeCalled = - new PropertySetAnalysisParameters( - "TestTypeToTrack", - new ConstructorMapper( // Start off with MakeUnsafe() not being called yet. - ImmutableArray.Create( - PropertySetAbstractValueKind.Flagged)), - new PropertyMapperCollection( - new PropertyMapper( // Dummy property whose abstract value is set by the InvocationMapper below. - "...dummy", - (PointsToAbstractValue pointsToAbstractValue) => - { - // Shouldn't be called, since no property assignments to "...dummy". - return PropertySetAbstractValueKind.Unknown; - }, - propertyIndex: 0)), - new InvocationMapperCollection( - new InvocationMapper( - "MakeSafe", - (IMethodSymbol method) => - { - // In practice, make sure we're looking at the correct method. - return true; - }, - (PropertySetAbstractValue previousAbstractValue, - IMethodSymbol method, - IReadOnlyList argumentPointsToAbstractValues) => - { - // Any method invocation to MakeSafe() will unflag the property at index 0 (same propertyIndex as - // "...dummy" above). - return previousAbstractValue.ReplaceAt( - propertyIndex: 0, - kind: PropertySetAbstractValueKind.Unflagged); - } - )), - new HazardousUsageEvaluatorCollection( - new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. - "Method", - (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => - { - // When doing this for reals, need to examine the method to make sure we're looking at the right - // method and arguments. - - // With only one property being tracked, this is straightforward. - return (abstractValue[0]) switch - { - PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, - PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, - _ => HazardousUsageEvaluationResult.Unflagged, - }; - }) - )); - - [Fact] - public void TestTypeToTrack_HazardousUnlessMakeSafeCalled_OneInstanceFlagged() - { - VerifyCSharp(@" -class TestClass -{ - void TestMethod() - /**/{ - TestTypeToTrack t = new TestTypeToTrack(); - t.Method(); - }/**/ -}", - TestTypeToTrack_HazardousUnlessMakeSafeCalled, - (7, 9, "void TestTypeToTrack.Method()", HazardousUsageEvaluationResult.Flagged)); - } - - [Fact] - public void TestTypeToTrack_HazardousUnlessMakeSafeCalled_OneInstanceAnotherMethodFlagged() - { - VerifyCSharp(@" -class TestClass -{ - void TestMethod() - /**/{ - TestTypeToTrack t = new TestTypeToTrack(); - t.AnotherMethod(); - t.Method(); - }/**/ -}", - TestTypeToTrack_HazardousUnlessMakeSafeCalled, - (8, 9, "void TestTypeToTrack.Method()", HazardousUsageEvaluationResult.Flagged)); - } - - [Fact] - public void TestTypeToTrack_HazardousUnlessMakeSafeCalled_OneInstanceUnflagged() - { - VerifyCSharp(@" -class TestClass -{ - void TestMethod() - /**/{ - TestTypeToTrack t = new TestTypeToTrack(); - t.MakeSafe(); - t.Method(); - }/**/ -}", - TestTypeToTrack_HazardousUnlessMakeSafeCalled); - } - - [Fact] - public void TestTypeToTrack_HazardousUnlessMakeSafeCalled_TwoInstancesUnflagged() - { - VerifyCSharp(@" -class TestClass -{ - void TestMethod() - /**/{ - TestTypeToTrack s = new TestTypeToTrack(); - s.MakeSafe(); - TestTypeToTrack u = new TestTypeToTrack(); - TestTypeToTrack t = new TestTypeToTrack(); - t.AnotherMethod(); - t = s; - t.Method(); - }/**/ -}", - TestTypeToTrack_HazardousUnlessMakeSafeCalled); - } - - [Fact] - public void TestTypeToTrack_HazardousUnlessMakeSafeCalled_TwoInstancesFlagged() - { - VerifyCSharp(@" -class TestClass -{ - void TestMethod() - /**/{ - TestTypeToTrack s = new TestTypeToTrack(); - s.MakeSafe(); - TestTypeToTrack u = new TestTypeToTrack(); - TestTypeToTrack t = new TestTypeToTrack(); - t.AnotherMethod(); - t = u; - t.Method(); - }/**/ -}", - TestTypeToTrack_HazardousUnlessMakeSafeCalled, - (12, 9, "void TestTypeToTrack.Method()", HazardousUsageEvaluationResult.Flagged)); - } - #region Infrastructure private ITestOutputHelper TestOutput { get; } diff --git a/src/Utilities/Compiler/Analyzer.Utilities.projitems b/src/Utilities/Compiler/Analyzer.Utilities.projitems index 4d991f3466..44f138bbbf 100644 --- a/src/Utilities/Compiler/Analyzer.Utilities.projitems +++ b/src/Utilities/Compiler/Analyzer.Utilities.projitems @@ -77,9 +77,12 @@ + + + diff --git a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs index 7c1f6250ae..c716a7381e 100644 --- a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs +++ b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs @@ -690,6 +690,38 @@ public static IOperation WalkUpConversion(this IOperation operation) return thrownObject?.Type; } + + /// + /// Determines if the one of the invocation's arguments' values is an argument of the specified type, and if so, find + /// the first one. + /// + /// Invocation operation whose arguments to look through. + /// First found IArgumentOperation.Value of the specified type, order by the method's + /// signature's parameters (as opposed to how arguments are specified when invoked). + /// True if one is found, false otherwise. + /// + /// IInvocationOperation.Arguments are ordered by how they are specified, which may differ from the order in the method + /// signature if the caller specifies arguments by name. This will find the first typeof operation ordered by the + /// method signature's parameters. + /// + public static bool HasArgument( + this IInvocationOperation invocationOperation, + [NotNullWhen(returnValue: true)] out TOperation? firstFoundArgument) + where TOperation : class, IOperation + { + firstFoundArgument = null; + int minOrdinal = int.MaxValue; + foreach (IArgumentOperation argumentOperation in invocationOperation.Arguments) + { + if (argumentOperation.Parameter.Ordinal < minOrdinal && argumentOperation.Value is TOperation to) + { + minOrdinal = argumentOperation.Parameter.Ordinal; + firstFoundArgument = to; + } + } + + return firstFoundArgument != null; + } } } diff --git a/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs b/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs index df26e28a29..aa581d8673 100644 --- a/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs +++ b/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs @@ -112,6 +112,30 @@ public static bool IsPropertyWithBackingField([NotNullWhen(returnValue: true)] t propertySymbol.ContainingType.GetMembers().OfType().Any(f => f.IsImplicitlyDeclared && Equals(f.AssociatedSymbol, symbol)); } + /// + /// Determines if the given symbol is a backing field for a property. + /// + /// This symbol to check. + /// The property that this field symbol is backing. + /// True if the given symbol is a backing field for a property, false otherwise. + public static bool IsBackingFieldForProperty( + [NotNullWhen(returnValue: true)] this ISymbol? symbol, + [NotNullWhen(returnValue: true)] out IPropertySymbol? propertySymbol) + { + if (symbol is IFieldSymbol fieldSymbol + && fieldSymbol.IsImplicitlyDeclared + && fieldSymbol.AssociatedSymbol is IPropertySymbol p) + { + propertySymbol = p; + return true; + } + else + { + propertySymbol = null; + return false; + } + } + public static bool IsUserDefinedOperator([NotNullWhen(returnValue: true)] this ISymbol? symbol) { return (symbol as IMethodSymbol)?.MethodKind == MethodKind.UserDefinedOperator; @@ -654,6 +678,48 @@ public static bool HasAttribute(this ISymbol symbol, [NotNullWhen(returnValue: t return attribute != null && symbol.GetAttributes().Any(attr => attr.AttributeClass.Equals(attribute)); } + /// + /// Determines if the given symbol has the specified attributes. + /// + /// Symbol to examine. + /// Type symbols of the attributes to check for. + /// Boolean array, same size and order as , indicating that the corresponding + /// attirbute is present. + public static bool[] HasAttributes(this ISymbol symbol, params INamedTypeSymbol?[] attributes) + { + bool[] isAttributePresent = new bool[attributes.Length]; + foreach (var attributeData in symbol.GetAttributes()) + { + for (int i = 0; i < attributes.Length; i++) + { + if (attributeData.AttributeClass.Equals(attributes[i])) + { + isAttributePresent[i] = true; + } + } + } + + return isAttributePresent; + } + + + /// + /// Gets enumeration of attributes that are of the specified type. + /// + /// This symbol whose attributes to get. + /// Type of attribute to look for. + /// Enumeration of attributes. + [SuppressMessage("RoslyDiagnosticsPerformance", "RS0001:Use SpecializedCollections.EmptyEnumerable()", Justification = "Not available in all projects")] + public static IEnumerable GetAttributes(this ISymbol symbol, INamedTypeSymbol? attributeType) + { + if (attributeType == null) + { + return Enumerable.Empty(); + } + + return symbol.GetAttributes().Where(attr => attr.AttributeClass.Equals(attributeType)); + } + /// /// Indicates if a symbol has at least one location in source. /// diff --git a/src/Utilities/Compiler/PooledObjects/PooledHashSet.cs b/src/Utilities/Compiler/PooledObjects/PooledHashSet.cs index 3ed9d4a19d..98a42cbdc2 100644 --- a/src/Utilities/Compiler/PooledObjects/PooledHashSet.cs +++ b/src/Utilities/Compiler/PooledObjects/PooledHashSet.cs @@ -13,7 +13,6 @@ namespace Analyzer.Utilities.PooledObjects { // HashSet that can be recycled via an object pool - // NOTE: these HashSets always have the default comparer. internal sealed class PooledHashSet : HashSet, IDisposable { private readonly ObjectPool>? _pool; diff --git a/src/Utilities/Compiler/PooledObjects/PooledSortedSet.cs b/src/Utilities/Compiler/PooledObjects/PooledSortedSet.cs new file mode 100644 index 0000000000..3f012cc2f0 --- /dev/null +++ b/src/Utilities/Compiler/PooledObjects/PooledSortedSet.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; + +#pragma warning disable CA1000 // Do not declare static members on generic types + +namespace Analyzer.Utilities.PooledObjects +{ + /// + /// Pooled . + /// + /// Type of elements in the set. + internal sealed class PooledSortedSet : SortedSet, IDisposable + { + private readonly ObjectPool>? _pool; + + public PooledSortedSet(ObjectPool>? pool, IComparer? comparer = null) + : base(comparer) + { + _pool = pool; + } + + public void Dispose() => Free(); + + public void Free() + { + this.Clear(); + _pool?.Free(this); + } + + // global pool + private static readonly ObjectPool> s_poolInstance = CreatePool(); + private static readonly ConcurrentDictionary, ObjectPool>> s_poolInstancesByComparer + = new ConcurrentDictionary, ObjectPool>>(); + + private static ObjectPool> CreatePool(IComparer? comparer = null) + { + ObjectPool>? pool = null; + pool = new ObjectPool>( + () => new PooledSortedSet(pool, comparer), + 128); + return pool; + } + + /// + /// Gets a pooled instance of a with an optional comparer. + /// + /// Comparer to use, or null for the element type's default comparer. + /// An empty . + public static PooledSortedSet GetInstance(IComparer? comparer = null) + { + var pool = comparer == null ? + s_poolInstance : + s_poolInstancesByComparer.GetOrAdd(comparer, c => CreatePool(c)); + var instance = pool.Allocate(); + Debug.Assert(instance.Count == 0); + return instance; + } + } +} diff --git a/src/Utilities/Compiler/SymbolByDisplayStringComparer.cs b/src/Utilities/Compiler/SymbolByDisplayStringComparer.cs new file mode 100644 index 0000000000..d1307f86b4 --- /dev/null +++ b/src/Utilities/Compiler/SymbolByDisplayStringComparer.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace Analyzer.Utilities +{ + /// + /// for s sorted by display strings. + /// +#pragma warning disable CA1812 // Is too instantiated. + internal class SymbolByDisplayStringComparer : IComparer +#pragma warning restore CA1812 + { + /// + /// Constructs. + /// + /// The compilation containing the types to be compared. + public SymbolByDisplayStringComparer(Compilation compilation) + : this(SymbolDisplayStringCache.GetOrCreate(compilation)) + { + } + + /// + /// Constructs. + /// + /// The cache display strings to use. + public SymbolByDisplayStringComparer(SymbolDisplayStringCache symbolDisplayStringCache) + { + this.SymbolDisplayStringCache = symbolDisplayStringCache ?? throw new ArgumentNullException(nameof(symbolDisplayStringCache)); + } + + /// + /// Cache of symbol display strings. + /// + public SymbolDisplayStringCache SymbolDisplayStringCache { get; } + + /// + /// Compares two type symbols by their display strings. + /// + /// First type symbol to compare. + /// Second type symbol to compare. + /// Less than 0 if is before , 0 if equal, greater than 0 if + /// is after . + public int Compare(ITypeSymbol x, ITypeSymbol y) + { + return StringComparer.Ordinal.Compare( + this.SymbolDisplayStringCache.GetDisplayString(x), + this.SymbolDisplayStringCache.GetDisplayString(y)); + } + } +} diff --git a/src/Utilities/Compiler/SymbolDisplayNameCache.cs b/src/Utilities/Compiler/SymbolDisplayNameCache.cs new file mode 100644 index 0000000000..5c38e98418 --- /dev/null +++ b/src/Utilities/Compiler/SymbolDisplayNameCache.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Concurrent; +using Microsoft.CodeAnalysis; + +namespace Analyzer.Utilities +{ + /// + /// Cache ISymbol.ToDisplayName() results, to avoid performance concerns. + /// + public sealed class SymbolDisplayNameCache + { + private static readonly BoundedCacheWithFactory s_byCompilationCache = + new BoundedCacheWithFactory(); + + /// + /// Mapping of a symbol to its ToDisplayString(). + /// + private readonly ConcurrentDictionary SymbolToDisplayNames = + new ConcurrentDictionary(); + + + private SymbolDisplayNameCache() + { + } + + /// + /// Gets the symbol display string cache for the compilation. + /// + /// + /// + public static SymbolDisplayNameCache GetOrCreate(Compilation compilation) + { + return s_byCompilationCache.GetOrCreateValue(compilation, CreateSymbolDisplayNameCache); + + // Local functions + static SymbolDisplayNameCache CreateSymbolDisplayNameCache(Compilation compilation) + => new SymbolDisplayNameCache(); + } + + /// + /// Gets the symbol's display string. + /// + /// Symbol to get the display string. + /// The symbol's display string. + public string GetDisplayString(ISymbol symbol) + { + return this.SymbolToDisplayNames.GetOrAdd(symbol, s => s.ToDisplayString()); + } + } +} diff --git a/src/Utilities/Compiler/SymbolDisplayStringCache.cs b/src/Utilities/Compiler/SymbolDisplayStringCache.cs new file mode 100644 index 0000000000..d73f09c121 --- /dev/null +++ b/src/Utilities/Compiler/SymbolDisplayStringCache.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Concurrent; +using Microsoft.CodeAnalysis; + +namespace Analyzer.Utilities +{ + /// + /// Cache ISymbol.ToDisplayName() results, to avoid performance concerns. + /// + internal sealed class SymbolDisplayStringCache + { + /// + /// Caches by compilation. + /// + private static readonly BoundedCacheWithFactory s_byCompilationCache = + new BoundedCacheWithFactory(); + + /// + /// Mapping of a symbol to its ToDisplayString(). + /// + private readonly ConcurrentDictionary SymbolToDisplayNames = + new ConcurrentDictionary(); + + /// + /// Doesn't construct. + /// + private SymbolDisplayStringCache() + { + } + + /// + /// Gets the symbol display string cache for the compilation. + /// + /// Compilation that this cache is for. + /// A SymbolDisplayStringCache. + public static SymbolDisplayStringCache GetOrCreate(Compilation compilation) + { + return s_byCompilationCache.GetOrCreateValue(compilation, CreateSymbolDisplayNameCache); + + // Local functions + static SymbolDisplayStringCache CreateSymbolDisplayNameCache(Compilation compilation) + => new SymbolDisplayStringCache(); + } + + /// + /// Gets the symbol's display string. + /// + /// Symbol to get the display string. + /// The symbol's display string. + public string GetDisplayString(ISymbol symbol) + { + return this.SymbolToDisplayNames.GetOrAdd(symbol, s => s.ToDisplayString()); + } + } +} diff --git a/src/Utilities/Compiler/TypeSymbolByMetadataNameComparer.cs b/src/Utilities/Compiler/TypeSymbolByMetadataNameComparer.cs new file mode 100644 index 0000000000..2128859d4d --- /dev/null +++ b/src/Utilities/Compiler/TypeSymbolByMetadataNameComparer.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace Analyzer.Utilities +{ + /// + /// for s sorted by display strings. + /// + internal class TypeSymbolByMetadataNameComparer : IComparer + { + /// + /// Constructs. + /// + public TypeSymbolByMetadataNameComparer(Compilation compilation) + : this(SymbolDisplayStringCache.GetOrCreate(compilation)) + { + } + + /// + /// + /// + /// + public TypeSymbolByMetadataNameComparer(SymbolDisplayStringCache symbolDisplayStringCache) + { + this.SymbolDisplayStringCache = symbolDisplayStringCache ?? throw new ArgumentNullException(nameof(symbolDisplayStringCache)); + } + + public SymbolDisplayStringCache SymbolDisplayStringCache { get; } + + public int Compare(ITypeSymbol x, ITypeSymbol y) + { + return StringComparer.Ordinal.Compare(this.SymbolDisplayStringCache[x], y.ToDisplayString()); + } + } +} diff --git a/src/Utilities/Compiler/WellKnownTypeNames.cs b/src/Utilities/Compiler/WellKnownTypeNames.cs index f9ff5c9ac6..0d3b9de09b 100644 --- a/src/Utilities/Compiler/WellKnownTypeNames.cs +++ b/src/Utilities/Compiler/WellKnownTypeNames.cs @@ -53,6 +53,7 @@ internal static class WellKnownTypeNames public const string NUnitFrameworkTestCaseSourceAttribute = "NUnit.Framework.TestCaseSourceAttribute"; public const string NUnitFrameworkTheoryAttribute = "NUnit.Framework.TheoryAttribute"; public const string NewtonsoftJsonJsonConvert = "Newtonsoft.Json.JsonConvert"; + public const string NewtonsoftJsonJsonIgnoreAttribute = "Newtonsoft.Json.JsonIgnoreAttribute"; public const string NewtonsoftJsonJsonSerializer = "Newtonsoft.Json.JsonSerializer"; public const string NewtonsoftJsonJsonSerializerSettings = "Newtonsoft.Json.JsonSerializerSettings"; public const string NewtonsoftJsonTypeNameHandling = "Newtonsoft.Json.TypeNameHandling"; @@ -194,10 +195,16 @@ internal static class WellKnownTypeNames public const string SystemRuntimeInteropServicesSafeHandle = "System.Runtime.InteropServices.SafeHandle"; public const string SystemRuntimeInteropServicesStructLayoutAttribute = "System.Runtime.InteropServices.StructLayoutAttribute"; public const string SystemRuntimeInteropServicesUnmanagedType = "System.Runtime.InteropServices.UnmanagedType"; + public const string SystemRuntimeSerializationDataContractAttribute = "System.Runtime.Serialization.DataContractAttribute"; + public const string SystemRuntimeSerializationDataContractSerializer = "System.Runtime.Serialization.DataContractSerializer"; public const string SystemRuntimeSerializationDataMemberAttribute = "System.Runtime.Serialization.DataMemberAttribute"; public const string SystemRuntimeSerializationFormattersBinaryBinaryFormatter = "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"; + public const string SystemRuntimeSerializationFormattersSoapSoapFormatter = "System.Runtime.Serialization.Formatters.Soap.SoapFormatter"; public const string SystemRuntimeSerializationIDeserializationCallback = "System.Runtime.Serialization.IDeserializationCallback"; + public const string SystemRuntimeSerializationIgnoreDataMemberAttribute = "System.Runtime.Serialization.IgnoreDataMemberAttribute"; public const string SystemRuntimeSerializationISerializable = "System.Runtime.Serialization.ISerializable"; + public const string SystemRuntimeSerializationJsonDataContractJsonSerializer = "System.Runtime.Serialization.Json"; + public const string SystemRuntimeSerializationKnownTypeAttribute = "System.Runtime.Serialization.KnownTypeAttribute"; public const string SystemRuntimeSerializationNetDataContractSerializer = "System.Runtime.Serialization.NetDataContractSerializer"; public const string SystemRuntimeSerializationOnDeserializedAttribute = "System.Runtime.Serialization.OnDeserializedAttribute"; public const string SystemRuntimeSerializationOnDeserializingAttribute = "System.Runtime.Serialization.OnDeserializingAttribute"; @@ -233,6 +240,7 @@ internal static class WellKnownTypeNames public const string SystemSecurityCryptographyX509CertificatesX509Chain = "System.Security.Cryptography.X509Certificates.X509Chain"; public const string SystemSecurityCryptographyX509CertificatesX509Store = "System.Security.Cryptography.X509Certificates.X509Store"; public const string SystemSerializableAttribute = "System.SerializableAttribute"; + public const string SystemServiceModelOperationContractAttribute = "System.ServiceModel.OperationContractAttribute"; public const string SystemSingle = "System.Single"; public const string SystemStackOverflowException = "System.StackOverflowException"; public const string SystemString = "System.String"; @@ -251,6 +259,7 @@ internal static class WellKnownTypeNames public const string SystemThreadingTasksValueTask = "System.Threading.Tasks.ValueTask"; public const string SystemThreadingThread = "System.Threading.Thread"; public const string SystemTimeSpan = "System.TimeSpan"; + public const string SystemType = "System.Type"; public const string SystemUri = "System.Uri"; public const string SystemWebConfigurationHttpRuntimeSection = "System.Web.Configuration.HttpRuntimeSection"; public const string SystemWebHttpCookie = "System.Web.HttpCookie"; @@ -423,6 +432,19 @@ internal static class WellKnownTypeNames public const string SystemXmlSchemaXmlSchema = "System.Xml.Schema.XmlSchema"; public const string SystemXmlSchemaXmlSchemaCollection = "System.Xml.Schema.XmlSchemaCollection"; public const string SystemXmlSchemaXmlSchemaXPath = "System.Xml.Schema.XmlSchemaXPath"; + public const string SystemXmlSerializationXmlAnyAttributeAttribute = "System.Xml.Serialization.XmlAnyAttributeAttribute"; + public const string SystemXmlSerializationXmlAnyElementAttribute = "System.Xml.Serialization.XmlAnyElementAttribute"; + public const string SystemXmlSerializationXmlArrayAttribute = "System.Xml.Serialization.XmlArrayAttribute"; + public const string SystemXmlSerializationXmlArrayItemAttribute = "System.Xml.Serialization.XmlArrayItemAttribute"; + public const string SystemXmlSerializationXmlAttributeAttribute = "System.Xml.Serialization.XmlAttributeAttribute"; + public const string SystemXmlSerializationXmlChoiceIdentifierAttribute = "System.Xml.Serialization.XmlChoiceIdentifierAttribute"; + public const string SystemXmlSerializationXmlElementAttribute = "System.Xml.Serialization.XmlElementAttribute"; + public const string SystemXmlSerializationXmlEnumAttribute = "System.Xml.Serialization.XmlEnumAttribute"; + public const string SystemXmlSerializationXmlIgnoreAttribute = "System.Xml.Serialization.XmlIgnoreAttribute"; + public const string SystemXmlSerializationXmlIncludeAttribute = "System.Xml.Serialization.XmlIncludeAttribute"; + public const string SystemXmlSerializationXmlRootAttribute = "System.Xml.Serialization.XmlRootAttribute"; + public const string SystemXmlSerializationXmlTextAttribute = "System.Xml.Serialization.XmlTextAttribute"; + public const string SystemXmlSerializationXmlTypeAttribute = "System.Xml.Serialization.XmlTypeAttribute"; public const string SystemXmlSerializationXmlSerializer = "System.Xml.Serialization.XmlSerializer"; public const string SystemXmlXPathXPathDocument = "System.Xml.XPath.XPathDocument"; public const string SystemXmlXPathXPathExpression = "System.Xml.XPath.XPathExpression"; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis.Utilities.projitems b/src/Utilities/FlowAnalysis/FlowAnalysis.Utilities.projitems index 158f93134d..ce97fc4613 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis.Utilities.projitems +++ b/src/Utilities/FlowAnalysis/FlowAnalysis.Utilities.projitems @@ -166,8 +166,6 @@ - - diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/ConstructorMapper.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/ConstructorMapper.cs index 3ba385a302..623cfa18aa 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/ConstructorMapper.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/ConstructorMapper.cs @@ -39,25 +39,12 @@ public delegate PropertySetAbstractValue PointsToAbstractValueCallback( IReadOnlyList argumentPointsToAbstractValues); /// - /// Initializes a using constant s whenever - /// the type being tracked by PropertySetAnalysis is instantiated. + /// Initializes a using constant s whenever the type being tracked by PropertySetAnalysis is instantiated. /// - /// Constant s, in the same order - /// that the corresponding was initialized with. - public ConstructorMapper(ImmutableArray propertyAbstractValueKinds) - { - this.PropertyAbstractValues = propertyAbstractValueKinds; - } - - /// - /// Initializes a using constant s whenever - /// the type being tracked by PropertySetAnalysis is instantiated. - /// - /// Constant s, in the same order - /// that the corresponding was initialized with. - public ConstructorMapper(params PropertySetAbstractValueKind[] propertyAbstractValueKinds) - : this(ImmutableArray.Create(propertyAbstractValueKinds)) + /// Constant s, in the same order that the corresponding was initialized with. + public ConstructorMapper(ImmutableArray propertyAbstractValues) { + this.PropertyAbstractValues = propertyAbstractValues; } /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapper.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapper.cs deleted file mode 100644 index 9a0f7fd59e..0000000000 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapper.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; -using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; - -namespace Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis -{ - /// - /// Maps from a method invocation on a tracked type (or derived) to a . - /// - internal class InvocationMapper - { - /// - /// Predicate for matching methods. - /// - /// Method to match. - /// True if matching, false otherwise. - public delegate bool MethodSignatureMatcher(IMethodSymbol method); - - /// - /// Mapping from a method invocation to a , by examing the arguments' - /// s and s. - /// - /// Previous abstract value of all properties being tracked. - /// The method being invoked. - /// Invoked method's arguments' s. - /// Invoked method's arguments' s. - /// Updated after the method invocation. - public delegate PropertySetAbstractValue InvocationValueContentAbstractValueCallback( - PropertySetAbstractValue previousAbstractValue, - IMethodSymbol methodSymbol, - IReadOnlyList valueContentAbstractValues, - IReadOnlyList pointsToAbstractValues); - - /// - /// Mapping from a method invocation to a , by examing the arguments' - /// s. - /// - /// Previous abstract value of all properties being tracked. - /// The method being invoked. - /// Invoked method's arguments' s. - /// Updated after the method invocation. - public delegate PropertySetAbstractValue InvocationPointsToAbstractValueCallback( - PropertySetAbstractValue previousAbstractValue, - IMethodSymbol methodSymbol, - IReadOnlyList pointsToAbstractValues); - - /// - /// Constructs. - /// - /// Method being invoked. - /// Predicate for matching method overloads by their arguments. - /// Callback for mapping the invoked method's arguments to a - /// . - public InvocationMapper( - string methodMetadataName, - MethodSignatureMatcher methodSignatureMatcher, - InvocationValueContentAbstractValueCallback mapFromArgumentValueContentAbstractValues) - { - this.MethodMetadataName = methodMetadataName ?? throw new ArgumentNullException(nameof(methodMetadataName)); - this.SignatureMatcher = methodSignatureMatcher ?? throw new ArgumentNullException(nameof(methodSignatureMatcher)); - this.MapFromArgumentValueContentAbstractValues = mapFromArgumentValueContentAbstractValues ?? throw new ArgumentNullException(nameof(mapFromArgumentValueContentAbstractValues)); - } - - /// - /// Constructs. - /// - /// Method being invoked. - /// Predicate for matching method overloads by their arguments. - /// Callback for mapping the invoked method's arguments to a - /// . - public InvocationMapper( - string methodMetadataName, - MethodSignatureMatcher methodSignatureMatcher, - InvocationPointsToAbstractValueCallback mapFromArgumentPointsToAbstractValues) - { - this.MethodMetadataName = methodMetadataName ?? throw new ArgumentNullException(nameof(methodMetadataName)); - this.SignatureMatcher = methodSignatureMatcher ?? throw new ArgumentNullException(nameof(methodSignatureMatcher)); - this.MapFromArgumentPointsToAbstractValues = mapFromArgumentPointsToAbstractValues ?? throw new ArgumentNullException(nameof(mapFromArgumentPointsToAbstractValues)); - } - - /// - /// Method's metadata name. - /// - internal string MethodMetadataName { get; } - - /// - /// Predicate for matching by method's parameters. - /// - internal MethodSignatureMatcher SignatureMatcher { get; } - - /// - /// Callback for mapping from invoked method arguments. - /// - internal InvocationValueContentAbstractValueCallback? MapFromArgumentValueContentAbstractValues { get; } - - /// - /// Callback for mapping from invoked method arguments. - /// - internal InvocationPointsToAbstractValueCallback? MapFromArgumentPointsToAbstractValues { get; } - - /// - /// Indicates that ValueContentAnalysis is required. - /// - internal bool RequiresValueContentAnalysis { get { return this.MapFromArgumentValueContentAbstractValues != null; } } - } -} diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapperCollection.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapperCollection.cs deleted file mode 100644 index a4f0733236..0000000000 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/InvocationMapperCollection.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using Microsoft.CodeAnalysis; - -namespace Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis -{ - /// - /// Collection of s. - /// - internal class InvocationMapperCollection - { - /// - /// Constructs. - /// - /// The s for this collection. - /// - /// If a single method matches with multiple s, the first one wins. - /// - public InvocationMapperCollection(IEnumerable invocationMappers) - { - foreach (InvocationMapper invocationMapper in invocationMappers) - { - if (!this.InvocationMappers.TryGetValue(invocationMapper.MethodMetadataName, out List list)) - { - list = new List(); - this.InvocationMappers.Add(invocationMapper.MethodMetadataName, list); - } - - list.Add(invocationMapper); - this.RequiresValueContentAnalysis |= invocationMapper.RequiresValueContentAnalysis; - } - } - - /// - /// Constructs. - /// - /// The s for this collection. - /// - /// If a single method matches with multiple s, the first one wins. - /// - public InvocationMapperCollection(params InvocationMapper[] invocationMappers) - : this((IEnumerable)invocationMappers) - { - } - - /// - /// An empty collection, just so you don't have to new one up yourself. - /// - public static InvocationMapperCollection Empty { get; } = new InvocationMapperCollection(); - - /// - /// Indicates that at least one requires ValueContentAnalysis. - /// - internal bool RequiresValueContentAnalysis { get; } - - /// - /// Keys are method names, values are lists of InvocationMappers. - /// The lists are linearly searched to find a matching method signature. First match wins. - /// - private readonly Dictionary> InvocationMappers = - new Dictionary>(StringComparer.Ordinal); - - /// - /// Tries to find the first matching . - /// - /// Method symbol to find a matching for. - /// Matched if found. - /// True if a matching was found in this collection, false otherwise. - internal bool TryGetInvocationMapper( - IMethodSymbol method, - [NotNullWhen(returnValue: true)] out InvocationMapper? invocationMapper) - { - invocationMapper = null; - - if (this.InvocationMappers.TryGetValue(method.MetadataName, out List list)) - { - foreach (InvocationMapper m in list) - { - if (m.SignatureMatcher(method)) - { - invocationMapper = m; - return true; - } - } - } - - return false; - } - } -} diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapper.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapper.cs index cc8b35bad7..0f9114fc29 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapper.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapper.cs @@ -14,14 +14,14 @@ internal sealed class PropertyMapper #pragma warning restore CA1812 { /// - /// Mapping from of the property assignment value to a + /// Mapping from to a /// /// Property's assigned value's . /// What the property's assigned value should map to. public delegate PropertySetAbstractValueKind ValueContentAbstractValueCallback(ValueContentAbstractValue valueContentAbstractValue); /// - /// Mapping from of the property assignment value to a + /// Mapping from to a /// /// Property's assigned value's . /// What the property's assigned value should map to. diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapperCollection.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapperCollection.cs index de158e86e9..2ce7757b39 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapperCollection.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertyMapperCollection.cs @@ -8,17 +8,10 @@ namespace Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis { - /// - /// Collection of s. - /// #pragma warning disable CA1812 // Is too instantiated. internal sealed class PropertyMapperCollection #pragma warning restore CA1812 { - /// - /// Constructs. - /// - /// s to use in this collection. public PropertyMapperCollection(IEnumerable propertyMappers) { if (propertyMappers == null) @@ -72,10 +65,6 @@ public PropertyMapperCollection(IEnumerable propertyMappers) this.RequiresValueContentAnalysis = this.PropertyMappersWithIndex.Values.Any(t => t.PropertyMapper.RequiresValueContentAnalysis); } - /// - /// Constructs. - /// - /// s to use in this collection. public PropertyMapperCollection(params PropertyMapper[] propertyMappers) : this((IEnumerable)propertyMappers) { diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAbstractValue.cs index 418f90b775..c4ec259698 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAbstractValue.cs @@ -147,14 +147,14 @@ public PropertySetAbstractValueKind this[int index] } } - internal PropertySetAbstractValue ReplaceAt(int propertyIndex, PropertySetAbstractValueKind kind) + internal PropertySetAbstractValue ReplaceAt(int index, PropertySetAbstractValueKind kind) { - Debug.Assert(propertyIndex >= 0); + Debug.Assert(index >= 0); int newLength; - if (propertyIndex >= this.KnownPropertyAbstractValues.Length) + if (index >= this.KnownPropertyAbstractValues.Length) { - newLength = propertyIndex + 1; + newLength = index + 1; } else { @@ -171,7 +171,7 @@ internal PropertySetAbstractValue ReplaceAt(int propertyIndex, PropertySetAbstra kinds.Add(PropertySetAbstractValueKind.Unknown); } - kinds[propertyIndex] = kind; + kinds[index] = kind; return GetInstance(kinds); } finally diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs index bd31ed3fc6..01a193b79a 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs @@ -475,88 +475,12 @@ internal void ProcessExitBlock(PropertySetBlockAnalysisResult exitBlockOutput) } } - public override PropertySetAbstractValue VisitInvocation_NonLambdaOrDelegateOrLocalFunction( - IMethodSymbol method, - IOperation? visitedInstance, - ImmutableArray visitedArguments, - bool invokedAsDelegate, - IOperation originalOperation, - PropertySetAbstractValue defaultValue) + public override PropertySetAbstractValue VisitInvocation_NonLambdaOrDelegateOrLocalFunction(IMethodSymbol method, IOperation? visitedInstance, ImmutableArray visitedArguments, bool invokedAsDelegate, IOperation originalOperation, PropertySetAbstractValue defaultValue) { PropertySetAbstractValue baseValue = base.VisitInvocation_NonLambdaOrDelegateOrLocalFunction(method, visitedInstance, visitedArguments, invokedAsDelegate, originalOperation, defaultValue); - // If we have a matching InvocationMapper, update the abstract value on the invoked instance. - if (visitedInstance != null - && this.TrackedTypeSymbols.Any(s => visitedInstance.Type.GetBaseTypesAndThis().Contains(s)) - && this.DataFlowAnalysisContext.InvocationMappers.TryGetInvocationMapper(method, out InvocationMapper? invocationMapper)) - { - PropertySetAbstractValue newAbstractValue; - if (invocationMapper.MapFromArgumentPointsToAbstractValues != null) - { - ArrayBuilder builder = ArrayBuilder.GetInstance(); - try - { - foreach (IArgumentOperation argumentOperation in visitedArguments) - { - builder.Add(this.GetPointsToAbstractValue(argumentOperation)); - } - - PointsToAbstractValue visitedInstancePointsTo = this.GetPointsToAbstractValue(visitedInstance); - foreach (AbstractLocation location in visitedInstancePointsTo.Locations) - { - PropertySetAbstractValue previousAbstractValue = this.GetAbstractValue(location); - newAbstractValue = invocationMapper.MapFromArgumentPointsToAbstractValues( - previousAbstractValue, - method, - builder); - this.SetAbstractValue(location, newAbstractValue); - } - } - finally - { - builder.Free(); - } - } - else if (invocationMapper.MapFromArgumentValueContentAbstractValues != null) - { - Debug.Assert(this.DataFlowAnalysisContext.ValueContentAnalysisResultOpt != null); - ArrayBuilder pointsToBuilder = ArrayBuilder.GetInstance(); - ArrayBuilder valueContentBuilder = ArrayBuilder.GetInstance(); - try - { - foreach (IArgumentOperation argumentOperation in visitedArguments) - { - pointsToBuilder.Add(this.GetPointsToAbstractValue(argumentOperation)); - valueContentBuilder.Add(this.GetValueContentAbstractValue(argumentOperation.Value)); - } - - PointsToAbstractValue visitedInstancePointsTo = this.GetPointsToAbstractValue(visitedInstance); - foreach (AbstractLocation location in visitedInstancePointsTo.Locations) - { - PropertySetAbstractValue previousAbstractValue = this.GetAbstractValue(location); - newAbstractValue = invocationMapper.MapFromArgumentValueContentAbstractValues( - previousAbstractValue, - method, - valueContentBuilder, - pointsToBuilder); - this.SetAbstractValue(location, newAbstractValue); - } - } - finally - { - pointsToBuilder.Free(); - valueContentBuilder.Free(); - } - } - else - { - Debug.Fail("Unhandled InvocationMapper"); - } - } - - // If we have a HazardousUsageEvaluator for the tracked type being passed as an argument. if (this.DataFlowAnalysisContext.HazardousUsageEvaluators.TryGetArgumentHazardousUsageEvaluator( - out HazardousUsageEvaluator argumentHazardousUsageEvaluator)) + out HazardousUsageEvaluator argumentHazardousUsageEvaluator)) { foreach (IArgumentOperation visitedArgument in visitedArguments) { @@ -592,8 +516,10 @@ public override PropertySetAbstractValue VisitInvocation_NonLambdaOrDelegateOrLo propertySetInstance, (PropertySetAbstractValue abstractValue) => hazardousUsageEvaluator.InvocationEvaluator!(method, abstractValue)); } - - this.MergeInterproceduralResults(originalOperation); + else + { + this.MergeInterproceduralResults(originalOperation); + } return baseValue; } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.cs index cf7c6d3606..17db02eac3 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.cs @@ -40,7 +40,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe /// Names of the types to track. /// How constructor invocations map to s. /// How property assignments map to . - /// How method invocations affect a tracked object's . /// When and how to evaluate s to for hazardous usages. /// Interprocedural dataflow analysis configuration. /// Whether to be pessimistic. @@ -53,7 +52,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe ImmutableHashSet typeToTrackMetadataNames, ConstructorMapper constructorMapper, PropertyMapperCollection propertyMappers, - InvocationMapperCollection invocationMappers, HazardousUsageEvaluatorCollection hazardousUsageEvaluators, InterproceduralAnalysisConfiguration interproceduralAnalysisConfig, bool pessimisticAnalysis = false) @@ -79,9 +77,7 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe PointsToAnalysisResult? pointsToAnalysisResult; ValueContentAnalysisResult? valueContentAnalysisResultOpt; - if (!constructorMapper.RequiresValueContentAnalysis - && !propertyMappers.RequiresValueContentAnalysis - && !invocationMappers.RequiresValueContentAnalysis) + if (!constructorMapper.RequiresValueContentAnalysis && !propertyMappers.RequiresValueContentAnalysis) { pointsToAnalysisResult = PointsToAnalysis.TryGetOrComputeResult( cfg, @@ -133,7 +129,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe typeToTrackMetadataNames, constructorMapper, propertyMappers, - invocationMappers, hazardousUsageEvaluators); var result = TryGetOrComputeResultForAnalysisContext(analysisContext); return result; @@ -147,7 +142,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe /// Name of the type to track. /// How constructor invocations map to s. /// How property assignments map to . - /// How method invocations affect a tracked object's . /// When and how to evaluate s to for hazardous usages. /// Interprocedural dataflow analysis configuration. /// Whether to be pessimistic. @@ -160,7 +154,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe string typeToTrackMetadataName, ConstructorMapper constructorMapper, PropertyMapperCollection propertyMappers, - InvocationMapperCollection invocationMappers, HazardousUsageEvaluatorCollection hazardousUsageEvaluators, InterproceduralAnalysisConfiguration interproceduralAnalysisConfig, bool pessimisticAnalysis = false) @@ -172,7 +165,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe new string[] { typeToTrackMetadataName }.ToImmutableHashSet(), constructorMapper, propertyMappers, - invocationMappers, hazardousUsageEvaluators, interproceduralAnalysisConfig, pessimisticAnalysis); @@ -186,7 +178,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe /// Names of the types to track. /// How constructor invocations map to s. /// How property assignments map to . - /// How method invocations affect a tracked object's . /// When and how to evaluate s to for hazardous usages. /// Interprocedural dataflow analysis configuration. /// Whether to be pessimistic. @@ -199,7 +190,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe ImmutableHashSet typeToTrackMetadataNames, ConstructorMapper constructorMapper, PropertyMapperCollection propertyMappers, - InvocationMapperCollection invocationMappers, HazardousUsageEvaluatorCollection hazardousUsageEvaluators, InterproceduralAnalysisConfiguration interproceduralAnalysisConfig, bool pessimisticAnalysis = false) @@ -261,7 +251,6 @@ private PropertySetAnalysis(PropertySetAnalysisDomain analysisDomain, PropertySe typeToTrackMetadataNames, constructorMapper, propertyMappers, - invocationMappers, hazardousUsageEvaluators, interproceduralAnalysisConfig, pessimisticAnalysis); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs index 0104bc33a1..30d51db9b1 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs @@ -39,7 +39,6 @@ private PropertySetAnalysisContext( ImmutableHashSet typeToTrackMetadataNames, ConstructorMapper constructorMapper, PropertyMapperCollection propertyMappers, - InvocationMapperCollection invocationMappers, HazardousUsageEvaluatorCollection hazardousUsageEvaluators, ImmutableDictionary<(INamedTypeSymbol, bool), string> hazardousUsageTypesToNames) : base( @@ -63,7 +62,6 @@ private PropertySetAnalysisContext( this.TypeToTrackMetadataNames = typeToTrackMetadataNames; this.ConstructorMapper = constructorMapper; this.PropertyMappers = propertyMappers; - this.InvocationMappers = invocationMappers; this.HazardousUsageEvaluators = hazardousUsageEvaluators; this.HazardousUsageTypesToNames = hazardousUsageTypesToNames; } @@ -82,7 +80,6 @@ public static PropertySetAnalysisContext Create( ImmutableHashSet typeToTrackMetadataNames, ConstructorMapper constructorMapper, PropertyMapperCollection propertyMappers, - InvocationMapperCollection invocationMappers, HazardousUsageEvaluatorCollection hazardousUsageEvaluators) { return new PropertySetAnalysisContext( @@ -101,7 +98,6 @@ public static PropertySetAnalysisContext Create( typeToTrackMetadataNames: typeToTrackMetadataNames, constructorMapper: constructorMapper, propertyMappers: propertyMappers, - invocationMappers: invocationMappers, hazardousUsageEvaluators: hazardousUsageEvaluators, hazardousUsageTypesToNames: hazardousUsageEvaluators.GetTypeToNameMapping(wellKnownTypeProvider)); } @@ -134,7 +130,6 @@ public override PropertySetAnalysisContext ForkForInterproceduralAnalysis( this.TypeToTrackMetadataNames, this.ConstructorMapper, this.PropertyMappers, - this.InvocationMappers, this.HazardousUsageEvaluators, this.HazardousUsageTypesToNames); } @@ -154,11 +149,6 @@ public override PropertySetAnalysisContext ForkForInterproceduralAnalysis( /// public PropertyMapperCollection PropertyMappers { get; } - /// - /// How method invocations on tracked objects affect its . - /// - public InvocationMapperCollection InvocationMappers { get; } - /// /// When and how to evaluate s to for hazardous usages. /// @@ -172,7 +162,6 @@ protected override void ComputeHashCodePartsSpecific(Action addPart) addPart(TypeToTrackMetadataNames.GetHashCode()); addPart(ConstructorMapper.GetHashCode()); addPart(PropertyMappers.GetHashCode()); - addPart(InvocationMappers.GetHashCode()); addPart(HazardousUsageEvaluators.GetHashCode()); } #pragma warning restore CA1307 // Specify StringComparison diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs index 350fd2ccba..d000c0b363 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs @@ -109,17 +109,6 @@ public static PropertySetAbstractValueKind EvaluateLiteralValues( } } - /// - /// A for always mapping to Unknown. - /// - /// Ignored. - /// Always unknown. - /// Useful for dummy properties. - public static PropertySetAbstractValueKind AlwaysUnknown(PointsToAbstractValue _) - { - return PropertySetAbstractValueKind.Unknown; - } - /// /// A for all properties flagged being hazardous, treating all /// unknown as maybe flagged.