From 97c14d00a204b9d3c4d00ebb1e6aeaea4e0cf7e3 Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Mon, 5 Aug 2019 16:46:11 +0100 Subject: [PATCH] CA1829: Use property instead of Enumerable.Count{). --- .../Microsoft.CodeAnalysis.FxCopAnalyzers.md | 214 ++++++------ ...icrosoft.CodeAnalysis.FxCopAnalyzers.sarif | 19 ++ ...opertyInsteadOfCountMethodWhenAvailable.cs | 148 ++++++--- .../Microsoft.NetCore.Analyzers.md | 170 +++++----- .../Microsoft.NetCore.Analyzers.sarif | 19 ++ ...opertyInsteadOfCountMethodWhenAvailable.cs | 112 ------- ...yInsteadOfCountMethodWhenAvailableTests.cs | 312 ++++++++++++++++++ src/Utilities/Compiler/WellKnownTypes.cs | 5 + 8 files changed, 657 insertions(+), 342 deletions(-) delete mode 100644 src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs create mode 100644 src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index cc01bfaf64..317243072b 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -88,109 +88,111 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 85 | CA1826 | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | 86 | [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | True | For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition. | 87 | [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | True | For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. | -88 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | -89 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | -90 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007-do-not-directly-await-task) | Consider calling ConfigureAwait on the awaited task | Reliability | True | 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. | -91 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | -92 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | -93 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | -94 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | -95 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | -96 | [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119-seal-methods-that-satisfy-private-interfaces) | Seal methods that satisfy private interfaces | Security | True | 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. | -97 | [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153-avoid-handling-corrupted-state-exceptions) | Do Not Catch Corrupted State Exceptions | Security | True | False | Catching corrupted state exceptions could mask errors (such as access violations), resulting in inconsistent state of execution or making it easier for attackers to compromise system. Instead, catch and handle a more specific set of exception type(s) or re-throw the exception | -98 | [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) | Rethrow to preserve stack details. | Usage | True | False | Re-throwing caught exception changes stack information. | -99 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | -100 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | -101 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -102 | [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211-non-constant-fields-should-not-be-visible) | Non-constant fields should not be visible | Usage | True | False | Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques to synchronize access to the class object. | -103 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | -104 | [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214-do-not-call-overridable-methods-in-constructors) | Do not call overridable methods in constructors | Usage | True | False | Virtual methods defined on the class should not be called from constructors. If a derived class has overridden the method, the derived class version will be called (before the derived class constructor is called). | -105 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | -106 | [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217-do-not-mark-enums-with-flagsattribute) | Do not mark enums with FlagsAttribute | Usage | False | True | An externally visible enumeration is marked by using FlagsAttribute, and it has one or more values that are not powers of two or a combination of the other defined values on the enumeration. | -107 | [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218-override-gethashcode-on-overriding-equals) | Override GetHashCode on overriding Equals | Usage | True | True | GetHashCode returns a value, based on the current instance, that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code. | -108 | [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219-do-not-raise-exceptions-in-exception-clauses) | Do not raise exceptions in finally clauses | Usage | True | False | When an exception is raised in a finally clause, the new exception hides the active exception. This makes the original error difficult to detect and debug. | -109 | [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224-override-equals-on-overloading-operator-equals) | Override Equals on overloading operator equals | Usage | True | True | A public type implements the equality operator but does not override Object.Equals. | -110 | [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225-operator-overloads-have-named-alternates) | Operator overloads have named alternates | Usage | True | True | An operator overload was detected, and the expected named alternative method was not found. The named alternative member provides access to the same functionality as the operator and is provided for developers who program in languages that do not support overloaded operators. | -111 | [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226-operators-should-have-symmetrical-overloads) | Operators should have symmetrical overloads | Usage | True | True | A type implements the equality or inequality operator and does not implement the opposite operator. | -112 | [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227-collection-properties-should-be-read-only) | Collection properties should be read only | Usage | True | False | A writable collection property allows a user to replace the collection with a different collection. A read-only property stops the collection from being replaced but still allows the individual members to be set. | -113 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -114 | [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231-overload-operator-equals-on-overriding-valuetype-equals) | Overload operator equals on overriding value type Equals | Usage | True | True | In most programming languages there is no default implementation of the equality operator (==) for value types. If your programming language supports operator overloads, you should consider implementing the equality operator. Its behavior should be identical to that of Equals | -115 | [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234-pass-system-uri-objects-instead-of-strings) | Pass system uri objects instead of strings | Usage | True | False | A call is made to a method that has a string parameter whose name contains "uri", "URI", "urn", "URN", "url", or "URL". The declaring type of the method contains a corresponding method overload that has a System.Uri parameter. | -116 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -117 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | -118 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | -119 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -120 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -121 | CA2244 | Do not duplicate indexed element initializations | Usage | True | False | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | -122 | CA2245 | Do not assign a property to itself. | Usage | True | False | The property {0} should not be assigned to itself. | -123 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | -124 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -125 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -126 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -127 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | -128 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -129 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -130 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -131 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -132 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -133 | CA2326 | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | -134 | CA2327 | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -135 | CA2328 | Ensure that JsonSerializerSettings are secure | Security | False | 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. | -136 | CA2329 | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | 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. | -137 | CA2330 | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | 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. | -138 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -139 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | 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}'. | -140 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | 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}'. | -141 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -142 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -143 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | 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}'. | -144 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -145 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -146 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -147 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -148 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -149 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -150 | CA3061 | Do Not Add Schema By URL | Security | True | 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. | -151 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075-insecure-dtd-processing) | Insecure DTD processing in XML | Security | True | 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.  | -152 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076-insecure-xslt-script-execution) | Insecure XSLT script processing. | Security | True | 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. | -153 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077-insecure-processing-in-api-design-xml-document-and-xml-text-reader) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | 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.  | -154 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147-mark-verb-handlers-with-validateantiforgerytoken) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | -155 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | 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. | -156 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | 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. | -157 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -158 | CA5359 | Do Not Disable Certificate Validation | Security | True | 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. | -159 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | 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. | -160 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | 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. | -161 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | -162 | CA5363 | Do Not Disable Request Validation | Security | True | 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. | -163 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | -164 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | 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. | -165 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | 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. | -166 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | 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. | -167 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | 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. | -168 | CA5369 | Use XmlReader For Deserialize | Security | True | 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. | -169 | CA5370 | Use XmlReader For Validating Reader | Security | True | 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. | -170 | CA5371 | Use XmlReader For Schema Read | Security | True | 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 | CA5372 | Use XmlReader For XPathDocument | Security | True | 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 | CA5373 | Do not use obsolete key derivation function | Security | True | 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. | -173 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -174 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | 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. | -175 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -176 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | -177 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | 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. | -178 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | 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. | -179 | CA5380 | Do Not Add Certificates To Root Store | Security | True | 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. | -180 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | 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. | -181 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -182 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -183 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | -184 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -185 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | 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. | -186 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -187 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -188 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | 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. | -189 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -190 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | 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. | -191 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | 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. | -192 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | -193 | CA9999 | Analyzer version mismatch | Reliability | True | 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. | +88 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | +89 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | +90 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | +91 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007-do-not-directly-await-task) | Consider calling ConfigureAwait on the awaited task | Reliability | True | 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. | +92 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | +93 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | +94 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | +95 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | +96 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | +97 | [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119-seal-methods-that-satisfy-private-interfaces) | Seal methods that satisfy private interfaces | Security | True | 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. | +98 | [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153-avoid-handling-corrupted-state-exceptions) | Do Not Catch Corrupted State Exceptions | Security | True | False | Catching corrupted state exceptions could mask errors (such as access violations), resulting in inconsistent state of execution or making it easier for attackers to compromise system. Instead, catch and handle a more specific set of exception type(s) or re-throw the exception | +99 | [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) | Rethrow to preserve stack details. | Usage | True | False | Re-throwing caught exception changes stack information. | +100 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | +101 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | +102 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | +103 | [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211-non-constant-fields-should-not-be-visible) | Non-constant fields should not be visible | Usage | True | False | Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques to synchronize access to the class object. | +104 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | +105 | [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214-do-not-call-overridable-methods-in-constructors) | Do not call overridable methods in constructors | Usage | True | False | Virtual methods defined on the class should not be called from constructors. If a derived class has overridden the method, the derived class version will be called (before the derived class constructor is called). | +106 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | +107 | [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217-do-not-mark-enums-with-flagsattribute) | Do not mark enums with FlagsAttribute | Usage | False | True | An externally visible enumeration is marked by using FlagsAttribute, and it has one or more values that are not powers of two or a combination of the other defined values on the enumeration. | +108 | [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218-override-gethashcode-on-overriding-equals) | Override GetHashCode on overriding Equals | Usage | True | True | GetHashCode returns a value, based on the current instance, that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code. | +109 | [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219-do-not-raise-exceptions-in-exception-clauses) | Do not raise exceptions in finally clauses | Usage | True | False | When an exception is raised in a finally clause, the new exception hides the active exception. This makes the original error difficult to detect and debug. | +110 | [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224-override-equals-on-overloading-operator-equals) | Override Equals on overloading operator equals | Usage | True | True | A public type implements the equality operator but does not override Object.Equals. | +111 | [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225-operator-overloads-have-named-alternates) | Operator overloads have named alternates | Usage | True | True | An operator overload was detected, and the expected named alternative method was not found. The named alternative member provides access to the same functionality as the operator and is provided for developers who program in languages that do not support overloaded operators. | +112 | [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226-operators-should-have-symmetrical-overloads) | Operators should have symmetrical overloads | Usage | True | True | A type implements the equality or inequality operator and does not implement the opposite operator. | +113 | [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227-collection-properties-should-be-read-only) | Collection properties should be read only | Usage | True | False | A writable collection property allows a user to replace the collection with a different collection. A read-only property stops the collection from being replaced but still allows the individual members to be set. | +114 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | +115 | [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231-overload-operator-equals-on-overriding-valuetype-equals) | Overload operator equals on overriding value type Equals | Usage | True | True | In most programming languages there is no default implementation of the equality operator (==) for value types. If your programming language supports operator overloads, you should consider implementing the equality operator. Its behavior should be identical to that of Equals | +116 | [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234-pass-system-uri-objects-instead-of-strings) | Pass system uri objects instead of strings | Usage | True | False | A call is made to a method that has a string parameter whose name contains "uri", "URI", "urn", "URN", "url", or "URL". The declaring type of the method contains a corresponding method overload that has a System.Uri parameter. | +117 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | +118 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | +119 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | +120 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | +121 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | +122 | CA2244 | Do not duplicate indexed element initializations | Usage | True | False | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | +123 | CA2245 | Do not assign a property to itself. | Usage | True | False | The property {0} should not be assigned to itself. | +124 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | +125 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +126 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +127 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +128 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | +129 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +130 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +131 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +132 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +133 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +134 | CA2326 | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | +135 | CA2327 | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +136 | CA2328 | Ensure that JsonSerializerSettings are secure | Security | False | 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. | +137 | CA2329 | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | 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. | +138 | CA2330 | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | 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 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +140 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | 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}'. | +141 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | 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}'. | +142 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | +143 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +144 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | 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}'. | +145 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +146 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +147 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +148 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +149 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +150 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +151 | CA3061 | Do Not Add Schema By URL | Security | True | 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. | +152 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075-insecure-dtd-processing) | Insecure DTD processing in XML | Security | True | 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.  | +153 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076-insecure-xslt-script-execution) | Insecure XSLT script processing. | Security | True | 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. | +154 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077-insecure-processing-in-api-design-xml-document-and-xml-text-reader) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | 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.  | +155 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147-mark-verb-handlers-with-validateantiforgerytoken) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | +156 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | 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. | +157 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | 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. | +158 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | +159 | CA5359 | Do Not Disable Certificate Validation | Security | True | 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. | +160 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | 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. | +161 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | 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. | +162 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | +163 | CA5363 | Do Not Disable Request Validation | Security | True | 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. | +164 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | +165 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | 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. | +166 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | 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. | +167 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | 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. | +168 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | 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. | +169 | CA5369 | Use XmlReader For Deserialize | Security | True | 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. | +170 | CA5370 | Use XmlReader For Validating Reader | Security | True | 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 | CA5371 | Use XmlReader For Schema Read | Security | True | 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 | CA5372 | Use XmlReader For XPathDocument | Security | True | 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 | CA5373 | Do not use obsolete key derivation function | Security | True | 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. | +174 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +175 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | 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. | +176 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | +177 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | +178 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | 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. | +179 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | 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. | +180 | CA5380 | Do Not Add Certificates To Root Store | Security | True | 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. | +181 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | 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 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +183 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +184 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | +185 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | +186 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | 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. | +187 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +188 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +189 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | 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. | +190 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +191 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | 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. | +192 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | 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. | +193 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +194 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | 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. | +195 | CA9999 | Analyzer version mismatch | Reliability | True | 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 570af4975e..9e032deb6b 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -3661,6 +3661,25 @@ "Telemetry" ] } + }, + "CA5396": { + "id": "CA5396", + "shortDescription": "Set HttpOnly to true for HttpCookie", + "fullDescription": "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.", + "defaultLevel": "warning", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "SetHttpOnlyForHttpCookie", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Dataflow", + "Telemetry" + ] + } } } }, diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index bdf10de7f4..3193067371 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -1,6 +1,7 @@ // 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; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; @@ -25,6 +26,8 @@ namespace Microsoft.NetCore.Analyzers.Performance public sealed class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1829"; + private const string CountPropertyName = "Count"; + private const string LengthPropertyName = "Length"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); @@ -40,8 +43,6 @@ public sealed class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : Diagn helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/" + RuleId.ToLowerInvariant()); #pragma warning restore CA1308 // Normalize strings to uppercase - private static readonly ImmutableHashSet propertyNames = ImmutableHashSet.Create("Length", "Count"); - /// /// Returns a set of descriptors for the diagnostics that this analyzer is capable of producing. /// @@ -68,9 +69,16 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) { if (WellKnownTypes.Enumerable(context.Compilation) is INamedTypeSymbol enumerableType) { + var operationActionsContext = new UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext( + context.Compilation, + enumerableType, + WellKnownTypes.ICollection(context.Compilation)?.GetMembers(CountPropertyName).OfType().SingleOrDefault(), + WellKnownTypes.GenericICollection(context.Compilation)?.GetMembers(CountPropertyName).OfType().SingleOrDefault(), + WellKnownTypes.ImmutableArray(context.Compilation)); + var operationActionsHandler = context.Compilation.Language == LanguageNames.CSharp - ? (OperationActionsHandler)new CSharpOperationActionsHandler(containingSymbol: enumerableType, rule: s_rule) - : (OperationActionsHandler)new BasicOperationActionsHandler(containingSymbol: enumerableType, rule: s_rule); + ? (OperationActionsHandler)new CSharpOperationActionsHandler(operationActionsContext) + : (OperationActionsHandler)new BasicOperationActionsHandler(operationActionsContext); context.RegisterOperationAction( operationActionsHandler.AnalyzeInvocationOperation, @@ -78,32 +86,48 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) } } + private sealed class OperationActionsContext + { + public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumerableType, IPropertySymbol collectionCountProperty, IPropertySymbol collectionOfTCountProperty, INamedTypeSymbol immutableArrayType) + { + Compilation = compilation; + EnumerableType = enumerableType; + CollectionCountProperty = collectionCountProperty; + CollectionOfTCountProperty = collectionOfTCountProperty; + ImmutableArrayType = immutableArrayType; + } + + public Compilation Compilation { get; } + public INamedTypeSymbol EnumerableType { get; } + public IPropertySymbol CollectionCountProperty { get; } + public IPropertySymbol CollectionOfTCountProperty { get; } + public INamedTypeSymbol ImmutableArrayType { get; } + } + /// /// Handler for operaction actions. /// private abstract class OperationActionsHandler { - private readonly INamedTypeSymbol containingSymbol; - private readonly DiagnosticDescriptor rule; - - protected OperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) + protected OperationActionsHandler(OperationActionsContext context) { - this.containingSymbol = containingSymbol; - this.rule = rule; + Context = context; } + public OperationActionsContext Context { get; } + internal void AnalyzeInvocationOperation(OperationAnalysisContext context) { var invocationOperation = (IInvocationOperation)context.Operation; - if (GetEnumerableCountInvocationTargetType(invocationOperation, this.containingSymbol) is ITypeSymbol invocationTarget && + if (GetEnumerableCountInvocationTargetType(invocationOperation) is ITypeSymbol invocationTarget && GetReplacementProperty(invocationTarget) is string propertyName) { var propertiesBuilder = ImmutableDictionary.CreateBuilder(); propertiesBuilder.Add("PropertyName", propertyName); var diagnostic = Diagnostic.Create( - this.rule, + s_rule, invocationOperation.Syntax.GetLocation(), propertiesBuilder.ToImmutable(), propertyName); @@ -112,35 +136,79 @@ internal void AnalyzeInvocationOperation(OperationAnalysisContext context) } } - protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol); + protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation); - private static string GetReplacementProperty(ITypeSymbol invocationTarget) + private string GetReplacementProperty(ITypeSymbol invocationTarget) { if (invocationTarget.TypeKind == TypeKind.Array) { - return nameof(Array.Length); + return LengthPropertyName; } - foreach (var member in invocationTarget.GetMembers()) + if (invocationTarget.OriginalDefinition is ITypeSymbol originalDefinition && + originalDefinition.MetadataName.ToString().Equals(typeof(ImmutableArray<>).Name, StringComparison.Ordinal) && + originalDefinition.ContainingNamespace.ToString().Equals(typeof(ImmutableArray<>).Namespace, StringComparison.Ordinal)) { - if (member is IPropertySymbol property && propertyNames.Contains(property.Name)) - { - return property.Name; - } + return LengthPropertyName; + } + + if (invocationTarget.FindImplementationForInterfaceMember(this.Context.CollectionCountProperty) is IPropertySymbol countProperty && + !countProperty.ExplicitInterfaceImplementations.Any()) + { + return CountPropertyName; } - foreach (var type in invocationTarget.AllInterfaces) + if (findImplementationForCollectionOfTInterfaceCountProperty(invocationTarget)) { - foreach (var member in type.GetMembers()) + return CountPropertyName; + } + + return null; + + bool findImplementationForCollectionOfTInterfaceCountProperty(ITypeSymbol invocationTarget) + { + if (isCollectionOfTInterface(invocationTarget)) { - if (member is IPropertySymbol property && propertyNames.Contains(property.Name)) + return true; + } + + if (invocationTarget.TypeKind == TypeKind.Interface) + { + if (invocationTarget.GetMembers(CountPropertyName).OfType().Any()) { - return property.Name; + return false; + } + + foreach (var @interface in invocationTarget.AllInterfaces) + { + if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && + isCollectionOfTInterface(originalInterfaceDefinition)) + { + return true; + } + } + } + else + { + foreach (var @interface in invocationTarget.AllInterfaces) + { + if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && + isCollectionOfTInterface(originalInterfaceDefinition)) + { + if (invocationTarget.FindImplementationForInterfaceMember(@interface.GetMembers(CountPropertyName)[0]) is IPropertySymbol propertyImplementation && + !propertyImplementation.ExplicitInterfaceImplementations.Any()) + { + return true; + } + } } } - } - return null; + return false; + + bool isCollectionOfTInterface(ITypeSymbol type) + => type.OriginalDefinition?.Equals(this.Context.CollectionOfTCountProperty.ContainingSymbol) ?? false; + } } } @@ -151,23 +219,23 @@ private static string GetReplacementProperty(ITypeSymbol invocationTarget) /// private sealed class CSharpOperationActionsHandler : OperationActionsHandler { - internal CSharpOperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) : base(containingSymbol, rule) + internal CSharpOperationActionsHandler(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext context) + : base(context) { } - protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol) + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) { var method = invocationOperation.TargetMethod; if (invocationOperation.Arguments.Length == 1 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - method.ContainingSymbol.Equals(containingSymbol)) + method.ContainingSymbol.Equals(this.Context.EnumerableType) && + ((INamedTypeSymbol)(method.Parameters[0].Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) { - var targetType = invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation + return invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation ? convertionOperation.Operand.Type : invocationOperation.Arguments[0].Value.Type; - - return targetType as ITypeSymbol; } return null; @@ -181,23 +249,23 @@ protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocatio /// private sealed class BasicOperationActionsHandler : OperationActionsHandler { - internal BasicOperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) : base(containingSymbol, rule) + internal BasicOperationActionsHandler(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext context) + : base(context) { } - protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol) + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) { var method = invocationOperation.TargetMethod; if (invocationOperation.Arguments.Length == 0 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - method.ContainingSymbol.Equals(containingSymbol)) + method.ContainingSymbol.Equals(this.Context.EnumerableType) && + ((INamedTypeSymbol)(invocationOperation.Instance.Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) { - var targetType = invocationOperation.Instance is IConversionOperation convertionOperation - ? convertionOperation.Operand.Type - : invocationOperation.Instance.Type; - - return targetType as ITypeSymbol; + return invocationOperation.Instance is IConversionOperation convertionOperation + ? convertionOperation.Operand.Type + : invocationOperation.Instance.Type; } return null; diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index 4ebcb774ec..03bd12b107 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -17,87 +17,89 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 14 | CA1826 | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | 15 | [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | True | For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition. | 16 | [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | True | For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. | -17 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | -18 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | -19 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | -20 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | -21 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | -22 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | -23 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | -24 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | -25 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | -26 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -27 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | -28 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | -29 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -30 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -31 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | -32 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | -33 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -34 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -35 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | -36 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -37 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -38 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -39 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | -40 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -41 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -42 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -43 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -44 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -45 | CA2326 | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | -46 | CA2327 | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -47 | CA2328 | Ensure that JsonSerializerSettings are secure | Security | False | 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. | -48 | CA2329 | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | 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. | -49 | CA2330 | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | 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 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -51 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | 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}'. | -52 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | 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}'. | -53 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -54 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -55 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | 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}'. | -56 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -57 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -58 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -59 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -60 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -61 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -62 | CA3061 | Do Not Add Schema By URL | Security | True | 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. | -63 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | 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. | -64 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | 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. | -65 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -66 | CA5359 | Do Not Disable Certificate Validation | Security | True | 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. | -67 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | 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. | -68 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | 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. | -69 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | -70 | CA5363 | Do Not Disable Request Validation | Security | True | 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. | -71 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | -72 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | 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. | -73 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | 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. | -74 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | 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. | -75 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | 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. | -76 | CA5369 | Use XmlReader For Deserialize | Security | True | 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. | -77 | CA5370 | Use XmlReader For Validating Reader | Security | True | 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 | CA5371 | Use XmlReader For Schema Read | Security | True | 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 | CA5372 | Use XmlReader For XPathDocument | Security | True | 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 | CA5373 | Do not use obsolete key derivation function | Security | True | 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. | -81 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -82 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | 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. | -83 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -84 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | -85 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | 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. | -86 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | 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. | -87 | CA5380 | Do Not Add Certificates To Root Store | Security | True | 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. | -88 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | 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 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -90 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -91 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | -92 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -93 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | 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. | -94 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -95 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -96 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | 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. | -97 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -98 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | 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. | -99 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | 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. | -100 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +17 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | +18 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | +19 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | +20 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | +21 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | +22 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | +23 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | +24 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | +25 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | +26 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | +27 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | +28 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | +29 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | +30 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | +31 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | +32 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | +33 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | +34 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | +35 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | +36 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | +37 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +38 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +39 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +40 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | +41 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +42 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +43 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +44 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +45 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +46 | CA2326 | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | +47 | CA2327 | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +48 | CA2328 | Ensure that JsonSerializerSettings are secure | Security | False | 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 | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | 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 | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | 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) | Review code for SQL injection vulnerabilities | Security | False | 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) | Review code for XSS vulnerabilities | Security | False | 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) | Review code for file path injection vulnerabilities | Security | False | 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) | Review code for information disclosure vulnerabilities | Security | False | 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) | Review code for LDAP injection vulnerabilities | Security | False | 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) | Review code for process command injection vulnerabilities | Security | False | 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) | Review code for open redirect vulnerabilities | Security | False | 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) | Review code for XPath injection vulnerabilities | Security | False | 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) | Review code for XML injection vulnerabilities | Security | False | 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) | Review code for XAML injection vulnerabilities | Security | False | 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) | Review code for DLL injection vulnerabilities | Security | False | 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) | Review code for regex injection vulnerabilities | Security | False | 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 | Do Not Add Schema By URL | Security | True | 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) | Do Not Use Weak Cryptographic Algorithms | Security | True | 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) | Do Not Use Broken Cryptographic Algorithms | Security | True | 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 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | +67 | CA5359 | Do Not Disable Certificate Validation | Security | True | 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 | Do Not Call Dangerous Methods In Deserialization | Security | True | 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 | True | 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 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | +71 | CA5363 | Do Not Disable Request Validation | Security | True | 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 | False | Using a deprecated security protocol rather than the system default is risky. | +73 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | 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 | Use XmlReader For DataSet Read Xml | Security | True | 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 | Do Not Serialize Types With Pointer Fields | Security | False | 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 | Set ViewStateUserKey For Classes Derived From Page | Security | True | 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 | Use XmlReader For Deserialize | Security | True | 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 | Use XmlReader For Validating Reader | Security | True | 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 | Use XmlReader For Schema Read | Security | True | 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 | Use XmlReader For XPathDocument | Security | True | 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 | Do not use obsolete key derivation function | Security | True | 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 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +83 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | 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 | Use SharedAccessProtocol HttpsOnly | Security | True | 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 | Use Container Level Access Policy | Security | True | 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 | True | 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 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | 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 | Do Not Add Certificates To Root Store | Security | True | 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 | Ensure Certificates Are Not Added To Root Store | Security | True | 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 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +91 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +92 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | +93 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | 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 | 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 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +96 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +97 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | 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 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +99 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | 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. | +100 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | 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. | +101 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +102 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | 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. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index 78e0545aef..b40f49c50e 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -1741,6 +1741,25 @@ "Telemetry" ] } + }, + "CA5396": { + "id": "CA5396", + "shortDescription": "Set HttpOnly to true for HttpCookie", + "fullDescription": "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.", + "defaultLevel": "warning", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "SetHttpOnlyForHttpCookie", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Dataflow", + "Telemetry" + ] + } } } }, diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs deleted file mode 100644 index 5d28395be2..0000000000 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ /dev/null @@ -1,112 +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; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Operations; -using Xunit; -using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< - Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, - Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer>; -using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< - Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, - Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer>; - -namespace Microsoft.NetCore.Analyzers.Performance.UnitTests -{ - public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests - { - [Theory] - [InlineData("string[]", nameof(Array.Length))] - [InlineData("System.Collections.Immutable.ImmutableArray", nameof(ImmutableArray.Length))] - [InlineData("System.Collections.Generic.List", nameof(List.Count))] - [InlineData("System.Collections.Generic.IList", nameof(IList.Count))] - [InlineData("System.Collections.Generic.ICollection", nameof(ICollection.Count))] - public static Task CSharp_Fixed(string type, string propertyName) - => VerifyCS.VerifyCodeFixAsync( - $@"using System; -using System.Linq; -public static class C -{{ - public static {type} GetData() => default; - public static int M() => GetData().Count(); -}} -", - VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) - .WithLocation(6, 30) - .WithArguments(propertyName), - $@"using System; -using System.Linq; -public static class C -{{ - public static {type} GetData() => default; - public static int M() => GetData().{propertyName}; -}} -"); - - [Theory] - [InlineData("string()", nameof(Array.Length))] - [InlineData("System.Collections.Immutable.ImmutableArray(Of Integer)", nameof(ImmutableArray.Length))] - public static Task Basic_Fixed(string type, string propertyName) - => VerifyVB.VerifyCodeFixAsync( - $@"Imports System -Imports System.Linq -Public Module M - Public Function GetData() As {type} - Return Nothing - End Function - Public Function F() As Integer - Return GetData().Count() - End Function -End Module -", - VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) - .WithLocation(8, 16) - .WithArguments(propertyName), - $@"Imports System -Imports System.Linq -Public Module M - Public Function GetData() As {type} - Return Nothing - End Function - Public Function F() As Integer - Return GetData().{propertyName} - End Function -End Module -"); - - [Theory] - [InlineData("System.Collections.Generic.IEnumerable")] - public static Task CSharp_NoDiagnostic(string type) - => VerifyCS.VerifyAnalyzerAsync( - $@"using System; -using System.Linq; -public static class C -{{ - public static {type} GetData() => default; - public static int M() => GetData().Count(); -}} -"); - - [Theory] - [InlineData("System.Collections.Generic.List(Of Integer)")] - [InlineData("System.Collections.Generic.IList(Of Integer)")] - [InlineData("System.Collections.Generic.ICollection(Of Integer)")] - [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] - public static Task Basic_NoDiagnostic(string type) - => VerifyVB.VerifyAnalyzerAsync( - $@"Imports System -Imports System.Linq -Public Module M - Public Function GetData() As {type} - Return Nothing - End Function - Public Function F() As Integer - Return GetData().Count() - End Function -End Module -"); - } -} diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs new file mode 100644 index 0000000000..31524ed4f3 --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -0,0 +1,312 @@ +// 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; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Dynamic; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Operations; +using Xunit; +using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< + Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer>; +using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< + Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer>; + +namespace Microsoft.NetCore.Analyzers.Performance.UnitTests +{ + public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests + { + [Theory] + [InlineData("string[]", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray", nameof(ImmutableArray.Length))] + [InlineData("System.Collections.Generic.List", nameof(List.Count))] + [InlineData("System.Collections.Generic.IList", nameof(IList.Count))] + [InlineData("System.Collections.Generic.ICollection", nameof(ICollection.Count))] + public static Task CSharp_Fixed(string type, string propertyName) + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(6, 30) + .WithArguments(propertyName), + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().{propertyName}; +}} +"); + + [Theory] + [InlineData("string()", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray(Of Integer)", nameof(ImmutableArray.Length))] + public static Task Basic_Fixed(string type, string propertyName) + => VerifyVB.VerifyCodeFixAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(8, 16) + .WithArguments(propertyName), + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().{propertyName} + End Function +End Module +"); + + [Theory] + [InlineData("System.Collections.Generic.IEnumerable")] + public static Task CSharp_NoDiagnostic(string type) + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Theory] + [InlineData("System.Collections.Generic.List(Of Integer)")] + [InlineData("System.Collections.Generic.IList(Of Integer)")] + [InlineData("System.Collections.Generic.ICollection(Of Integer)")] + [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] + public static Task Basic_NoDiagnostic(string type) + => VerifyVB.VerifyAnalyzerAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module +"); + + [Fact] + public static Task CSharp_ICollectionOfTImplementerWithImplicitCount_Fixed() + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + public int Count => throw new NotImplementedException(); + public bool IsReadOnly => throw new NotImplementedException(); + public void Add(string item) => throw new NotImplementedException(); + public void Clear() => throw new NotImplementedException(); + public bool Contains(string item) => throw new NotImplementedException(); + public void CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + public bool Remove(string item) => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(18, 30) + .WithArguments("Count"), + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + public int Count => throw new NotImplementedException(); + public bool IsReadOnly => throw new NotImplementedException(); + public void Add(string item) => throw new NotImplementedException(); + public void Clear() => throw new NotImplementedException(); + public bool Contains(string item) => throw new NotImplementedException(); + public void CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + public bool Remove(string item) => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count; +}} +"); + + [Fact] + public static Task CSharp_ICollectionImplementerWithImplicitCount_Fixed() + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public class T : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{{ + public int Count => throw new NotImplementedException(); + bool global::System.Collections.ICollection.IsSynchronized => throw new NotImplementedException(); + object global::System.Collections.ICollection.SyncRoot => throw new NotImplementedException(); + void global::System.Collections.ICollection.CopyTo(global::System.Array array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(17, 30) + .WithArguments("Count"), + $@"using System; +using System.Linq; +public class T : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{{ + public int Count => throw new NotImplementedException(); + bool global::System.Collections.ICollection.IsSynchronized => throw new NotImplementedException(); + object global::System.Collections.ICollection.SyncRoot => throw new NotImplementedException(); + void global::System.Collections.ICollection.CopyTo(global::System.Array array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count; +}} +"); + + [Fact] + public static Task CSharp_ICollectionOfTImplementerWithExplicitCount_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + int global::System.Collections.Generic.ICollection.Count => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.IsReadOnly => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Add(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Clear() => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Contains(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Remove(string item) => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Fact] + public static Task CSharp_InterfaceShadowingICollectionOfT_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + @"using System; +using System.Linq; +public interface I : global::System.Collections.Generic.ICollection +{ + new int Count { get; } +} +public static class C +{ + public static I GetData() => default; + public static int M() => GetData().Count(); +} +"); + + [Fact] + public static Task CSharp_InterfaceShadowingICollection_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + @"using System; +using System.Linq; +public interface I : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{ + new int Count { get; } +} +public static class C +{ + public static I GetData() => default; + public static int M() => GetData().Count(); +} +"); + + [Fact] + public static Task CSharp_ClassShadowingICollectionOfT_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + public int Count => throw new NotImplementedException(); + int global::System.Collections.Generic.ICollection.Count => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.IsReadOnly => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Add(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Clear() => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Contains(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Remove(string item) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Fact] + public static Task CSharp_ClassShadowingICollection_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public class T : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{{ + public int Count => throw new NotImplementedException(); + int global::System.Collections.ICollection.Count => throw new NotImplementedException(); + bool global::System.Collections.ICollection.IsSynchronized => throw new NotImplementedException(); + object global::System.Collections.ICollection.SyncRoot => throw new NotImplementedException(); + void global::System.Collections.ICollection.CopyTo(global::System.Array array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +"); + } +} diff --git a/src/Utilities/Compiler/WellKnownTypes.cs b/src/Utilities/Compiler/WellKnownTypes.cs index 70baf6d32f..b2a59cb92c 100644 --- a/src/Utilities/Compiler/WellKnownTypes.cs +++ b/src/Utilities/Compiler/WellKnownTypes.cs @@ -528,6 +528,11 @@ public static INamedTypeSymbol HttpVerbs(Compilation compilation) return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpVerbs); } + public static INamedTypeSymbol ImmutableArray(Compilation compilation) + { + return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.ImmutableArray<>).FullName); + } + public static INamedTypeSymbol IImmutableDictionary(Compilation compilation) { return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableDictionary<,>).FullName);