As regras de segurança oferecem suporte a bibliotecas e aplicativos mais seguros. Essas regras ajudam a evitar falhas de segurança em seu programa. Se você desativar qualquer uma dessas regras, você deve marcar claramente o motivo no código e também informar o oficial de segurança designado para o seu projeto de desenvolvimento.

Nesta seção

Regra Descrição
CA2100: Revisar consultas SQL para vulnerabilidades de segurança Um método define a propriedade System.Data.IDbCommand.CommandText usando uma cadeia de caracteres que é criada a partir de um argumento de cadeia de caracteres para o método. Essa regra pressupõe que o argumento de cadeia de caracteres contenha a entrada do usuário. Uma cadeia de caracteres de comando SQL criada a partir da entrada do usuário é vulnerável a ataques de injeção de SQL.
CA2109: Revisar manipuladores de eventos visíveis Um método de manipulação de eventos público ou protegido foi detectado. Os métodos de manipulação de eventos não devem ser expostos, a menos que seja absolutamente necessário.
CA2119: Métodos de vedação que satisfazem interfaces privadas Um tipo público herdável fornece uma implementação de método substituível de uma interface interna (Friend no Visual Basic). Para corrigir uma violação dessa regra, evite que o método seja substituído fora do assembly.
CA2153: Evite manipular exceções de estado corrompidas Exceções de Estado Corrompido (CSE) indicam que existe corrupção de memória em seu processo. Detectá-los em vez de permitir que o processo falhe pode levar a vulnerabilidades de segurança se um invasor puder colocar uma exploração na região de memória corrompida.
CA2300: Não use o desserializador inseguro BinaryFormatter Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2301: Não chame BinaryFormatter.Deserialize sem primeiro definir BinaryFormatter.Binder Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2302: Verifique se BinaryFormatter.Binder está definido antes de chamar BinaryFormatter.Deserialize Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2305: Não use o desserializador inseguro LosFormatter Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2310: Não use o desserializador inseguro NetDataContractSerializer Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2311: Não desserializar sem primeiro definir NetDataContractSerializer.Binder Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2312: Certifique-se de que NetDataContractSerializer.Binder está definido antes de desserializar Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2315: Não use o desserializador inseguro ObjectStateFormatter Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2321: Não desserializar com JavaScriptSerializer usando um SimpleTypeResolver Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2322: Certifique-se de que JavaScriptSerializer não é inicializado com SimpleTypeResolver antes de desserializar Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2326: Não use valores TypeNameHandling diferentes de Nenhum Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2327: Não use JsonSerializerSettings inseguro Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2328: Certifique-se de que JsonSerializerSettings são seguros Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2329: Não desserializar com JsonSerializer usando uma configuração insegura Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2330: Certifique-se de que JsonSerializer tem uma configuração segura ao desserializar Desserializadores inseguros são vulneráveis ao desserializar dados não confiáveis. Um invasor pode modificar os dados serializados para incluir tipos inesperados para injetar objetos com efeitos colaterais mal-intencionados.
CA2350: Ensure DataTable.ReadXml()'s input is trusted When deserializing a DataTable with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There may be unknown remote code execution vulnerabilities.
CA2351: Ensure DataSet.ReadXml()'s input is trusted When deserializing a DataSet with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There may be unknown remote code execution vulnerabilities.
CA2352: Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks A class or struct marked with SerializableAttribute contains a DataSet or DataTable field or property, and doesn't have a GeneratedCodeAttribute.
CA2353: Unsafe DataSet or DataTable in serializable type A class or struct marked with an XML serialization attribute or a data contract attribute contains a DataSet or DataTable field or property.
CA2354: Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attack Deserializing with an System.Runtime.Serialization.IFormatter serialized, and the casted type's object graph can include a DataSet or DataTable.
CA2355: Unsafe DataSet or DataTable in deserialized object graph Deserializing when the casted or specified type's object graph can include a DataSet or DataTable.
CA2356: Unsafe DataSet or DataTable in web deserialized object graph A method with a System.Web.Services.WebMethodAttribute or System.ServiceModel.OperationContractAttribute has a parameter that may reference a DataSet or DataTable.
CA2361: Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data When deserializing a DataSet with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There may be unknown remote code execution vulnerabilities.
CA2362: Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks When deserializing untrusted input with BinaryFormatter and the deserialized object graph contains a DataSet or DataTable, an attacker can craft a malicious payload to perform a remote code execution attack.
CA3001: Review code for SQL injection vulnerabilities When working with untrusted input and SQL commands, be mindful of SQL injection attacks. An SQL injection attack can execute malicious SQL commands, compromising the security and integrity of your application.
CA3002: Review code for XSS vulnerabilities When working with untrusted input from web requests, be mindful of cross-site scripting (XSS) attacks. An XSS attack injects untrusted input into raw HTML output, allowing the attacker to execute malicious scripts or maliciously modify content in your web page.
CA3003: Review code for file path injection vulnerabilities When working with untrusted input from web requests, be mindful of using user-controlled input when specifying paths to files.
CA3004: Review code for information disclosure vulnerabilities Disclosing exception information gives attackers insight into the internals of your application, which can help attackers find other vulnerabilities to exploit.
CA3006: Review code for process command injection vulnerabilities When working with untrusted input, be mindful of command injection attacks. A command injection attack can execute malicious commands on the underlying operating system, compromising the security and integrity of your server.
CA3007: Review code for open redirect vulnerabilities When working with untrusted input, be mindful of open redirect vulnerabilities. An attacker can exploit an open redirect vulnerability to use your website to give the appearance of a legitimate URL, but redirect an unsuspecting visitor to a phishing or other malicious webpage.
CA3008: Review code for XPath injection vulnerabilities When working with untrusted input, be mindful of XPath injection attacks. Constructing XPath queries using untrusted input may allow an attacker to maliciously manipulate the query to return an unintended result, and possibly disclose the contents of the queried XML.
CA3009: Review code for XML injection vulnerabilities When working with untrusted input, be mindful of XML injection attacks.
CA3010: Review code for XAML injection vulnerabilities When working with untrusted input, be mindful of XAML injection attacks. XAML is a markup language that directly represents object instantiation and execution. That means elements created in XAML can interact with system resources (for example, network access and file system IO).
CA3011: Review code for DLL injection vulnerabilities When working with untrusted input, be mindful of loading untrusted code. If your web application loads untrusted code, an attacker may be able to inject malicious DLLs into your process and execute malicious code.
CA3012: Review code for regex injection vulnerabilities When working with untrusted input, be mindful of regex injection attacks. An attacker can use regex injection to maliciously modify a regular expression, to make the regex match unintended results, or to make the regex consume excessive CPU resulting in a Denial of Service attack.
CA3061: Do not add schema by URL Do not use the unsafe overload of the Add method because it may cause dangerous external references.
CA3075: Insecure DTD Processing If you use insecure DTDProcessing instances or reference external entity sources, the parser may accept untrusted input and disclose sensitive information to attackers.
CA3076: Insecure XSLT Script Execution If you execute Extensible StyleSheet Language Transformations (XSLT) in .NET applications insecurely, the processor may resolve untrusted URI references that could disclose sensitive information to attackers, leading to Denial of Service and Cross-Site attacks.
CA3077: Insecure Processing in API Design, XML Document and XML Text Reader When designing an API derived from XMLDocument and XMLTextReader, be mindful of DtdProcessing. Using insecure DTDProcessing instances when referencing or resolving external entity sources or setting insecure values in the XML may lead to information disclosure.
CA3147: Mark verb handlers with ValidateAntiForgeryToken When designing an ASP.NET MVC controller, be mindful of cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET MVC controller.
CA5350: Do Not Use Weak Cryptographic Algorithms Weak encryption algorithms and hashing functions are used today for a number of reasons, but they should not be used to guarantee the confidentiality or integrity of the data they protect. This rule triggers when it finds TripleDES, SHA1, or RIPEMD160 algorithms in the code.
CA5351: Do Not Use Broken Cryptographic Algorithms Broken cryptographic algorithms are not considered secure and their use should be strongly discouraged. This rule triggers when it finds the MD5 hash algorithm or either the DES or RC2 encryption algorithms in code.
CA5358: Do Not Use Unsafe Cipher Modes Do Not Use Unsafe Cipher Modes
CA5359: Do not disable certificate validation 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 , any certificate will pass validation.true
CA5360: Do not call dangerous methods in deserialization Insecure deserialization is a vulnerability that 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 that 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.
CA5361: Do not disable SChannel use of strong crypto Setting to weakens the cryptography used in outgoing Transport Layer Security (TLS) connections. Weaker cryptography can compromise the confidentiality of communication between your application and the server, making it easier for attackers to eavesdrop sensitive data.Switch.System.Net.DontEnableSchUseStrongCryptotrue
CA5362: Potential reference cycle in deserialized object graph If deserializing untrusted data, then any code processing the deserialized object graph needs to handle reference cycles without going into infinite loops. This includes both code that's part of a deserialization callback and code that processes the object graph after deserialization completed. Otherwise, an attacker could perform a Denial-of-Service attack with malicious data containing a reference cycle.
CA5363: Do not disable request validation Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content that can lead to injection attacks, including cross-site-scripting.
CA5364: Do not use deprecated security protocols Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Older protocol versions of TLS are less secure than TLS 1.2 and TLS 1.3 and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk.
CA5365: Do Not Disable HTTP Header Checking 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.
CA5366: Use XmlReader For DataSet Read XML Using a DataSet to read XML with untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled.
CA5367: Do Not Serialize Types With Pointer Fields This rule checks whether there's a serializable class with a pointer field or property. Members that can't be serialized can be a pointer, such as static members or fields marked with NonSerializedAttribute.
CA5368: Set ViewStateUserKey For Classes Derived From Page 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 attackers cannot use the variable to generate an attack. Otherwise, there will be vulnerabilities to cross-site request forgery.
CA5369: Use XmlReader for Deserialize Processing untrusted DTD and XML schemas may enable loading dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled.
CA5370: Use XmlReader for validating reader Processing untrusted DTD and XML schemas may enable loading dangerous external references. This dangerous loading can be restricted by using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled.
CA5371: Use XmlReader for schema read Processing untrusted DTD and XML schemas may enable loading dangerous external references. Using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled restricts this.
CA5372: Use XmlReader for XPathDocument Processing XML from untrusted data may load dangerous external references, which can be restricted by using an XmlReader with a secure resolver or with DTD processing disabled.
CA5373: Do not use obsolete key derivation function This rule detects the invocation of weak key derivation methods System.Security.Cryptography.PasswordDeriveBytes and . System.Security.Cryptography.PasswordDeriveBytes used a weak algorithm PBKDF1.Rfc2898DeriveBytes.CryptDeriveKey
CA5374: Do Not Use XslTransform This rule checks if System.Xml.Xsl.XslTransform is instantiated in the code. System.Xml.Xsl.XslTransform is now obsolete and shouldn't be used.
CA5375: Do not use account shared access signature An account SAS can delegate access to read, write, and delete operations on blob containers, tables, queues, and file shares that are not permitted with a service SAS. However, it doesn't support container-level policies and has less flexibility and control over the permissions that are granted. Once malicious users get it, your storage account will be compromised easily.
CA5376: Use SharedAccessProtocol HttpsOnly SAS is sensitive data that can't be transported in plain text on HTTP.
CA5377: Use container level access policy A container-level access policy can be modified or revoked at any time. It provides greater flexibility and control over the permissions that are granted.
CA5378: Do not disable ServicePointManagerSecurityProtocols Setting to limits Windows Communication Framework's (WCF) Transport Layer Security (TLS) connections to using TLS 1.0. That version of TLS will be deprecated.DisableUsingServicePointManagerSecurityProtocolstrue
CA5379: Ensure key derivation function algorithm is sufficiently strong The Rfc2898DeriveBytes class defaults to using the SHA1 algorithm. You should specify the hash algorithm to use in some overloads of the constructor with SHA256 or higher. Note, HashAlgorithm property only has a accessor and doesn't have a modifier.getoverriden
CA5380: Do not add certificates to root store This rule detects code that adds a certificate into the Trusted Root Certification Authorities certificate store. 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.
CA5381: Ensure certificates are not added to root store This rule detects code that potentially adds a certificate into the Trusted Root Certification Authorities certificate store. By default, the Trusted Root Certification Authorities certificate store is configured with a set of public certification authorities (CAs) that has met the requirements of the Microsoft Root Certificate Program.
CA5382: Use secure cookies in ASP.NET Core Applications available over HTTPS must use secure cookies, which indicate to the browser that the cookie should only be transmitted using Transport Layer Security (TLS).
CA5383: Ensure use secure cookies in ASP.NET Core Applications available over HTTPS must use secure cookies, which indicate to the browser that the cookie should only be transmitted using Transport Layer Security (TLS).
CA5384: Do not use digital signature algorithm (DSA) DSA is a weak asymmetric encryption algorithm.
CA5385: Use Rivest–Shamir–Adleman (RSA) algorithm with sufficient key size An RSA key smaller than 2048 bits is more vulnerable to brute force attacks.
CA5386: Avoid hardcoding SecurityProtocolType value Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Protocol versions TLS 1.0 and TLS 1.1 are deprecated, while TLS 1.2 and TLS 1.3 are current. In the future, TLS 1.2 and TLS 1.3 may be deprecated. To ensure that your application remains secure, avoid hardcoding a protocol version and target at least .NET Framework v4.7.1.
CA5387: Do not use weak key derivation function with insufficient iteration count This rule checks if a cryptographic key was generated by Rfc2898DeriveBytes with an iteration count of less than 100,000. A higher iteration count can help mitigate against dictionary attacks that try to guess the generated cryptographic key.
CA5388: Ensure sufficient iteration count when using weak key derivation function This rule checks if a cryptographic key was generated by Rfc2898DeriveBytes with an iteration count that may be less than 100,000. A higher iteration count can help mitigate against dictionary attacks that try to guess the generated cryptographic key.
CA5389: Do not add archive item's path to the target file system path File 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.
CA5390: Do not hard-code encryption key For a symmetric algorithm to be successful, the secret key must be known only to the sender and the receiver. When a key is hard-coded, it is easily discovered. Even with compiled binaries, it is easy for malicious users to extract it. Once the private key is compromised, the cipher text can be decrypted directly and is not protected anymore.
CA5391: Use antiforgery tokens in ASP.NET Core MVC controllers Handling a , , , or request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller.POSTPUTPATCHDELETE
CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes By default, P/Invoke functions 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.
CA5393: Do not use unsafe DllImportSearchPath value There could be a malicious DLL in the default DLL search directories and assembly directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory.
CA5394: Do not use insecure randomness Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated.
CA5395: Miss HttpVerb attribute for action methods All the action methods that create, edit, delete, or otherwise modify data needs to be protected with the antiforgery attribute from cross-site request forgery attacks. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data.
CA5396: Set HttpOnly to true for HttpCookie 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.
CA5397: Do not use deprecated SslProtocols values Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Older protocol versions of TLS are less secure than TLS 1.2 and TLS 1.3 and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk.
CA5398: Avoid hardcoded SslProtocols values O Transport Layer Security (TLS) protege a comunicação entre computadores, mais comumente com HTTPS (Hypertext Transfer Protocol Secure). As versões de protocolo TLS 1.0 e TLS 1.1 foram preteridas, enquanto TLS 1.2 e TLS 1.3 são atuais. No futuro, o TLS 1.2 e o TLS 1.3 podem ser preteridos. Para garantir que seu aplicativo permaneça seguro, evite codificar uma versão de protocolo.
CA5399: Desativar definitivamente a verificação da lista de revogação de certificados HttpClient Um certificado revogado não é mais confiável. Ele pode ser usado por invasores que passam alguns dados maliciosos ou roubam dados confidenciais na comunicação HTTPS.
CA5400: Verifique se a verificação da lista de revogação de certificados HttpClient não está desabilitada Um certificado revogado não é mais confiável. Ele pode ser usado por invasores que passam alguns dados maliciosos ou roubam dados confidenciais na comunicação HTTPS.
CA5401: Não use CreateEncryptor com IV não padrão A criptografia simétrica deve sempre usar um vetor de inicialização não repetível para evitar ataques de dicionário.
CA5402: Usar CreateEncryptor com o IV padrão A criptografia simétrica deve sempre usar um vetor de inicialização não repetível para evitar ataques de dicionário.
CA5403: Não codificar certificado Theorparameter de um X509Certificate ouX509Certificate2construtor é codificado.datarawData
CA5404: Não desative as verificações de validação de token As propriedades TokenValidationParametersque controlam a validação de token não devem ser definidas.false
CA5405: Nem sempre pule a validação de token em delegados O retorno de chamada atribuído aAudienceValidator ou LifetimeValidatorsempre retorna.true

Artigo Original