diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 799c6a982a..ae31f7a019 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -4,7 +4,7 @@ Example: [Microsoft.CodeAnalysis.FxCopAnalyzers](https://www.nuget.org/packages/ #### Package Version -Example: v2.9.4 (Latest) +Example: v2.9.5-beta1.final (Latest) #### Diagnostic ID diff --git a/Directory.Build.targets b/Directory.Build.targets index 2ea7e89d2e..7882a3975a 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,4 +1,16 @@ + + + + + EULA.rtf + true + + + ThirdPartyNotices.rtf + true + + \ No newline at end of file diff --git a/GuidelinesForNewRules.md b/GuidelinesForNewRules.md index 214b9641d8..f772d2a84c 100644 --- a/GuidelinesForNewRules.md +++ b/GuidelinesForNewRules.md @@ -3,16 +3,18 @@ 1. File an [issue](https://github.com/dotnet/roslyn-analyzers/issues/new) describing your proposed rule prior to working on a PR. This will ensure that the rule gets triaged and there is no duplicate work involved from an existing rule OR another contributor working on a similar rule. -2. Follow the below steps to choose the appropriate **rule ID** for the new rule: +2. Newly proposed rule would be tagged with [Needs-Review](https://github.com/dotnet/roslyn-analyzers/labels/Needs-Review) label. An [Approved-Rule](https://github.com/dotnet/roslyn-analyzers/labels/Approved-Rule) label indicates that the proposal has been reviewed and a PR to implement the rule would be accepted. + +3. Follow the below steps to choose the appropriate **rule ID** for the new rule: 1. Choose the **applicable 'category'** for the new rule. See [DiagnosticCategoryAndIdRanges.txt](.//src//Utilities//Compiler//DiagnosticCategoryAndIdRanges.txt) for current diagnostic categories, and the CA IDs reserved for each category. 2. Refer to the current [official documentation](https://docs.microsoft.com/visualstudio/code-quality/code-analysis-for-managed-code-warnings) for all CA rules by rule category. For example, while adding a new rule in the `Performance` category, you should navigate to the [Performance Rules section](https://docs.microsoft.com/visualstudio/code-quality/performance-warnings). Say you find that `CA1824` is the last documented rule ID in this category, and there are couple of doc issues on that page for very recently added rules `CA1825` and `CA1826` for which we documentation still needs to be added, then you can choose `CA1827` as the ID for your rule. 3. Double check that you have chosen an unused CA ID by searching the repo, for example use following query for `CA1827`: https://github.com/dotnet/roslyn-analyzers/search?q=CA1827. -3. Follow the below guidelines to choose the appropriate **analyzer package** for the new rule: +4. Follow the below guidelines to choose the appropriate **analyzer package** for the new rule: 1. Read the README section [here](https://github.com/dotnet/roslyn-analyzers#the-following-are-subpackages-or-nuget-dependencies-that-are-automatically-installed-when-you-install-the-microsoftcodeanalysisfxcopanalyzers-package) to get an idea of the content of the analyzer packages in the repo. 2. For majority of cases, you would be contributing to either [Microsoft.CodeQuality.Analyzers](https://github.com/dotnet/roslyn-analyzers#microsoftcodequalityanalyzers) or [Microsoft.NetCoreAnalyzers](https://github.com/dotnet/roslyn-analyzers#microsoftnetcoreanalyzers). Analyzers related to pure code quality improvements, which are not specific to any API should go into `Microsoft.CodeQuality.Analyzers`. Analyzers specific to usage of a specific .NetCore/.NetStandard API should go into `Microsoft.NetCore.Analyzers` package. 3. A good rule of thumb is that if your analyzer needs to invoke `GetTypeByMetadataName`, then most likely it is an API specific analyzer and belongs to `Microsoft.NetCore.Analyzers`. -4. **NOTE:** Once the new rule is merged, please make sure that you **file an issue OR submit a PR on the [official documentation page](https://docs.microsoft.com/visualstudio/code-quality/code-analysis-for-managed-code-warnings) for the rule's category**. If filing an issue, please include all relevant information in the issue to allow the documentation experts to easily author the documentation. For example, see [this issue](https://github.com/MicrosoftDocs/visualstudio-docs/issues/3454). +5. **NOTE:** Once the new rule is merged, it needs to be documented. Either submit a PR on the [official documentation page](https://docs.microsoft.com/visualstudio/code-quality/code-analysis-for-managed-code-warnings) for the rule's category (preferred) or [file an issue](https://github.com/MicrosoftDocs/visualstudio-docs/issues). If filing an issue, please include all relevant information in the issue to allow the documentation experts to easily author the documentation. For example, see [this issue](https://github.com/MicrosoftDocs/visualstudio-docs/issues/3454). diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 707ea998c1..bf99bee0d9 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -26,23 +26,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -License notice for Humanizer -------------------------------------- - -https://github.com/Humanizr/Humanizer - -Copyright (c) 2018 .NET Foundation and Contributors - -This software is licensed subject to the MIT license, available at -https://opensource.org/licenses/MIT - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - License notice for Roslyn Clr Heap Allocation Analyzer ------------------------------------- diff --git a/VERSIONING.md b/VERSIONING.md index 6f065ac42b..7176253d97 100644 --- a/VERSIONING.md +++ b/VERSIONING.md @@ -40,3 +40,4 @@ Sr. No. | Release Version | Commit Tag | Commit SHA 20 | 2.9.3 | v2.9.3 | [7f096af](https://github.com/dotnet/roslyn-analyzers/commit/7f096aff22c1fd35652d55a9405e13d421dfe512) | Microsoft.CodeAnalysis.Analyzers, Microsoft.CodeAnalysis.FxCopAnalyzers, Microsoft.CodeAnalysis.Metrics, Microsoft.CodeAnalysis.VersionCheckAnalyzer, Microsoft.CodeQuality.Analyzers, Microsoft.NetCore.Analyzers, Microsoft.NetFramework.Analyzers, Roslyn.Diagnostics.Analyzers, Microsoft.CodeAnalysis.PublicApiAnalyzers, Microsoft.CodeAnalysis.BannedApiAnalyzers 21 | 2.9.4-beta1.final (pre-release) | v2.9.4-beta1.final | [3b22a6a](https://github.com/dotnet/roslyn-analyzers/commit/3b22a6a82d450350ab0cf27504adab8d1226b2a8) | Microsoft.CodeAnalysis.Analyzers, Microsoft.CodeAnalysis.FxCopAnalyzers, Microsoft.CodeAnalysis.Metrics, Microsoft.CodeAnalysis.VersionCheckAnalyzer, Microsoft.CodeQuality.Analyzers, Microsoft.NetCore.Analyzers, Microsoft.NetFramework.Analyzers, Roslyn.Diagnostics.Analyzers, Microsoft.CodeAnalysis.PublicApiAnalyzers, Microsoft.CodeAnalysis.BannedApiAnalyzers, Microsoft.CodeAnalysis.FlowAnalysis.Utilities 22 | 2.9.4 | v2.9.4 | [a1a198d](https://github.com/dotnet/roslyn-analyzers/commit/a1a198d1c5d2359e93dd4ab4b1c4f7421512724e) | Microsoft.CodeAnalysis.Analyzers, Microsoft.CodeAnalysis.FxCopAnalyzers, Microsoft.CodeAnalysis.Metrics, Microsoft.CodeAnalysis.VersionCheckAnalyzer, Microsoft.CodeQuality.Analyzers, Microsoft.NetCore.Analyzers, Microsoft.NetFramework.Analyzers, Roslyn.Diagnostics.Analyzers, Microsoft.CodeAnalysis.PublicApiAnalyzers, Microsoft.CodeAnalysis.BannedApiAnalyzers, Microsoft.CodeAnalysis.FlowAnalysis.Utilities +23 | 2.9.5-beta1.final (pre-release) | v2.9.5-beta1.final | [494de6f](https://github.com/dotnet/roslyn-analyzers/commit/494de6f80082746e41d69355535f8dc3bfef494a) | Microsoft.CodeAnalysis.Analyzers, Microsoft.CodeAnalysis.FxCopAnalyzers, Microsoft.CodeAnalysis.Metrics, Microsoft.CodeAnalysis.VersionCheckAnalyzer, Microsoft.CodeQuality.Analyzers, Microsoft.NetCore.Analyzers, Microsoft.NetFramework.Analyzers, Roslyn.Diagnostics.Analyzers, Microsoft.CodeAnalysis.PublicApiAnalyzers, Microsoft.CodeAnalysis.BannedApiAnalyzers diff --git a/assets/ThirdPartyNotices.rtf b/assets/ThirdPartyNotices.rtf index b74371f578..444886afc9 100644 --- a/assets/ThirdPartyNotices.rtf +++ b/assets/ThirdPartyNotices.rtf @@ -1,54 +1,270 @@ -{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033\deflangfe1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Tahoma;}} -{\colortbl ;\red0\green0\blue255;} -{\*\generator Riched20 10.0.10037}{\*\mmathPr\mnaryLim0\mdispDef1\mwrapIndent1440 }\viewkind4\uc1 -\pard\nowidctlpar\sb120\sa120\f0\fs19 THIRD-PARTY SOFTWARE NOTICES AND INFORMATION\par +{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033\deflangfe1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Calibri;}{\f1\fnil\fcharset0 Calibri;}} +{\colortbl ;\red247\green247\blue247;\red0\green0\blue255;\red36\green41\blue46;\red255\green255\blue255;\red0\green0\blue0;} +{\*\generator Riched20 10.0.17134}{\*\mmathPr\mdispDef1\mwrapIndent1440 }\viewkind4\uc1 +\pard\widctlpar\highlight1\expndtw3\f0\fs22 NOTICES AND INFORMATION\par Do Not Translate or Localize\par \par -This file provides information regarding components that are being relicensed to you by Microsoft Corporation under Microsoft's software licensing terms. Microsoft Corporation reserves all rights not expressly granted herein.\par + +\pard\nowidctlpar The Roslyn Analyzers software incorporates material from third parties. Microsoft makes certain open source code available at {{\field{\*\fldinst{HYPERLINK https://3rdpartysource.microsoft.com }}{\fldrslt{https://3rdpartysource.microsoft.com\ul0\cf0}}}}\f0\fs22 , or you may send a check or money order for US $5.00, including the product name, the open source component name, and version number, to:\par + +\pard\widctlpar\par +Source Code Compliance Team\par +Microsoft Corporation\par +One Microsoft Way\par +Redmond, WA 98052\par +USA\par \par -%% \caps .NET Compiler Platform\caps0 NOTICES AND INFORMATION BEGIN HERE\par +Notwithstanding any other terms, you may reverse engineer this software to the extent required to debug changes to any libraries licensed under the GNU Lesser General Public License.\par +\par + +\pard\nowidctlpar\highlight0\expndtw0 %% \cf3\highlight4 .NET Compiler Platform \cf0\highlight0 NOTICES AND INFORMATION BEGIN HERE\par =========================================\par -Copyright (C) .NET Foundation. All rights reserved.\par -\par -Apache License, Version 2.0\par -Apache License\par -Version 2.0, January 2004\par -{{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs19\par -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par -1. Definitions.\par -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\par -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\par -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\par -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.\par -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\par -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\par -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\par -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\par -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."\par -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\par -2. Grant of Copyright License.\par -Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\par -3. Grant of Patent License.\par -Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\par -4. Redistribution.\par -You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\par -1. You must give any other recipients of the Work or Derivative Works a copy of this License; and\par -2. You must cause any modified files to carry prominent notices stating that You changed the files; and\par -3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\par -4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.\par -You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\par -5. Submission of Contributions.\par -Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\par -6. Trademarks.\par -This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\par -7. Disclaimer of Warranty.\par -Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\par -8. Limitation of Liability.\par -In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\par -9. Accepting Warranty or Additional Liability.\par -While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\par -END OF TERMS AND CONDITIONS\par +Copyright (c) .NET Foundation. All rights reserved.\par +\par + +\pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5 Apache License\par + Version 2.0, January 2004\par + {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par +\par + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par +\par + 1. Definitions.\par +\par + "License" shall mean the terms and conditions for use, reproduction,\par + and distribution as defined by Sections 1 through 9 of this document.\par +\par + "Licensor" shall mean the copyright owner or entity authorized by\par + the copyright owner that is granting the License.\par +\par + "Legal Entity" shall mean the union of the acting entity and all\par + other entities that control, are controlled by, or are under common\par + control with that entity. For the purposes of this definition,\par + "control" means (i) the power, direct or indirect, to cause the\par + direction or management of such entity, whether by contract or\par + otherwise, or (ii) ownership of fifty percent (50%) or more of the\par + outstanding shares, or (iii) beneficial ownership of such entity.\par +\par + "You" (or "Your") shall mean an individual or Legal Entity\par + exercising permissions granted by this License.\par +\par + "Source" form shall mean the preferred form for making modifications,\par + including but not limited to software source code, documentation\par + source, and configuration files.\par +\par + "Object" form shall mean any form resulting from mechanical\par + transformation or translation of a Source form, including but\par + not limited to compiled object code, generated documentation,\par + and conversions to other media types.\par +\par + "Work" shall mean the work of authorship, whether in Source or\par + Object form, made available under the License, as indicated by a\par + copyright notice that is included in or attached to the work\par + (an example is provided in the Appendix below).\par +\par + "Derivative Works" shall mean any work, whether in Source or Object\par + form, that is based on (or derived from) the Work and for which the\par + editorial revisions, annotations, elaborations, or other modifications\par + represent, as a whole, an original work of authorship. For the purposes\par + of this License, Derivative Works shall not include works that remain\par + separable from, or merely link (or bind by name) to the interfaces of,\par + the Work and Derivative Works thereof.\par +\par + "Contribution" shall mean any work of authorship, including\par + the original version of the Work and any modifications or additions\par + to that Work or Derivative Works thereof, that is intentionally\par + submitted to Licensor for inclusion in the Work by the copyright owner\par + or by an individual or Legal Entity authorized to submit on behalf of\par + the copyright owner. For the purposes of this definition, "submitted"\par + means any form of electronic, verbal, or written communication sent\par + to the Licensor or its representatives, including but not limited to\par + communication on electronic mailing lists, source code control systems,\par + and issue tracking systems that are managed by, or on behalf of, the\par + Licensor for the purpose of discussing and improving the Work, but\par + excluding communication that is conspicuously marked or otherwise\par + designated in writing by the copyright owner as "Not a Contribution."\par +\par + "Contributor" shall mean Licensor and any individual or Legal Entity\par + on behalf of whom a Contribution has been received by Licensor and\par + subsequently incorporated within the Work.\par +\par + 2. Grant of Copyright License. Subject to the terms and conditions of\par + this License, each Contributor hereby grants to You a perpetual,\par + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par + copyright license to reproduce, prepare Derivative Works of,\par + publicly display, publicly perform, sublicense, and distribute the\par + Work and such Derivative Works in Source or Object form.\par +\par + 3. Grant of Patent License. Subject to the terms and conditions of\par + this License, each Contributor hereby grants to You a perpetual,\par + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par + (except as stated in this section) patent license to make, have made,\par + use, offer to sell, sell, import, and otherwise transfer the Work,\par + where such license applies only to those patent claims licensable\par + by such Contributor that are necessarily infringed by their\par + Contribution(s) alone or by combination of their Contribution(s)\par + with the Work to which such Contribution(s) was submitted. If You\par + institute patent litigation against any entity (including a\par + cross-claim or counterclaim in a lawsuit) alleging that the Work\par + or a Contribution incorporated within the Work constitutes direct\par + or contributory patent infringement, then any patent licenses\par + granted to You under this License for that Work shall terminate\par + as of the date such litigation is filed.\par +\par + 4. Redistribution. You may reproduce and distribute copies of the\par + Work or Derivative Works thereof in any medium, with or without\par + modifications, and in Source or Object form, provided that You\par + meet the following conditions:\par +\par + (a) You must give any other recipients of the Work or\par + Derivative Works a copy of this License; and\par +\par + (b) You must cause any modified files to carry prominent notices\par + stating that You changed the files; and\par +\par + (c) You must retain, in the Source form of any Derivative Works\par + that You distribute, all copyright, patent, trademark, and\par + attribution notices from the Source form of the Work,\par + excluding those notices that do not pertain to any part of\par + the Derivative Works; and\par +\par + (d) If the Work includes a "NOTICE" text file as part of its\par + distribution, then any Derivative Works that You distribute must\par + include a readable copy of the attribution notices contained\par + within such NOTICE file, excluding those notices that do not\par + pertain to any part of the Derivative Works, in at least one\par + of the following places: within a NOTICE text file distributed\par + as part of the Derivative Works; within the Source form or\par + documentation, if provided along with the Derivative Works; or,\par + within a display generated by the Derivative Works, if and\par + wherever such third-party notices normally appear. The contents\par + of the NOTICE file are for informational purposes only and\par + do not modify the License. You may add Your own attribution\par + notices within Derivative Works that You distribute, alongside\par + or as an addendum to the NOTICE text from the Work, provided\par + that such additional attribution notices cannot be construed\par + as modifying the License.\par +\par + You may add Your own copyright statement to Your modifications and\par + may provide additional or different license terms and conditions\par + for use, reproduction, or distribution of Your modifications, or\par + for any such Derivative Works as a whole, provided Your use,\par + reproduction, and distribution of the Work otherwise complies with\par + the conditions stated in this License.\par +\par + 5. Submission of Contributions. Unless You explicitly state otherwise,\par + any Contribution intentionally submitted for inclusion in the Work\par + by You to the Licensor shall be under the terms and conditions of\par + this License, without any additional terms or conditions.\par + Notwithstanding the above, nothing herein shall supersede or modify\par + the terms of any separate license agreement you may have executed\par + with Licensor regarding such Contributions.\par +\par + 6. Trademarks. This License does not grant permission to use the trade\par + names, trademarks, service marks, or product names of the Licensor,\par + except as required for reasonable and customary use in describing the\par + origin of the Work and reproducing the content of the NOTICE file.\par +\par + 7. Disclaimer of Warranty. Unless required by applicable law or\par + agreed to in writing, Licensor provides the Work (and each\par + Contributor provides its Contributions) on an "AS IS" BASIS,\par + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par + implied, including, without limitation, any warranties or conditions\par + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par + PARTICULAR PURPOSE. You are solely responsible for determining the\par + appropriateness of using or redistributing the Work and assume any\par + risks associated with Your exercise of permissions under this License.\par +\par + 8. Limitation of Liability. In no event and under no legal theory,\par + whether in tort (including negligence), contract, or otherwise,\par + unless required by applicable law (such as deliberate and grossly\par + negligent acts) or agreed to in writing, shall any Contributor be\par + liable to You for damages, including any direct, indirect, special,\par + incidental, or consequential damages of any character arising as a\par + result of this License or out of the use or inability to use the\par + Work (including but not limited to damages for loss of goodwill,\par + work stoppage, computer failure or malfunction, or any and all\par + other commercial damages or losses), even if such Contributor\par + has been advised of the possibility of such damages.\par +\par + 9. Accepting Warranty or Additional Liability. While redistributing\par + the Work or Derivative Works thereof, You may choose to offer,\par + and charge a fee for, acceptance of support, warranty, indemnity,\par + or other liability obligations and/or rights consistent with this\par + License. However, in accepting such obligations, You may act only\par + on Your own behalf and on Your sole responsibility, not on behalf\par + of any other Contributor, and only if You agree to indemnify,\par + defend, and hold each Contributor harmless for any liability\par + incurred by, or claims asserted against, such Contributor by reason\par + of your accepting any such warranty or additional liability.\par +\par + END OF TERMS AND CONDITIONS\par +\par + APPENDIX: How to apply the Apache License to your work.\par +\par + To apply the Apache License to your work, attach the following\par + boilerplate notice, with the fields enclosed by brackets "[]"\par + replaced with your own identifying information. (Don't include\par + the brackets!) The text should be enclosed in the appropriate\par + comment syntax for the file format. We also recommend that a\par + file or class name and description of purpose be included on the\par + same "printed page" as the copyright notice for easier\par + identification within third-party archives.\par +\par + Copyright [yyyy] [name of copyright owner]\par +\par + Licensed under the Apache License, Version 2.0 (the "License");\par + you may not use this file except in compliance with the License.\par + You may obtain a copy of the License at\par +\par + {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par +\par + Unless required by applicable law or agreed to in writing, software\par + distributed under the License is distributed on an "AS IS" BASIS,\par + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par + See the License for the specific language governing permissions and\par + limitations under the License.\par + +\pard\nowidctlpar\cf0 =========================================\par +END OF \cf3\highlight4 .NET Compiler Platform \cf0\highlight0 NOTICES AND INFORMATION\par +\par +%% Humanizer NOTICES AND INFORMATION BEGIN HERE\par +=========================================\par +The MIT License (MIT)\par +\par +Copyright (c) 2012-2014 Mehdi Khalili\par +\par +Permission is hereby granted, free of charge, to any person obtaining a copy\par +of this software and associated documentation files (the "Software"), to deal\par +in the Software without restriction, including without limitation the rights\par +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\par +copies of the Software, and to permit persons to whom the Software is\par +furnished to do so, subject to the following conditions:\par +\par +The above copyright notice and this permission notice shall be included in\par +all copies or substantial portions of the Software.\par +\par +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\par +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\par +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\par +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\par +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\par +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\par +THE SOFTWARE.\par +\par +==============================================================================\par +\par +Inflector ({{\field{\*\fldinst{HYPERLINK https://github.com/srkirkland/Inflector }}{\fldrslt{https://github.com/srkirkland/Inflector\ul0\cf0}}}}\f0\fs22 )\par +The MIT License (MIT)\par +Copyright (c) 2013 Scott Kirkland\par +\par +==============================================================================\par +\par +ByteSize ({{\field{\*\fldinst{HYPERLINK https://github.com/omar/ByteSize }}{\fldrslt{https://github.com/omar/ByteSize\ul0\cf0}}}}\f0\fs22 )\par +The MIT License (MIT)\par +Copyright (c) 2013-2014 Omar Khudeira ({{\field{\*\fldinst{HYPERLINK http://omar.io }}{\fldrslt{http://omar.io\ul0\cf0}}}}\f0\fs22 )\par +\par +==============================================================================\par =========================================\par -END OF \caps .NET Compiler Platform\caps0 NOTICES AND INFORMATION\par +END OF Humanizer NOTICES AND INFORMATION\f1\lang9\par } \ No newline at end of file diff --git a/eng/Analyzers_NonShippingRules.ruleset b/eng/Analyzers_NonShippingRules.ruleset index 9d67b91e3a..11dfde9320 100644 --- a/eng/Analyzers_NonShippingRules.ruleset +++ b/eng/Analyzers_NonShippingRules.ruleset @@ -28,4 +28,8 @@ + + + + diff --git a/eng/GenerateAnalyzerNuspec.csx b/eng/GenerateAnalyzerNuspec.csx index a7110c86b9..521bb82bec 100644 --- a/eng/GenerateAnalyzerNuspec.csx +++ b/eng/GenerateAnalyzerNuspec.csx @@ -225,6 +225,7 @@ if (legacyRulesets.Length > 0) } } +result.AppendLine(FileElement(Path.Combine(assetsDir, "EULA.rtf"), "")); result.AppendLine(FileElement(Path.Combine(assetsDir, "ThirdPartyNotices.rtf"), "")); result.AppendLine(@" "); diff --git a/eng/Versions.props b/eng/Versions.props index 7229609f39..9a2a375a5c 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -4,7 +4,7 @@ 2.9.5 2.9.6 - beta1 + beta2 true @@ -20,10 +20,10 @@ 2.9.0 - 3.0.0 - 2.9.4 + 3.3.1-beta3-final + 2.9.5-beta1.final 3.0.0-beta2.19218.3+e96bad97 - 2.11.0-beta2-63603-03 + 3.3.0-beta2-19376-02 2.0.0-pre-20160714 diff --git a/src/GenerateAnalyzerRulesets/Program.cs b/src/GenerateAnalyzerRulesets/Program.cs index 4f8b482d10..5412fafb4d 100644 --- a/src/GenerateAnalyzerRulesets/Program.cs +++ b/src/GenerateAnalyzerRulesets/Program.cs @@ -277,32 +277,24 @@ bool shouldSkipRule(DiagnosticDescriptor rule) string getRuleAction(DiagnosticDescriptor rule) { - switch (rulesetKind) + return rulesetKind switch { - case RulesetKind.CategoryDefault: - return getRuleActionCore(enable: categoryPass && rule.IsEnabledByDefault); + RulesetKind.CategoryDefault => getRuleActionCore(enable: categoryPass && rule.IsEnabledByDefault), - case RulesetKind.CategoryEnabled: - return getRuleActionCore(enable: categoryPass); + RulesetKind.CategoryEnabled => getRuleActionCore(enable: categoryPass), - case RulesetKind.CustomTagDefault: - return getRuleActionCore(enable: customTagPass && rule.IsEnabledByDefault); + RulesetKind.CustomTagDefault => getRuleActionCore(enable: customTagPass && rule.IsEnabledByDefault), - case RulesetKind.CustomTagEnabled: - return getRuleActionCore(enable: customTagPass); + RulesetKind.CustomTagEnabled => getRuleActionCore(enable: customTagPass), - case RulesetKind.AllDefault: - return getRuleActionCore(enable: rule.IsEnabledByDefault); + RulesetKind.AllDefault => getRuleActionCore(enable: rule.IsEnabledByDefault), - case RulesetKind.AllEnabled: - return getRuleActionCore(enable: true); + RulesetKind.AllEnabled => getRuleActionCore(enable: true), - case RulesetKind.AllDisabled: - return getRuleActionCore(enable: false); + RulesetKind.AllDisabled => getRuleActionCore(enable: false), - default: - throw new InvalidProgramException(); - } + _ => throw new InvalidProgramException(), + }; string getRuleActionCore(bool enable) { diff --git a/src/MetaCompilation.Analyzers/Setup/source.extension.vsixmanifest b/src/MetaCompilation.Analyzers/Setup/source.extension.vsixmanifest index 53cb77a5e8..fa69f0840a 100644 --- a/src/MetaCompilation.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/MetaCompilation.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ MetaCompilation Analyzers This is a sample diagnostic extension for the .NET Compiler Platform ("Roslyn"). + EULA.rtf diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Setup/source.extension.vsixmanifest b/src/Microsoft.CodeAnalysis.Analyzers/Setup/source.extension.vsixmanifest index 47e107136a..9f30967fa2 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/Microsoft.CodeAnalysis.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ .NET Compiler Platform (Roslyn) Analyzers Analyzers for .NET Compiler Platform (Roslyn) APIs. + EULA.rtf diff --git a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs index 5f4f6455a9..9e1f179267 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/MissingKindArgumentToRegisterActionRuleTests.cs @@ -240,24 +240,16 @@ private static DiagnosticResult GetBasicExpectedDiagnostic(int line, int column, private static DiagnosticResult GetExpectedDiagnostic(int line, int column, MissingKindArgument kind) { - string message; - switch (kind) + var message = kind switch { - case MissingKindArgument.SymbolKind: - message = CodeAnalysisDiagnosticsResources.MissingSymbolKindArgumentToRegisterActionMessage; - break; + MissingKindArgument.SymbolKind => CodeAnalysisDiagnosticsResources.MissingSymbolKindArgumentToRegisterActionMessage, - case MissingKindArgument.SyntaxKind: - message = CodeAnalysisDiagnosticsResources.MissingSyntaxKindArgumentToRegisterActionMessage; - break; + MissingKindArgument.SyntaxKind => CodeAnalysisDiagnosticsResources.MissingSyntaxKindArgumentToRegisterActionMessage, - case MissingKindArgument.OperationKind: - message = CodeAnalysisDiagnosticsResources.MissingOperationKindArgumentToRegisterActionMessage; - break; + MissingKindArgument.OperationKind => CodeAnalysisDiagnosticsResources.MissingOperationKindArgumentToRegisterActionMessage, - default: - throw new ArgumentException("Unsupported argument kind", nameof(kind)); - } + _ => throw new ArgumentException("Unsupported argument kind", nameof(kind)), + }; return new DiagnosticResult(DiagnosticIds.MissingKindArgumentToRegisterActionRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(line, column) diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs index 8e9f33cad7..18dc5d3e17 100644 --- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs @@ -78,33 +78,17 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte compilationContext.RegisterOperationAction( context => { - ISymbol symbol; - switch (context.Operation) + var symbol = context.Operation switch { - case IObjectCreationOperation objectCreation: - symbol = objectCreation.Constructor; - break; - case IInvocationOperation invocation: - symbol = invocation.TargetMethod; - break; - case IMemberReferenceOperation memberReference: - symbol = memberReference.Member; - break; - case IConversionOperation conversion: - symbol = conversion.OperatorMethod; - break; - case IUnaryOperation unary: - symbol = unary.OperatorMethod; - break; - case IBinaryOperation binary: - symbol = binary.OperatorMethod; - break; - case IIncrementOrDecrementOperation incrementOrDecrement: - symbol = incrementOrDecrement.OperatorMethod; - break; - default: - throw new NotImplementedException($"Unhandled OperationKind: {context.Operation.Kind}"); - } + IObjectCreationOperation objectCreation => objectCreation.Constructor, + IInvocationOperation invocation => invocation.TargetMethod, + IMemberReferenceOperation memberReference => memberReference.Member, + IConversionOperation conversion => conversion.OperatorMethod, + IUnaryOperation unary => unary.OperatorMethod, + IBinaryOperation binary => binary.OperatorMethod, + IIncrementOrDecrementOperation incrementOrDecrement => incrementOrDecrement.OperatorMethod, + _ => throw new NotImplementedException($"Unhandled OperationKind: {context.Operation.Kind}"), + }; VerifySymbol(symbol, context.Operation.Syntax, context.ReportDiagnostic, restrictedInternalsVisibleToMap, namespaceToIsBannedMap); diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Setup/source.extension.vsixmanifest b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Setup/source.extension.vsixmanifest index b5a1477567..38f38d4837 100644 --- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Setup/source.extension.vsixmanifest +++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Banned API Analyzers Banned API Analyzers + EULA.rtf diff --git a/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt b/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt index 18e52f2712..03ba62dfad 100644 --- a/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt +++ b/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt @@ -350,7 +350,7 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContainsN Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContainsNonLiteralState.Undefined = 1 -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContainsNonLiteralState Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.IsLiteralState.get -> bool -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.TryGetSingleLiteral(out T literalValue) -> bool +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.TryGetSingleNonNullLiteral(out T literalValue) -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.LiteralValues.get -> System.Collections.Immutable.ImmutableHashSet Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.NonLiteralState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContainsNonLiteralState Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAnalysis @@ -631,6 +631,7 @@ static readonly Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis.Dis static readonly Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis.DisposeAbstractValue.Unknown -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis.DisposeAbstractValue static Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.ContainsEmptyStringLiteralState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue static Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.ContainsOneIntergralLiteralState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue +static Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.ContainsNullLiteralState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue static Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.ContainsZeroIntergralLiteralState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue static Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.DoesNotContainLiteralOrNonLiteralState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue static Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue.InvalidState.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis.ValueContentAbstractValue diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index 19b444865c..e6baaecb16 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -124,81 +124,82 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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 | False | 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 | False | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -191 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | -192 | 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. | -193 | 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. | -194 | 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 | -195 | CA5395 | Miss HttpVerb attribute for action methods | Security | False | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | -196 | 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. | -197 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -198 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -199 | CA5399 | Definitely disable HttpClient certificate revocation list check | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -200 | CA5400 | Ensure HttpClient certificate revocation list check is not disabled | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | -201 | 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. | +124 | CA2246 | Assigning symbol and its member in the same statement. | Usage | True | False | Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. | +125 | [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. | +126 | [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. | +127 | [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. | +128 | [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. | +129 | [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. | +130 | [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. | +131 | [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. | +132 | [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. | +133 | [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. | +134 | [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. | +135 | [CA2326](https://docs.microsoft.com/visualstudio/code-quality/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. | +136 | [CA2327](https://docs.microsoft.com/visualstudio/code-quality/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. | +137 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/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. | +138 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/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. | +139 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/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. | +140 | [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}'. | +141 | [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}'. | +142 | [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}'. | +143 | [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}'. | +144 | [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}'. | +145 | [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}'. | +146 | [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}'. | +147 | [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}'. | +148 | [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}'. | +149 | [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}'. | +150 | [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}'. | +151 | [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}'. | +152 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/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. | +153 | [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.  | +154 | [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. | +155 | [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.  | +156 | [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}. | +157 | [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. | +158 | [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. | +159 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | +160 | 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. | +161 | 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. | +162 | [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. | +163 | 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. | +164 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/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. | +165 | [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. | +166 | 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. | +167 | 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. | +168 | 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. | +169 | 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. | +170 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/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. | +171 | [CA5370](https://docs.microsoft.com/visualstudio/code-quality/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. | +172 | [CA5371](https://docs.microsoft.com/visualstudio/code-quality/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. | +173 | [CA5372](https://docs.microsoft.com/visualstudio/code-quality/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. | +174 | [CA5373](https://docs.microsoft.com/visualstudio/code-quality/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. | +175 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +176 | 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. | +177 | 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. | +178 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | +179 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | 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. | +180 | 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. | +181 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/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. | +182 | [CA5381](https://docs.microsoft.com/visualstudio/code-quality/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. | +183 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +184 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +185 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | +186 | 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. | +187 | [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. | +188 | 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). | +189 | 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). | +190 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +191 | CA5390 | Do Not Hard Code Encryption Key | Security | False | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +192 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | +193 | CA5392 | 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. | +194 | 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. | +195 | 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 | +196 | CA5395 | Miss HttpVerb attribute for action methods | Security | False | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | +197 | CA5396 | 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. | +198 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +199 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +200 | CA5399 | Definitely disable HttpClient certificate revocation list check | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +201 | CA5400 | Ensure HttpClient certificate revocation list check is not disabled | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +202 | 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 7995cfb167..d09daed252 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -1489,6 +1489,20 @@ "Visual Basic" ] } + }, + "CA2246": { + "id": "CA2246", + "shortDescription": "Assigning symbol and its member in the same statement.", + "fullDescription": "Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements.", + "defaultLevel": "warning", + "properties": { + "category": "Usage", + "isEnabledByDefault": true, + "typeName": "AssigningSymbolAndItsMemberInSameStatement", + "languages": [ + "C#" + ] + } } } }, @@ -2935,6 +2949,7 @@ "shortDescription": "Do Not Add Schema By URL", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca3061", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3083,6 +3098,7 @@ "shortDescription": "Do Not Disable Request Validation", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5363", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3192,6 +3208,7 @@ "shortDescription": "Use XmlReader For Deserialize", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5369", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3210,6 +3227,7 @@ "shortDescription": "Use XmlReader For Validating Reader", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5370", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3228,6 +3246,7 @@ "shortDescription": "Use XmlReader For Schema Read", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5371", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3246,6 +3265,7 @@ "shortDescription": "Use XmlReader For XPathDocument", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5372", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3264,6 +3284,7 @@ "shortDescription": "Do not use obsolete key derivation function", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5373", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3394,6 +3415,7 @@ "shortDescription": "Do Not Add Certificates To Root Store", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5380", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3413,6 +3435,7 @@ "shortDescription": "Ensure Certificates Are Not Added To Root Store", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5381", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -3563,6 +3586,7 @@ "shortDescription": "Do Not Add Archive Item's Path To The Target File System Path", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5389", "properties": { "category": "Security", "isEnabledByDefault": false, diff --git a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ja.xlf b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ja.xlf index b38c9c254b..7aa782bfa5 100644 --- a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ja.xlf +++ b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ja.xlf @@ -4,7 +4,7 @@ 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. - このパッケージのアナライザーを正しく実行するには、特定のバージョン以上の Microsoft.CodeAnalysis が必要です。正しいアナライザー バージョンをインストールするには、https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions を参照してください。 + このパッケージのアナライザーを正しく実行するには、特定のバージョン以上の Microsoft.CodeAnalysis が必要です。正しいアナライザー バージョンをインストールするには、https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versionsを参照してください。 diff --git a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.pl.xlf b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.pl.xlf index f968d09030..34544ffca9 100644 --- a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.pl.xlf +++ b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.pl.xlf @@ -9,7 +9,7 @@ Version mismatch between the analyzer package '{0}' and Microsoft.CodeAnalysis '{1}'. Certain analyzers in this package will not run until the version mismatch is fixed. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. - Niezgodność wersji między pakietem analizatorów \x201e{0} i metodą Microsoft.CodeAnalysis \x201e{1}”. Niektóre analizatory w tym pakiecie nie uruchomią się, dopóki niezgodność wersji nie zostanie naprawiona. Skorzystaj ze strony https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions, aby zainstalować prawidłową wersję analizatora. + Niezgodność wersji między pakietem analizatorów „{0} i metodą Microsoft.CodeAnalysis „{1}”. Niektóre analizatory w tym pakiecie nie uruchomią się, dopóki niezgodność wersji nie zostanie naprawiona. Skorzystaj ze strony https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions, aby zainstalować prawidłową wersję analizatora. diff --git a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ru.xlf b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ru.xlf index b363f61792..5e5d533af9 100644 --- a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ru.xlf +++ b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.ru.xlf @@ -4,12 +4,12 @@ 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. - Для правильной работы анализаторам в этом пакете требуется определенная минимальная версия Microsoft.CodeAnalysis. Сведения об установке подходящей версии анализатора см. на странице https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions + Для правильной работы анализаторам в этом пакете требуется определенная минимальная версия Microsoft.CodeAnalysis. Сведения об установке подходящей версии анализатора см. на странице https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions. Version mismatch between the analyzer package '{0}' and Microsoft.CodeAnalysis '{1}'. Certain analyzers in this package will not run until the version mismatch is fixed. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. - Несоответствие версий между пакетом анализатора "{0}" и Microsoft.CodeAnalysis "{1}". Отдельные анализаторы в этом пакете не будут работать до устранения этого несоответствия. Сведения об установке подходящей версии анализатора см. на странице https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions + Несоответствие версий между пакетом анализатора "{0}" и Microsoft.CodeAnalysis "{1}". Отдельные анализаторы в этом пакете не будут работать до устранения этого несоответствия. Сведения об установке подходящей версии анализатора см. на странице https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions. diff --git a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.tr.xlf b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.tr.xlf index b72f150b4d..76d2cfaac5 100644 --- a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.tr.xlf +++ b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/xlf/MicrosoftCodeAnalysisVersionCheckAnalyzerResources.tr.xlf @@ -4,7 +4,7 @@ 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. - Bu paketteki çözümleyicilerin düzgün yürütme yapabilmesi için Microsoft.CodeAnalysis'in belirli bir en düşük sürümü gerekir. Doğru çözümleyici sürümünü yüklemek için https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versionsadresine başvurun. + Bu paketteki çözümleyicilerin düzgün yürütme yapabilmesi için Microsoft.CodeAnalysis'in belirli bir en düşük sürümü gerekir. Doğru çözümleyici sürümünü yüklemek için https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions adresine başvurun. diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs index 4acc8ebe10..43dbf28d20 100644 --- a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs @@ -62,16 +62,14 @@ private static bool IsEmptyBlockBody(BlockSyntax blockBody, SemanticModel semant private static bool IsEmptyExpressionBody(ArrowExpressionClauseSyntax expressionBody, SemanticModel semanticModel) { - switch (expressionBody.Expression.Kind()) + return (expressionBody.Expression.Kind()) switch { - case SyntaxKind.ThrowExpression: - return true; + SyntaxKind.ThrowExpression => true, - case SyntaxKind.InvocationExpression: - return IsConditionalInvocation((InvocationExpressionSyntax)expressionBody.Expression, semanticModel); - } + SyntaxKind.InvocationExpression => IsConditionalInvocation((InvocationExpressionSyntax)expressionBody.Expression, semanticModel), - return false; + _ => false, + }; } private static bool IsConditionalInvocation(InvocationExpressionSyntax invocationExpr, SemanticModel semanticModel) diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs index c8324a5bf1..c967b6ef91 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.Fixer.cs index f4c8f5b6eb..3098859738 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.Fixer.cs @@ -2,7 +2,6 @@ using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs index 7df36fb5e0..e3ce67c49f 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs @@ -185,20 +185,16 @@ private static IEnumerable GetExplicitImplementations(ISymbol symbol) return null; } - switch (symbol.Kind) + return symbol.Kind switch { - case SymbolKind.Method: - return ((IMethodSymbol)symbol).ExplicitInterfaceImplementations; + SymbolKind.Method => ((IMethodSymbol)symbol).ExplicitInterfaceImplementations, - case SymbolKind.Event: - return ((IEventSymbol)symbol).ExplicitInterfaceImplementations; + SymbolKind.Event => ((IEventSymbol)symbol).ExplicitInterfaceImplementations, - case SymbolKind.Property: - return ((IPropertySymbol)symbol).ExplicitInterfaceImplementations; + SymbolKind.Property => ((IPropertySymbol)symbol).ExplicitInterfaceImplementations, - default: - return null; - } + _ => null, + }; } private static async Task MakeContainingTypeSealed(Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorsShouldHaveSymmetricalOverloads.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorsShouldHaveSymmetricalOverloads.Fixer.cs index 77139d6821..2f635ded60 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorsShouldHaveSymmetricalOverloads.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorsShouldHaveSymmetricalOverloads.Fixer.cs @@ -106,17 +106,16 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) private static OperatorKind GetInvertedOperatorKind(IMethodSymbol containingOperator) { - switch (containingOperator.Name) + return containingOperator.Name switch { - case WellKnownMemberNames.EqualityOperatorName: return OperatorKind.Inequality; - case WellKnownMemberNames.InequalityOperatorName: return OperatorKind.Equality; - case WellKnownMemberNames.LessThanOperatorName: return OperatorKind.GreaterThan; - case WellKnownMemberNames.LessThanOrEqualOperatorName: return OperatorKind.GreaterThanOrEqual; - case WellKnownMemberNames.GreaterThanOperatorName: return OperatorKind.LessThan; - case WellKnownMemberNames.GreaterThanOrEqualOperatorName: return OperatorKind.LessThanOrEqual; - } - - throw new InvalidOperationException(); + WellKnownMemberNames.EqualityOperatorName => OperatorKind.Inequality, + WellKnownMemberNames.InequalityOperatorName => OperatorKind.Equality, + WellKnownMemberNames.LessThanOperatorName => OperatorKind.GreaterThan, + WellKnownMemberNames.LessThanOrEqualOperatorName => OperatorKind.GreaterThanOrEqual, + WellKnownMemberNames.GreaterThanOperatorName => OperatorKind.LessThan, + WellKnownMemberNames.GreaterThanOrEqualOperatorName => OperatorKind.LessThanOrEqual, + _ => throw new InvalidOperationException(), + }; } } } \ No newline at end of file diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverloadOperatorEqualsOnOverridingValueTypeEquals.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverloadOperatorEqualsOnOverridingValueTypeEquals.Fixer.cs index 828fad13fc..4ecb35a03f 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverloadOperatorEqualsOnOverridingValueTypeEquals.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverloadOperatorEqualsOnOverridingValueTypeEquals.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsOnOverloadingOperatorEquals.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsOnOverloadingOperatorEquals.Fixer.cs index 3877c948fc..61e4f104e5 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsOnOverloadingOperatorEquals.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsOnOverloadingOperatorEquals.Fixer.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideGetHashCodeOnOverridingEquals.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideGetHashCodeOnOverridingEquals.Fixer.cs index b620e327e1..0867bd5b08 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideGetHashCodeOnOverridingEquals.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideGetHashCodeOnOverridingEquals.Fixer.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.Fixer.cs index 00cb0e7642..30238f2bae 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.Fixer.cs index 9ba1a31232..e78227d0df 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs index 15de6a30a4..5021534be0 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs @@ -288,23 +288,18 @@ static bool isApplicableByDefault(string ruleId, SymbolKind symbolKind) } // Compat: we match the default threshold values for old FxCop implementation. - switch (ruleId) + return ruleId switch { - case CA1501RuleId: - return 5; + CA1501RuleId => 5, - case CA1502RuleId: - return 25; + CA1502RuleId => 25, - case CA1505RuleId: - return 10; + CA1505RuleId => 10, - case CA1506RuleId: - return symbolKind == SymbolKind.NamedType ? 95 : (uint)40; + CA1506RuleId => symbolKind == SymbolKind.NamedType ? 95 : (uint)40, - default: - throw new NotImplementedException(); - } + _ => throw new NotImplementedException(), + }; } }); } diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/MicrosoftCodeQualityAnalyzersResources.resx b/src/Microsoft.CodeQuality.Analyzers/Core/MicrosoftCodeQualityAnalyzersResources.resx index 5fc9391b6a..302c58cfc6 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/MicrosoftCodeQualityAnalyzersResources.resx +++ b/src/Microsoft.CodeQuality.Analyzers/Core/MicrosoftCodeQualityAnalyzersResources.resx @@ -1334,4 +1334,13 @@ The property {0} should not be assigned to itself. + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + Assigning symbol and its member in the same statement. + \ No newline at end of file diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs new file mode 100644 index 0000000000..aa73798712 --- /dev/null +++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs @@ -0,0 +1,100 @@ +// 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.Immutable; +using Analyzer.Utilities; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines +{ + /// + /// CA2246: Prevent objects from being referenced in statements where they are reassigned + /// + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class AssigningSymbolAndItsMemberInSameStatement : DiagnosticAnalyzer + { + internal const string RuleId = "CA2246"; + + private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.AssigningSymbolAndItsMemberInSameStatementTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); + private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.AssigningSymbolAndItsMemberInSameStatementMessage), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); + private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.AssigningSymbolAndItsMemberInSameStatementDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); + + internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId, + s_localizableTitle, + s_localizableMessage, + DiagnosticCategory.Usage, + DiagnosticHelpers.DefaultDiagnosticSeverity, + DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, + s_localizableDescription); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + + context.RegisterOperationAction(AnalyzeAssignment, OperationKind.SimpleAssignment); + } + + private void AnalyzeAssignment(OperationAnalysisContext context) + { + var assignmentOperation = (ISimpleAssignmentOperation)context.Operation; + + // Check if there are more then one assignment in a statement + if (!(assignmentOperation.Target is IMemberReferenceOperation operationTarget)) + { + return; + } + + // This analyzer makes sense only for reference type objects + if (operationTarget.Instance?.Type.IsValueType == true) + { + return; + } + + // Search for object equal to operationTarget.Instance further in assignment chain + bool isViolationFound = false; + if (operationTarget.Instance is ILocalReferenceOperation localInstance) + { + isViolationFound = AnalyzeAssignmentToMember(assignmentOperation, localInstance, (a, b) => a.Local.Equals(b.Local)); + } + else if (operationTarget.Instance is IMemberReferenceOperation memberInstance) + { + isViolationFound = AnalyzeAssignmentToMember(assignmentOperation, memberInstance, (a, b) => a.Member.Equals(b.Member) && a.Instance?.Syntax.ToString() == b.Instance?.Syntax.ToString()); + } + else if (operationTarget.Instance is IParameterReferenceOperation parameterInstance) + { + isViolationFound = AnalyzeAssignmentToMember(assignmentOperation, parameterInstance, (a, b) => a.Parameter.Equals(b.Parameter)); + } + else + { + return; + } + + if (isViolationFound) + { + var diagnostic = Diagnostic.Create(Rule, operationTarget.Syntax.GetLocation(), operationTarget.Instance.Syntax, operationTarget.Member.Name); + context.ReportDiagnostic(diagnostic); + } + } + + private static bool AnalyzeAssignmentToMember(ISimpleAssignmentOperation assignmentOperation, T instance, Func equalityComparer) where T : class, IOperation + { + // Check every simple assignments target in a statement for equality to `instance` + while (assignmentOperation.Value.Kind == OperationKind.SimpleAssignment) + { + assignmentOperation = (ISimpleAssignmentOperation)assignmentOperation.Value; + + var operationValue = assignmentOperation.Target as T; + if (equalityComparer(instance, operationValue)) + { + return true; + } + } + return false; + } + } +} diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/RemoveEmptyFinalizers.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/RemoveEmptyFinalizers.Fixer.cs index c14bba943b..027e33ab19 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/RemoveEmptyFinalizers.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/RemoveEmptyFinalizers.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs index 942f019b72..2590c15e83 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.cs.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.cs.xlf index 678c1e84bf..04e41a7c3e 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.cs.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.cs.xlf @@ -7,6 +7,21 @@ Připojit .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Vyhněte se Async Void. @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Podpis metody obsahuje parametr, který se nepoužívá v těle metody. + Vyhněte se v kódu nepoužitým parametrům. Pokud parametr nelze odebrat, změňte jeho název tak, aby začínal podtržítkem, za kterým volitelně následuje celé číslo, například _, _1, _2 atd. Tyto řetězce se považují za názvy speciálních symbolů pro vyřazení. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.de.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.de.xlf index 4e54818d8f..b57851f6b0 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.de.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.de.xlf @@ -7,6 +7,21 @@ "ConfigureAwait(true)" anfügen + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Async Void vermeiden @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Eine Methodensignatur enthält einen Parameter, der im Methodentext nicht verwendet wird. + Vermeiden Sie nicht verwendete Parameter in Ihrem Code. Wenn der Parameter nicht entfernt werden kann, ändern Sie dessen Namen so, dass er mit einem Unterstrich beginnt, dem optional eine Zahl angefügt wird. Beispiel: "_", "_1", "_2" usw. Diese werden als spezielle Symbolnamen für Ausschussparameter behandelt. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.es.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.es.xlf index e8a179017a..a0aef542d9 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.es.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.es.xlf @@ -7,6 +7,21 @@ Anexar .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Evitar async void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Una signatura de método incluye un parámetro que no se usa en el cuerpo del método. + Evite los parámetros sin usar en el código. Si el parámetro no se puede quitar, cámbielo de nombre para que empiece por un carácter de subrayado, seguido opcionalmente por un entero, como "_", "_1", "_2", etc. Estos se tratan como nombres de símbolos de descarte especiales. @@ -1804,7 +1819,7 @@ The property {0} should not be assigned to itself. - La propiedad {0} no debe asignarse a sí misma. + La propiedad {0} no debe asignarse a sí misma. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.fr.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.fr.xlf index c6fbc12d4b..34d10025a9 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.fr.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.fr.xlf @@ -7,6 +7,21 @@ Ajouter .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Éviter Async Void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Une signature de méthode inclut un paramètre qui n'est pas utilisé dans le corps de la méthode. + Évitez les paramètres inutilisés dans votre code. Évitez les paramètres inutilisés dans votre code. Si vous ne pouvez pas supprimer un paramètre, changez son nom en le faisant commencer par un trait de soulignement éventuellement suivi d'un entier, par exemple '_', '_1', '_2', etc. Ces types d'élément sont traités en tant que noms de symboles discard spéciaux. @@ -1804,7 +1819,7 @@ The property {0} should not be assigned to itself. - La propriété {0} ne doit pas être assignée à elle-même. + La propriété {0} ne doit pas être assignée à elle-même. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.it.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.it.xlf index 126468ddf2..91fc429240 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.it.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.it.xlf @@ -7,6 +7,21 @@ Accoda .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Evitare metodi asincroni void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Una firma di metodo include un parametro non usato nel corpo del metodo. + Evitare parametri inutilizzati nel codice. Se non è possibile rimuovere il parametro, modificarne il nome in modo che inizi con un carattere di sottolineatura e, facoltativamente, sia seguito da un numero intero, seguito da un numero intero, ad esempio '_', '_1', '_1', '_2' e così via. Questi vengono considerati come nomi di simboli speciali di rimozione. @@ -1809,7 +1824,7 @@ Do not assign a property to itself. - Non assegnare una proprietà a se stessa. + Non assegnare una proprietà a se stessa. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ja.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ja.xlf index d6a413b0c3..2c24cd26e1 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ja.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ja.xlf @@ -7,6 +7,21 @@ .ConfigureAwait(true) を追加します + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Async Void を使用しないでください @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - メソッドのシグネチャに、メソッドの本体で使用されていないパラメーターが含まれています。 + コード内に使用されないパラメーターを指定しないでください。パラメーターを削除できない場合は、パラメーターの名前をアンダースコアの後にオプションで整数が続く名前 ('_'、'_1'、'_2' など) に変更してください。これらは、特別なディスカード シンボル名として扱われます。 diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ko.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ko.xlf index 2d9f33f0ba..1419222343 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ko.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ko.xlf @@ -7,6 +7,21 @@ .ConfigureAwait(true) 추가 + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Async Void를 사용하지 마세요. @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - 메서드 시그니처가 메서드 본문에서 사용하지 않는 매개 변수를 포함합니다. + 코드에 사용되지 않는 매개 변수를 사용하지 않도록 합니다. 매개 변수를 제거할 수 없는 경우 이름을 변경하여 밑줄로 시작하고 필요에 따라 뒤에 정수가 있도록 합니다(예: '_', '_1', '_2' 등). 해당 이름은 특수 무시 기호 이름으로 처리됩니다. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pl.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pl.xlf index 3ed0f59895..e7fed8d697 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pl.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pl.xlf @@ -7,6 +7,21 @@ Dołącz element .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Unikaj metod async void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Sygnatura metody zawiera parametr, który nie jest używany w treści metody. + Unikaj nieużywanych parametrów w kodzie. Jeśli nie można usunąć parametru, zmień jego nazwę, tak aby rozpoczynała się od znaku podkreślenia, a opcjonalnie następowała po niej liczba całkowita, taka jak „_”, „_1”, „_2” itp. Są one traktowane jako specjalne nazwy symboli odrzucenia. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pt-BR.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pt-BR.xlf index 1058e028d2..dc5bf3b9dd 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pt-BR.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.pt-BR.xlf @@ -7,6 +7,21 @@ Acrescentar .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Evitar async void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Uma assinatura de método inclui um parâmetro não usado no corpo do método. + Evite parâmetros não usados no código. Se o parâmetro não puder ser removido, altere seu nome para que ele comece com um sublinhado e seja seguido opcionalmente por um inteiro, como '_', '_1', '_2' etc. Esses nomes são tratados como nomes de símbolo de descarte especiais. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ru.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ru.xlf index b98cb6e91c..4c8e6ae113 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ru.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.ru.xlf @@ -7,6 +7,21 @@ Добавить .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Избегание Async Void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Сигнатура метода содержит параметр, который не используется в теле метода. + Избегайте неиспользуемых параметров в коде. Если параметр не может быть удален, измените его имя так, чтобы оно начиналось с символа подчеркивания, за которым при необходимости следует целое число, например, "_", "_1", "_2" и т. д. Эти имена рассматриваются как специальные имена для освобождаемых параметров. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.tr.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.tr.xlf index ad8c04c195..49d772185a 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.tr.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.tr.xlf @@ -7,6 +7,21 @@ Ekle .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void Async Void Kullanmayın @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - Yöntem imzası yöntem gövdesinde kullanılmayan bir parametre içeriyor. + Kodunuzda, kullanılmayan parametrelerden kaçının. Parametre kaldırılamıyorsa adını, bir alt çizgiyle başlayan ve isteğe bağlı olarak ardından tamsayı gelen ('_', '_1', '_2' gibi) bir değerle değiştirin. Bu değerler özel atılabilir değişken sembolü olarak işlenir. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hans.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hans.xlf index 572803d20c..6ad957d082 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hans.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hans.xlf @@ -7,6 +7,21 @@ 附加 .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void 避免使用 Async Void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - 方法签名包括一个未在方法体中使用的参数。 + 请避免在代码中使用未使用的参数。如果无法删除该参数,请更改其名称,使其以下划线开头,也可在下划线后面跟一个整数(如 "_"、"_1"、"_2" 等)。这些被视为特殊丢弃符号名。 diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hant.xlf b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hant.xlf index 7442f2e73d..d535b6895d 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hant.xlf +++ b/src/Microsoft.CodeQuality.Analyzers/Core/xlf/MicrosoftCodeQualityAnalyzersResources.zh-Hant.xlf @@ -7,6 +7,21 @@ 附加 .ConfigureAwait(true) + + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. + + + + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + Symbol '{0}' and its member '{1}' are both assigned in the same statement. You are at risk of assigning the member of an unintended object. + + + + Assigning symbol and its member in the same statement. + Assigning symbol and its member in the same statement. + + Avoid Async Void 避免 Async Void @@ -1709,7 +1724,7 @@ Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. - 方法簽章包括並未用於方法主體中的參數。 + 請避免在您的程式碼中使用參數。如果無法移除參數,請變更其名稱,使其以底線開頭,並可選擇在後面接著整數,例如 '_'、'_1'、'_2' 等。這些會視為特殊的捨棄符號名稱。 diff --git a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md index bd2bc4a99c..bd771450b2 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md +++ b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md @@ -87,3 +87,4 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 84 | [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. | 85 | 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. | 86 | CA2245 | Do not assign a property to itself. | Usage | True | False | The property {0} should not be assigned to itself. | +87 | CA2246 | Assigning symbol and its member in the same statement. | Usage | True | False | Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements. | diff --git a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif index 882bc119f4..a8ceb04c8e 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif +++ b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif @@ -1474,6 +1474,20 @@ "Visual Basic" ] } + }, + "CA2246": { + "id": "CA2246", + "shortDescription": "Assigning symbol and its member in the same statement.", + "fullDescription": "Assigning to a symbol and its member (field/property) in the same statement is not recommended. It is not clear if the member access was intended to use symbol's old value prior to the assignment or new value from the assignment in this statement. For clarity, consider splitting the assignments into separate statements.", + "defaultLevel": "warning", + "properties": { + "category": "Usage", + "isEnabledByDefault": true, + "typeName": "AssigningSymbolAndItsMemberInSameStatement", + "languages": [ + "C#" + ] + } } } }, diff --git a/src/Microsoft.CodeQuality.Analyzers/Setup/source.extension.vsixmanifest b/src/Microsoft.CodeQuality.Analyzers/Setup/source.extension.vsixmanifest index c157f08337..4872d21e3a 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/Microsoft.CodeQuality.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Microsoft.CodeQuality Analyzers Microsoft.CodeQuality Analyzers + EULA.rtf diff --git a/src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscoresTests.cs b/src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscoresTests.cs index 41316f664a..4699d02f42 100644 --- a/src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscoresTests.cs +++ b/src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscoresTests.cs @@ -882,27 +882,18 @@ private void Verify(string source, string language, DiagnosticAnalyzer analyzer, private static string GetApproriateMessage(SymbolKind symbolKind) { - switch (symbolKind) + return symbolKind switch { - case SymbolKind.Assembly: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly; - case SymbolKind.Namespace: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace; - case SymbolKind.NamedType: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType; - case SymbolKind.Member: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember; - case SymbolKind.DelegateParameter: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter; - case SymbolKind.MemberParameter: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter; - case SymbolKind.TypeTypeParameter: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter; - case SymbolKind.MethodTypeParameter: - return MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter; - default: - throw new System.Exception("Unknown Symbol Kind"); - } + SymbolKind.Assembly => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly, + SymbolKind.Namespace => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace, + SymbolKind.NamedType => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType, + SymbolKind.Member => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember, + SymbolKind.DelegateParameter => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter, + SymbolKind.MemberParameter => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter, + SymbolKind.TypeTypeParameter => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter, + SymbolKind.MethodTypeParameter => MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter, + _ => throw new System.Exception("Unknown Symbol Kind"), + }; } private enum SymbolKind diff --git a/src/Microsoft.CodeQuality.Analyzers/UnitTests/Maintainability/AvoidDeadConditionalCode_ValueContentAnalysis.cs b/src/Microsoft.CodeQuality.Analyzers/UnitTests/Maintainability/AvoidDeadConditionalCode_ValueContentAnalysis.cs index b695af4a14..649eeb97b4 100644 --- a/src/Microsoft.CodeQuality.Analyzers/UnitTests/Maintainability/AvoidDeadConditionalCode_ValueContentAnalysis.cs +++ b/src/Microsoft.CodeQuality.Analyzers/UnitTests/Maintainability/AvoidDeadConditionalCode_ValueContentAnalysis.cs @@ -2640,5 +2640,37 @@ End If End Sub End Module"); } + + [Trait(Traits.DataflowAnalysis, Traits.Dataflow.ValueContentAnalysis)] + [Fact] + public void ValueContentAnalysis_MergeForUnreachableCode() + { + var editorconfig = "dotnet_code_quality.interprocedural_analysis_kind = ContextSensitive"; + + VerifyCSharp(@" +using System; + +public class C +{ + public void Load(C c1, C c2) + { + var x = c1 ?? c2; + this.Load(null); + } + + public void Load(Uri productFileUrl, Uri originalLocation = null) + { + if (productFileUrl == null) + { + throw new ArgumentNullException(); + } + + Uri feedLocationUri = originalLocation ?? productFileUrl; + + _ = feedLocationUri.LocalPath; + } +} +", GetEditorConfigAdditionalFile(editorconfig)); + } } } diff --git a/src/Microsoft.CodeQuality.Analyzers/UnitTests/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatementTests.cs b/src/Microsoft.CodeQuality.Analyzers/UnitTests/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatementTests.cs new file mode 100644 index 0000000000..e9dfdf21a1 --- /dev/null +++ b/src/Microsoft.CodeQuality.Analyzers/UnitTests/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatementTests.cs @@ -0,0 +1,320 @@ +// 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 Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeQuality.Analyzers.QualityGuidelines; +using Test.Utilities; +using Xunit; + +namespace Microsoft.CodeQuality.Analyzers.UnitTests.QualityGuidelines +{ + public partial class AssigningSymbolAndItsMemberInSameStatementTests : DiagnosticAnalyzerTestBase + { + protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() + { + return new AssigningSymbolAndItsMemberInSameStatement(); + } + + protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() + { + return new AssigningSymbolAndItsMemberInSameStatement(); + } + + [Fact] + public void CSharpReassignLocalVariableAndReferToItsField() + { + VerifyCSharp(@" +public class C +{ + public C Field; +} + +public class Test +{ + public void Method() + { + C a = new C(), b = new C(); + a.Field = a = b; + } +} +", + GetCSharpResultAt(12, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "a", "Field")); + } + + [Fact] + public void CSharpReassignLocalVariableAndReferToItsProperty() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method() + { + C a = new C(), b = new C(), c; + a.Property = c = a = b; + } +} +", + GetCSharpResultAt(12, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "a", "Property")); + } + + [Fact] + public void CSharpReassignLocalVariablesPropertyAndReferToItsProperty() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method() + { + C a = new C(), b = new C(); + a.Property.Property = a.Property = b; + } +} +", + GetCSharpResultAt(12, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "a.Property", "Property")); + } + + [Fact] + public void CSharpReassignLocalVariableAndItsPropertyAndReferToItsProperty() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method() + { + C a = new C(), b = new C(); + a.Property.Property = a.Property = a = b; + } +} +", + GetCSharpResultAt(12, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "a.Property", "Property"), + GetCSharpResultAt(12, 31, AssigningSymbolAndItsMemberInSameStatement.Rule, "a", "Property")); + } + + [Fact] + public void CSharpReferToFieldOfReferenceTypeLocalVariableAfterItsReassignment() + { + VerifyCSharp(@" +public class C +{ + public C Field; +} + +public class Test +{ + static C x, y; + + public void Method() + { + x.Field = x = y; + } +} +", + GetCSharpResultAt(13, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "x", "Field")); + } + + [Fact] + public void CSharpReassignGlobalVariableAndReferToItsField() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + static C x, y; + + public void Method() + { + x.Property.Property = x.Property = y; + } +} +", + GetCSharpResultAt(13, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "x.Property", "Property")); + } + + [Fact] + public void CSharpReassignGlobalVariableAndItsPropertyAndReferToItsProperty() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + static C x, y; + + public void Method() + { + x.Property.Property = x.Property = x = y; + } +} +", + GetCSharpResultAt(13, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "x.Property", "Property"), + GetCSharpResultAt(13, 31, AssigningSymbolAndItsMemberInSameStatement.Rule, "x", "Property")); + } + + + [Fact] + public void CSharpReassignGlobalPropertyAndItsPropertyAndReferToItsProperty() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + static C x { get; set; } + static C y { get; set; } + + public void Method() + { + x.Property.Property = x.Property = x = y; + } +} +", + GetCSharpResultAt(14, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "x.Property", "Property"), + GetCSharpResultAt(14, 31, AssigningSymbolAndItsMemberInSameStatement.Rule, "x", "Property")); + } + + [Fact] + public void CSharpReassignSecondLocalVariableAndReferToItsPropertyOfFirstVariable() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method() + { + C a = new C(), b; + a.Property = b = a; + } +} +"); + } + + [Fact] + public void CSharpReassignPropertyOfFirstLocalVariableWithSecondAndReferToPropertyOfSecondVariable() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method() + { + C a = new C(), b = new C(), c; + b.Property.Property = a.Property = b; + } +} +"); + } + + [Fact] + public void CSharpReassignPropertyOfFirstLocalVariableWithThirdAndReferToPropertyOfSecondVariable() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method() + { + C a = new C(), b = new C(), c = new C(); + b.Property.Property = a.Property = c; + } +} +"); + } + + [Fact] + public void CSharpReassignMethodParameterAndReferToItsProperty() + { + VerifyCSharp(@" +public class C +{ + public C Property { get; set; } +} + +public class Test +{ + public void Method(C b) + { + C a = new C(); + b.Property = b = a; + } +} +", + GetCSharpResultAt(12, 9, AssigningSymbolAndItsMemberInSameStatement.Rule, "b", "Property")); + } + + [Fact] + public void CSharpReassignLocalValueTypeVariableAndReferToItsField() + { + VerifyCSharp(@" +public struct S +{ + public S Field; +} + +public class Test +{ + public void Method() + { + S a, b; + a.Field = a = b; + } +} +", TestValidationMode.AllowCompileErrors); + } + + [Fact] + public void CSharpReassignLocalValueTypeVariableAndReferToItsProperty() + { + VerifyCSharp(@" +public struct S +{ + public S Property { get; set; } +} + +public class Test +{ + public void Method() + { + S a, b; + a.Property = c = a = b; + } +} +", TestValidationMode.AllowCompileErrors); + } + } +} diff --git a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs index bd37250f54..e7db0e2ba1 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.Fixer.cs index f1dc2c6b38..e7446b4a20 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs index 9449b9b60d..db2796be3a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/TestForNaNCorrectly.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/TestForNaNCorrectly.Fixer.cs index 7c0ddba1ab..59db43bba7 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/TestForNaNCorrectly.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/TestForNaNCorrectly.Fixer.cs @@ -2,7 +2,6 @@ using Microsoft.CodeAnalysis.CodeFixes; using System.Collections.Immutable; -using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs index f49cbe3808..390efa104c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Immutable; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddArchiveItemPathToTheTargetFileSystemPath.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddArchiveItemPathToTheTargetFileSystemPath.cs index a013875d02..95f1befb4f 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddArchiveItemPathToTheTargetFileSystemPath.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddArchiveItemPathToTheTargetFileSystemPath.cs @@ -18,7 +18,7 @@ public class DoNotAddArchiveItemPathToTheTargetFileSystemPath : SourceTriggeredT nameof(MicrosoftNetCoreAnalyzersResources.DoNotAddArchiveItemPathToTheTargetFileSystemPath), nameof(MicrosoftNetCoreAnalyzersResources.DoNotAddArchiveItemPathToTheTargetFileSystemPathMessage), isEnabledByDefault: false, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5389", descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.DoNotAddArchiveItemPathToTheTargetFileSystemPathDescription), customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs index 0d8eaeca93..7b48ab9c56 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs @@ -34,7 +34,7 @@ public sealed class DoNotAddSchemaByURL : DiagnosticAnalyzer DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca3061", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpClientCRLCheck.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpClientCRLCheck.cs index cc4d5ece2c..a35161e7ce 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpClientCRLCheck.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpClientCRLCheck.cs @@ -83,31 +83,23 @@ class DoNotDisableHttpClientCRLCheck : DiagnosticAnalyzer "handler", (IMethodSymbol methodSymbol, PropertySetAbstractValue abstractValue) => { - switch (abstractValue[ServerCertificateValidationCallbackIndex]) + return (abstractValue[ServerCertificateValidationCallbackIndex]) switch { - case PropertySetAbstractValueKind.Flagged: - switch (abstractValue[CheckCertificateRevocationListIndex]) - { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => (abstractValue[CheckCertificateRevocationListIndex]) switch + { + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }, - case PropertySetAbstractValueKind.MaybeFlagged: - switch (abstractValue[CheckCertificateRevocationListIndex]) - { - case PropertySetAbstractValueKind.Unflagged: - return HazardousUsageEvaluationResult.Unflagged; - default: - return HazardousUsageEvaluationResult.MaybeFlagged; - } + PropertySetAbstractValueKind.MaybeFlagged => (abstractValue[CheckCertificateRevocationListIndex]) switch + { + PropertySetAbstractValueKind.Unflagged => HazardousUsageEvaluationResult.Unflagged, + _ => HazardousUsageEvaluationResult.MaybeFlagged, + }, - default: - return HazardousUsageEvaluationResult.Unflagged; - } + _ => HazardousUsageEvaluationResult.Unflagged, + }; }, true)); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableRequestValidation.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableRequestValidation.cs index 9534c7b613..d1cafc00d7 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableRequestValidation.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableRequestValidation.cs @@ -35,7 +35,7 @@ public sealed class DoNotDisableRequestValidation : DiagnosticAnalyzer DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5363", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotInstallRootCert.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotInstallRootCert.cs index 16c3f59d2c..483453aec7 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotInstallRootCert.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotInstallRootCert.cs @@ -28,7 +28,7 @@ public sealed class DoNotInstallRootCert : DiagnosticAnalyzer nameof(MicrosoftNetCoreAnalyzersResources.DefinitelyInstallRootCert), nameof(MicrosoftNetCoreAnalyzersResources.DefinitelyInstallRootCertMessage), DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5380", descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.DoNotInstallRootCertDescription), customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry); internal static DiagnosticDescriptor MaybeInstallRootCertRule = SecurityHelpers.CreateDiagnosticDescriptor( @@ -37,7 +37,7 @@ public sealed class DoNotInstallRootCert : DiagnosticAnalyzer nameof(MicrosoftNetCoreAnalyzersResources.MaybeInstallRootCert), nameof(MicrosoftNetCoreAnalyzersResources.MaybeInstallRootCertMessage), DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5381", descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.DoNotInstallRootCertDescription), customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry); @@ -52,17 +52,14 @@ public sealed class DoNotInstallRootCert : DiagnosticAnalyzer private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue) { - switch (propertySetAbstractValue[0]) + return (propertySetAbstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, - default: - return HazardousUsageEvaluationResult.Unflagged; - } + _ => HazardousUsageEvaluationResult.Unflagged, + }; } public override void Initialize(AnalysisContext context) @@ -101,13 +98,13 @@ public override void Initialize(AnalysisContext context) { if (constructorMethod.Parameters[0].Type.Equals(storeNameTypeSymbol)) { - kind = PropertySetCallbacks.EvaluateLiteralValues(argumentValueContentAbstractValues[0], o => o.Equals(6)); + kind = PropertySetCallbacks.EvaluateLiteralValues(argumentValueContentAbstractValues[0], o => o != null && o.Equals(6)); } else if (constructorMethod.Parameters[0].Type.SpecialType == SpecialType.System_String) { kind = PropertySetCallbacks.EvaluateLiteralValues( argumentValueContentAbstractValues[0], - s => string.Equals(s.ToString(), "root", StringComparison.OrdinalIgnoreCase)); + s => s != null && string.Equals(s.ToString(), "root", StringComparison.OrdinalIgnoreCase)); } } diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs index d11375e207..11761203d0 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs @@ -138,8 +138,8 @@ public override void Initialize(AnalysisContext context) invocationOperation.Arguments[1].Syntax]; // Just check for simple cases with one possible literal value. - if (switchNameValueContent.TryGetSingleLiteral(out var switchName) && - switchValueValueContent.TryGetSingleLiteral(out var switchValue) && + if (switchNameValueContent.TryGetSingleNonNullLiteral(out var switchName) && + switchValueValueContent.TryGetSingleNonNullLiteral(out var switchValue) && BadSwitches.TryGetValue(switchName, out var pair) && pair.BadValue.Equals(switchValue) && !IsConfiguredToSkipAnalysis(pair.Rule, operationAnalysisContext)) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs index 22966e1703..a5eb0091b4 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs @@ -54,15 +54,12 @@ class DoNotUseInsecureDeserializerJavaScriptSerializerWithSimpleTypeResolver : D private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue) { - switch (propertySetAbstractValue[0]) + return (propertySetAbstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.Unflagged: - return HazardousUsageEvaluationResult.Unflagged; - default: - return HazardousUsageEvaluationResult.MaybeFlagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.Unflagged => HazardousUsageEvaluationResult.Unflagged, + _ => HazardousUsageEvaluationResult.MaybeFlagged, + }; } public override void Initialize(AnalysisContext context) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseObsoleteKDFAlgorithm.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseObsoleteKDFAlgorithm.cs index b2ed197e6c..25ad5bc52a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseObsoleteKDFAlgorithm.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseObsoleteKDFAlgorithm.cs @@ -35,7 +35,7 @@ public sealed class DoNotUseObsoleteKDFAlgorithm : DiagnosticAnalyzer DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5373", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseWeakKDFInsufficientIterationCount.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseWeakKDFInsufficientIterationCount.cs index 0f98274c67..65bd75fd31 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseWeakKDFInsufficientIterationCount.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseWeakKDFInsufficientIterationCount.cs @@ -49,17 +49,14 @@ public sealed class DoNotUseWeakKDFInsufficientIterationCount : DiagnosticAnalyz private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue) { - switch (propertySetAbstractValue[0]) + return (propertySetAbstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, - default: - return HazardousUsageEvaluationResult.Unflagged; - } + _ => HazardousUsageEvaluationResult.Unflagged, + }; } public override void Initialize(AnalysisContext context) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/SourceTriggeredTaintedDataAnalyzerBase.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/SourceTriggeredTaintedDataAnalyzerBase.cs index 921b6fd0bc..456dd7d02c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/SourceTriggeredTaintedDataAnalyzerBase.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/SourceTriggeredTaintedDataAnalyzerBase.cs @@ -92,7 +92,33 @@ public override void Initialize(AnalysisContext context) operationAnalysisContext => { IInvocationOperation invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation; + + if (!sourceInfoSymbolMap.IsSourceMethodFast( + invocationOperation.TargetMethod, + invocationOperation.Arguments, + out bool isSourceMethod, + out bool requiresPointsTo, + out bool requiresValueContent)) + { + return; + } + IOperation rootOperation = operationAnalysisContext.Operation.GetRoot(); + + if (isSourceMethod) + { + lock (rootOperationsNeedingAnalysis) + { + rootOperationsNeedingAnalysis.Add(rootOperation); + } + + return; + } + else if (!requiresPointsTo && !requiresValueContent) + { + return; + } + PooledDictionary> evaluateWithPointsToAnalysis = null; PooledDictionary> evaluateWithValueContentAnalysis = null; PointsToAnalysisResult pointsToAnalysisResult = null; @@ -116,7 +142,7 @@ public override void Initialize(AnalysisContext context) } } - if (sourceInfoSymbolMap.RequiresValueContentAnalysis) + if (requiresValueContent) { valueContentAnalysisResult = ValueContentAnalysis.TryGetOrComputeResult( cfg, @@ -139,10 +165,10 @@ public override void Initialize(AnalysisContext context) try { if (sourceInfoSymbolMap.IsSourceMethod( - invocationOperation.TargetMethod, - invocationOperation.Arguments, - invocationOperation.Arguments.Select(o => pointsToAnalysisResult[o.Kind, o.Syntax]).ToImmutableArray(), - invocationOperation.Arguments.Select(o => valueContentAnalysisResult[o.Kind, o.Syntax]).ToImmutableArray(), + invocationOperation.TargetMethod, + invocationOperation.Arguments, + invocationOperation.Arguments.Select(o => pointsToAnalysisResult[o.Kind, o.Syntax]).ToImmutableArray(), + invocationOperation.Arguments.Select(o => valueContentAnalysisResult[o.Kind, o.Syntax]).ToImmutableArray(), out _)) { lock (rootOperationsNeedingAnalysis) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/UseSecureCookiesASPNetCore.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/UseSecureCookiesASPNetCore.cs index 16b987191e..a6d443928b 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/UseSecureCookiesASPNetCore.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/UseSecureCookiesASPNetCore.cs @@ -52,22 +52,19 @@ public sealed class UseSecureCookiesASPNetCore : DiagnosticAnalyzer "Secure", (ValueContentAbstractValue valueContentAbstractValue) => { - return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, o => o.Equals(false)); + return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, o => o != null && o.Equals(false)); })); private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue) { - switch (propertySetAbstractValue[0]) + return (propertySetAbstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, - default: - return HazardousUsageEvaluationResult.Unflagged; - } + _ => HazardousUsageEvaluationResult.Unflagged, + }; } public override void Initialize(AnalysisContext context) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForDeserialize.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForDeserialize.cs index 1fd9030b60..450a1bc1c3 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForDeserialize.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForDeserialize.cs @@ -23,7 +23,7 @@ public sealed class UseXmlReaderForDeserialize : UseXmlReaderBase DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5369", customTags: WellKnownDiagnosticTags.Telemetry); protected override string TypeMetadataName => WellKnownTypeNames.SystemXmlSerializationXmlSerializer; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForSchemaRead.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForSchemaRead.cs index f2b07c0e72..e8038e3fc0 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForSchemaRead.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForSchemaRead.cs @@ -23,7 +23,7 @@ public sealed class UseXmlReaderForSchemaRead : UseXmlReaderBase DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5371", customTags: WellKnownDiagnosticTags.Telemetry); protected override string TypeMetadataName => WellKnownTypeNames.SystemXmlSchemaXmlSchema; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForValidatingReader.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForValidatingReader.cs index cd1ed12378..503d097ead 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForValidatingReader.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForValidatingReader.cs @@ -23,7 +23,7 @@ public sealed class UseXmlReaderForValidatingReader : UseXmlReaderBase DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5370", customTags: WellKnownDiagnosticTags.Telemetry); protected override string TypeMetadataName => WellKnownTypeNames.SystemXmlXmlValidatingReader; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForXPathDocument.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForXPathDocument.cs index 625dff711f..9c4b1bc237 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForXPathDocument.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/UseXmlReaderForXPathDocument.cs @@ -23,7 +23,7 @@ public sealed class UseXmlReaderForXPathDocument : UseXmlReaderBase DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: Description, - helpLinkUri: null, + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca5372", customTags: WellKnownDiagnosticTags.Telemetry); protected override string TypeMetadataName => WellKnownTypeNames.SystemXmlXPathXPathDocument; diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf index ee43e6ea52..851c65668e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Starší verze protokolu zabezpečení TLS (Transport Layer Security) jsou méně bezpečné než TLS 1.2 a TLS 1.3 a mají větší pravděpodobnost výskytu nových ohrožení zabezpečení. Nepoužívejte starší verze protokolu, aby se riziko minimalizovalo. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + Verze protokolu TLS (Transport Layer Security) {0} je zastaralá. Pokud chcete, aby operační systém mohl zvolit verzi, použijte možnost None. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Nepoužívat zastaralé hodnoty SslProtocols @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Nepoužívat nezabezpečenou náhodnost {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} je nezabezpečený generátor náhodných čísel. Pokud se pro zabezpečení vyžaduje náhodnost, používejte kryptograficky zabezpečené generátory náhodných čísel. Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + Použití generátoru kryptograficky slabých pseudonáhodných čísel může útočníkovi umožnit předpovědět, jaká hodnota citlivá z hlediska bezpečnosti bude vygenerována. Použijte generátor kryptograficky silných náhodných čísel, pokud se vyžaduje nepředvídatelná hodnota, nebo zajistěte, aby se slabá pseudonáhodná čísla nepoužívala způsobem citlivým z hlediska bezpečnosti. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Nepoužívat nebezpečnou hodnotu DllImportSearchPath 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. - 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. + Ve výchozích adresářích pro vyhledávání DLL se může nacházet škodlivá knihovna DLL. Anebo v závislosti na tom, odkud se aplikace spouští, se může škodlivá knihovna DLL nacházet v adresáři aplikace. Použijte hodnotu DllImportSearchPath, která místo toho určuje explicitní vyhledávací cestu. Příznaky DllImportSearchPath, které toto pravidlo hledá, se dají nakonfigurovat v .editorconfig. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Použití nebezpečné hodnoty DllImportSearchPath {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Po zjištění ohrožení zabezpečení můžou aktuální verze protokolu TLS (Transport Layer Security) zastarat. Aby aplikace zůstala zabezpečená, nepoužívejte pevně zakódované hodnoty SslProtocols. Pokud chcete, aby operační systém mohl zvolit verzi, použijte možnost None. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Abyste zajistili, že aplikace zůstane v budoucnu zabezpečená, nepoužívejte pevně zakódované hodnoty SslProtocols {0}. Pokud chcete, aby operační systém mohl zvolit verzi, použijte možnost None. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Nepoužívat pevně zakódované hodnoty SslProtocols 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. - 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. + Když se deserializuje nedůvěryhodný vstup, není bezpečné povolit deserializaci libovolných typů. Pokud k deserializaci používáte JsonSerializer, použijte TypeNameHandling.None, nebo pro hodnoty jiné než None omezte deserializované typy pomocí SerializationBinder. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + Nepoužívat při deserializaci JsonSerializer s nezabezpečenou konfigurací 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. - 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. + Když se deserializuje nedůvěryhodný vstup, není bezpečné povolit deserializaci libovolných typů. Pokud k deserializaci používáte JsonSerializer, použijte TypeNameHandling.None, nebo pro hodnoty jiné než None omezte deserializované typy pomocí SerializationBinder. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Zajistit, aby měl JsonSerializer při deserializaci zabezpečenou konfiguraci + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Chybějící atribut HttpVerb pro metody akce All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Všechny metody, které vytvářejí, upravují, odstraňují nebo jinak modifikují data, tak činí při přetížení metody [HttpPost], což vyžaduje ochranu pomocí atributu proti padělkům v požadavku. Provedení operace GET by mělo představovat bezpečnou operaci, která nemá žádné vedlejší účinky a neupravuje trvalá data. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + Metoda akce {0} musí explicitně určit druh požadavku HTTP. @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Nastavit HttpOnly na hodnotu true pro 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. - 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. + Jako opatření důkladné ochrany zajistěte, aby soubory cookie protokolu HTTP, které jsou citlivé na zabezpečení, byly označeny jako HttpOnly. Tím se indikuje, že webové prohlížeče by neměly povolovat přístup skriptů k těmto souborům cookie. Vložené škodlivé skripty představují běžný způsob krádeže souborů cookie. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + Při použití HttpCookie je HttpCookie.HttpOnly nastaveno na hodnotu false nebo není vůbec nastaveno. Zajistěte, aby soubory cookie, které jsou citlivé na zabezpečení, byly označeny jako HttpOnly. Zabráníte tak v krádeži těchto souborů cookie škodlivými skripty. @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Používat tokeny proti padělkům v kontrolerech MVC ASP.NET Core Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + Zpracování požadavku POST, PUT, PATCH nebo DELETE bez ověřování tokenu proti padělkům může představovat ohrožení zabezpečení vůči útokům CSRF. Útok CSRF může odesílat na váš kontroler MVC ASP.NET Core škodlivé požadavky od ověřeného uživatele. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + Metoda {0} zpracovává požadavek {1} bez ověřování tokenu proti padělkům. Je potřeba také zajistit, aby váš formulář HTML odesílal tokeny proti padělkům. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Používat při voláních nespravovaného kódu atribut DefaultDllImportSearchPaths 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. - 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. + Ve výchozím nastavení se při voláních nespravovaného kódu s atributem DllImportAttribute prohledává několik adresářů včetně aktuálního pracovního adresáře pro načtení knihovny. U určitých aplikací to představuje problém zabezpečení, který může vést k napadení DLL. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + Metoda {0} nepoužila při voláních nespravovaného kódu atribut DefaultDllImportSearchPaths. @@ -1029,7 +1029,7 @@ 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. - Metoda {0} není bezpečná při deserializaci nedůvěryhodných dat přes JavaScriptSerializer inicializovaný s nástrojem SimpleTypeResolver. Zajistěte, aby byl JavaScriptSerializer inicializovaný bez zadání nástroje JavaScriptTypeResolver nebo aby byl inicializovaný s nástrojem JavaScriptTypeResolver, který omezuje typy objektů v grafu deserializovaných objektů. + Metoda {0} není bezpečná při deserializaci nedůvěryhodných dat přes JavaScriptSerializer inicializovaný s nástrojem SimpleTypeResolver. Zajistěte, aby byl JavaScriptSerializer inicializovaný bez zadání nástroje JavaScriptTypeResolver nebo aby byl inicializovaný s nástrojem JavaScriptTypeResolver, který omezuje typy objektů v grafu deserializovaných objektů. @@ -1039,7 +1039,7 @@ 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. - Metoda {0} není bezpečná při deserializaci nedůvěryhodných dat přes JavaScriptSerializer inicializovaný s nástrojem SimpleTypeResolver. Inicializujte JavaScriptSerializer bez zadání nástroje JavaScriptTypeResolver nebo ho inicializujte s nástrojem JavaScriptTypeResolver, který omezuje typy objektů v grafu deserializovaných objektů. + Metoda {0} není bezpečná při deserializaci nedůvěryhodných dat přes JavaScriptSerializer inicializovaný s nástrojem SimpleTypeResolver. Inicializujte JavaScriptSerializer bez zadání nástroje JavaScriptTypeResolver nebo ho inicializujte s nástrojem JavaScriptTypeResolver, který omezuje typy objektů v grafu deserializovaných objektů. @@ -1049,37 +1049,37 @@ 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. - 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. + Když se deserializuje nedůvěryhodný vstup, není bezpečné povolit deserializaci libovolných typů. Pokud používáte JsonSerializerSettings, použijte TypeNameHandling.None, nebo pro hodnoty jiné než None omezte deserializované typy pomocí SerializationBinder. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Nepoužívat nezabezpečená nastavení JsonSerializerSettings 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. - 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. + Když se deserializuje nedůvěryhodný vstup, není bezpečné povolit deserializaci libovolných typů. Pokud používáte JsonSerializerSettings, ujistěte se, že je zadaná možnost TypeNameHandling.None, nebo pro hodnoty jiné než None se ujistěte, že se zadala možnost SerializationBinder, aby se omezily deserializované typy. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Ujistěte se, že nastavení JsonSerializerSettings jsou zabezpečená 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. - 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. + Deserializace JSON při použití hodnoty TypeNameHandling jiné než None nemůže být nebezpečné. Pokud místo toho potřebujete zjistit deserializaci Json.NET, když není zadané SerializationBinder, zakažte pravidlo CA2326 a povolte pravidla CA2327, CA2328, CA2329 a CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + Deserializace JSON při použití hodnoty TypeNameHandling jiné než None nemůže být nebezpečné. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + Nepoužívat jiné hodnoty TypeNameHandling než None @@ -1319,7 +1319,7 @@ 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. - Při extrahování souborů z archivu a použití cesty k položce archivu zkontrolujte, jestli je cesta bezpečná. Cesta k archivu může být relativní a může umožnit přístup k systému souborů mimo očekávanou cílovou cestu k systému souborů, což může vést ke škodlivým změnám konfigurace a spouštění vzdáleného kódu prostřednictvím metody nastražení a čekání. + Při extrahování souborů z archivu a použití cesty k položce archivu zkontrolujte, jestli je cesta bezpečná. Cesta k archivu může být relativní a může umožnit přístup k systému souborů mimo očekávanou cílovou cestu k systému souborů, což může vést ke škodlivým změnám konfigurace a vzdálenému spuštění kódu prostřednictvím metody nastražení a čekání. @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Nepoužívat pevně zakódovaný šifrovací klíč SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + Vlastnost .Key objektu SymmetricAlgorithm ani parametr rgbKey metody by nikdy neměly mít pevně zakódované hodnoty. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Našlo se potenciální ohrožení zabezpečení, kde {0} v metodě {1} je možné poškodit pevně zakódovaným klíčem z {2} v metodě {3}. diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf index d5cdb2f433..e72f491fe5 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Ältere Protokollversionen von Transport Layer Security (TLS) sind weniger sicher als TLS 1.2 und TLS 1.3 und weisen eine höhere Wahrscheinlichkeit für neue Sicherheitsrisiken auf. Vermeiden Sie ältere Protokollversionen, um das Risiko zu minimieren. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + Die Transport Layer Security-Protokollversion {0} ist veraltet. Verwenden Sie "None", um dem Betriebssystem die Auswahl einer Version zu ermöglichen. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Keine veralteten SslProtocols-Werte verwenden @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Keine unsichere Zufälligkeitsstufe verwenden {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} ist ein unsicherer Zufallszahlen-Generator. Verwenden Sie kryptografisch sichere Zufallszahlen-Generatoren, wenn Zufälligkeit für die Sicherheit erforderlich ist. Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + Bei Verwendung eines kryptografisch schwachen Pseudozufallszahlen-Generators kann ein Angreifer möglicherweise vorhersagen, welcher sicherheitsrelevante Wert generiert wird. Verwenden Sie einen kryptografisch starken Zufallszahlen-Generator, wenn ein nicht vorhersehbarer Wert erforderlich ist, oder stellen Sie sicher, dass schwache Pseudozufallszahlen nicht auf sicherheitsrelevante Weise verwendet werden. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Keinen unsicheren DllImportSearchPath-Wert verwenden 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. - 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. + Die Standard-DLL-Suchverzeichnisse enthalten möglicherweise eine schädliche DLL. Je nachdem, von wo aus Ihre Anwendung ausgeführt wird, befindet sich möglicherweise auch eine schädliche DLL im Anwendungsverzeichnis. Verwenden Sie einen DllImportSearchPath-Wert, der stattdessen einen expliziten Suchpfad angibt. Die DllImportSearchPath-Flags, nach denen diese Regel sucht, können in .editorconfig konfiguriert werden. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Verwendung eines unsicheren DllImportSearchPath-Werts "{0}" Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Aktuelle Transport Layer Security-Protokollversionen werden möglicherweise als veraltet markiert, wenn Sicherheitsrisiken gefunden werden. Vermeiden Sie das Hartcodieren von SslProtocols-Werten, um Ihre Anwendung zu schützen. Verwenden Sie "None", um dem Betriebssystem die Auswahl einer Version zu ermöglichen. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Vermeiden Sie die Hartcodierung von SslProtocols "{0}", um sicherzustellen, dass Ihre Anwendung in Zukunft sicher bleibt. Verwenden Sie "None", um dem Betriebssystem die Auswahl einer Version zu ermöglichen. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Hartcodierte SslProtocols-Werte vermeiden 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. - 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. + Beim Deserialisieren nicht vertrauenswürdiger Eingaben ist das Zulassen der Deserialisierung beliebiger Typen unsicher. Geben Sie bei Verwendung von JsonSerializer zum Deserialisieren "TypeNameHandling.None" an, oder schränken Sie deserialisierte Typen für andere Werte als "None" mit einem SerializationBinder ein. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + JsonSerializer nicht zum Deserialisieren mit einer unsicheren Konfiguration verwenden 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. - 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. + Beim Deserialisieren nicht vertrauenswürdiger Eingaben ist das Zulassen der Deserialisierung beliebiger Typen unsicher. Geben Sie bei Verwendung von JsonSerializer zum Deserialisieren "TypeNameHandling.None" an, oder schränken Sie deserialisierte Typen für andere Werte als "None" mit einem SerializationBinder ein. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Bei der Deserialisierung mit JsonSerializer eine sichere Konfiguration sicherstellen + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Fehlendes HttpVerb-Attribut für Aktionsmethoden All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Alle Methoden, die Daten erstellen, bearbeiten, löschen oder anderweitig ändern, führen diese Vorgänge in der [HttpPost]-Überladung der Methode durch, die mit dem Fälschungssicherheitsattribut vor Anforderungsfälschung geschützt werden muss. Das Ausführen eines GET-Vorgangs muss ein sicherer Vorgang sein, der keine Nebenwirkungen hat und Ihre persistenten Daten nicht ändert. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + Die Aktionsmethode "{0}" muss die Art der HTTP-Anforderung explizit angeben. @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + HttpOnly für HttpCookie auf TRUE festlegen 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. - 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. + Stellen Sie als effektive Abwehrmaßnahme sicher, dass die sicherheitsrelevanten HTTP-Cookies als "HttpOnly" gekennzeichnet sind. Dadurch werden Webbrowser angewiesen, Skripts den Zugriff auf die Cookies zu verwehren. Eingefügte schädliche Skripts sind eine gängige Methode zum Stehlen von Cookies. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie.HttpOnly ist bei Verwendung eines HttpCookie auf FALSE oder gar nicht festgelegt. Stellen Sie sicher, dass sicherheitsrelevante Cookies als HttpOnly gekennzeichnet sind, um zu verhindern, dass sie von schädlichen Skripts gestohlen werden. @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Fälschungssicherheitstoken in ASP.NET Core MVC-Controllern verwenden Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + Die Verarbeitung einer POST-, PUT-, PATCH- oder DELETE-Anforderung ohne Überprüfung eines Fälschungssicherheitstokens ist möglicherweise anfällig für Angriffe durch websiteübergreifende Anforderungsfälschung. Bei einem Angriff durch websiteübergreifende Anforderungsfälschung können schädliche Anforderungen von einem authentifizierten Benutzer an den ASP.NET Core MVC-Controller gesendet werden. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + Die Methode "{0}" verarbeitet eine {1}-Anforderung ohne Überprüfung eines Fälschungssicherheitstokens. Sie müssen außerdem sicherstellen, dass Ihr HTML-Formular ein Fälschungssicherheitstoken sendet. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + DefaultDllImportSearchPaths-Attribut für P/Invokes verwenden 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. - 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. + Standardmäßig wird von P/Invokes über DllImportAttribute eine Reihe von Verzeichnissen getestet, einschließlich des aktuellen Arbeitsverzeichnisses für die zu ladende Bibliothek. Dies kann für bestimmte Anwendungen ein Sicherheitsproblem darstellen, das zu DLL-Hijacking führt. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + Die Methode "{0}" hat das DefaultDllImportSearchPaths-Attribut für P/Invokes nicht verwendet. @@ -1029,7 +1029,7 @@ 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. - Die Methode "{0}" ist unsicher, wenn nicht vertrauenswürdige Daten mit einem JavaScriptSerializer deserialisiert werden, der mit einem SimpleTypeResolver initialisiert wurde. Stellen Sie sicher, dass der JavaScriptSerializer ohne Angabe eines JavaScriptTypeResolver oder mit einem JavaScriptTypeResolver initialisiert wird, der die Objekttypen im deserialisierten Objektdiagramm einschränkt. + Die Methode "{0}" ist unsicher, wenn nicht vertrauenswürdige Daten mit einem JavaScriptSerializer deserialisiert werden, der mit einem SimpleTypeResolver initialisiert wurde. Stellen Sie sicher, dass der JavaScriptSerializer ohne Angabe eines JavaScriptTypeResolver oder mit einem JavaScriptTypeResolver initialisiert wird, der die Objekttypen im deserialisierten Objektgraphen einschränkt. @@ -1039,7 +1039,7 @@ 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. - Die Methode "{0}" ist unsicher, wenn nicht vertrauenswürdige Daten mit einem JavaScriptSerializer deserialisiert werden, der mit einem SimpleTypeResolver initialisiert wurde. Initialisieren Sie den JavaScriptSerializer ohne Angabe eines JavaScriptTypeResolver oder mit einem JavaScriptTypeResolver, der die Objekttypen im deserialisierten Objektdiagramm einschränkt. + Die Methode "{0}" ist unsicher, wenn nicht vertrauenswürdige Daten mit einem JavaScriptSerializer deserialisiert werden, der mit einem SimpleTypeResolver initialisiert wurde. Initialisieren Sie den JavaScriptSerializer ohne Angabe eines JavaScriptTypeResolver oder mit einem JavaScriptTypeResolver, der die Objekttypen im deserialisierten Objektgraphen einschränkt. @@ -1049,37 +1049,37 @@ 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. - 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. + Beim Deserialisieren nicht vertrauenswürdiger Eingaben ist das Zulassen der Deserialisierung beliebiger Typen unsicher. Geben Sie bei Verwendung von JsonSerializerSettings "TypeNameHandling.None" an, oder schränken Sie deserialisierte Typen für andere Werte als "None" mit einem SerializationBinder ein. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Keine unsicheren JsonSerializerSettings verwenden 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. - 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. + Beim Deserialisieren nicht vertrauenswürdiger Eingaben ist das Zulassen der Deserialisierung beliebiger Typen unsicher. Geben Sie bei Verwendung von JsonSerializerSettings "TypeNameHandling.None" an, oder stellen Sie für andere Werte als "None" sicher, dass ein SerializationBinder zum Einschränken deserialisierter Typen angegeben wird. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Sicherheit von JsonSerializerSettings sicherstellen 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. - 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. + Die Deserialisierung von JSON bei Verwendung eines anderen TypeNameHandling-Werts als "None" kann unsicher sein. Wenn Sie stattdessen die Json.NET-Deserialisierung ermitteln müssen, wenn kein SerializationBinder angegeben wird, deaktivieren Sie Regel CA2326, und aktivieren Sie die Regeln CA2327, CA2328, CA2329 und CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + Die Deserialisierung von JSON bei Verwendung eines anderen TypeNameHandling-Werts als "None" kann unsicher sein. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + Verwenden Sie keinen anderen TypeNameHandling-Wert als "None". @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Verschlüsselungsschlüssel nicht hartcodieren SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + Die .Key-Eigenschaft von SymmetricAlgorithm oder der rgbKey-Parameter einer Methode darf niemals ein hartcodierter Wert sein. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Es wurde ein potenzielles Sicherheitsrisiko gefunden. "{0}" in der Methode "{1}" wurde möglicherweise durch einen hartcodierten Schlüssel aus "{2}" in Methode "{3}" erweitert. diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf index 6665dae733..7a45152a64 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Las versiones anteriores del protocolo Seguridad de la capa de transporte (TLS) son menos seguras que las versiones TLS 1.2 y TLS 1.3, y es más probable que tengan nuevas vulnerabilidades. Evite las versiones anteriores del protocolo para minimizar el riesgo. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + La versión "{0}" del protocolo Seguridad de la capa de transporte está en desuso. Utilice "None" para permitir que el sistema operativo elija una versión. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + No usar valores de SslProtocols en desuso @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + No usar aleatoriedad no segura {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} es un generador de números aleatorios no seguro. Use generadores de números aleatorios que sean criptográficamente seguros cuando se requiera aleatoriedad por seguridad. Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + El uso de un generador de números seudoaleatorios no seguro criptográficamente puede permitir a un atacante predecir el valor sensible a la seguridad que se va a generar. Use un generador de números aleatorios fuertemente cifrado si se requiere un valor impredecible, o bien asegúrese de que no se usan números seudoaleatorios poco seguros en una situación sensible a la seguridad. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + No usar un valor de DllImportSearchPath no seguro 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. - 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. + Puede haber un archivo .dll malintencionado en los directorios de búsqueda de archivos .dll predeterminados. O bien, según desde dónde se ejecute la aplicación, puede haber un archivo .dll malintencionado en el directorio de la aplicación. Use un valor de DllImportSearchPath que especifique una ruta de acceso de búsqueda explícita. Las marcas de DllImportSearchPath que busca esta regla se pueden configurar en el archivo .editorconfig. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Se está usando un valor de DllImportSearchPath ({0}) que no es seguro Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Las versiones actuales del protocolo Seguridad de la capa de transporte pueden dejar de usarse si se encuentran vulnerabilidades. No codifique los valores de SslProtocols de forma rígida para mantener la aplicación segura. Use "None" para permitir que el sistema operativo elija una versión. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Evite codificar el valor "{0}" de SslProtocols de forma rígida para que la aplicación se mantenga segura en el futuro. Use "None" para permitir que el sistema operativo elija una versión. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Evitar valores de SslProtocols codificados de forma rígida 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. - 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. + Cuando se deserializa una entrada que no es de confianza, no es seguro permitir la deserialización de tipos arbitrarios. Cuando utilice la deserialización de JsonSerializer, use TypeNameHandling.None, o bien, para valores distintos de None, restrinja los tipos deserializados con SerializationBinder. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + No deserializar con JsonSerializer usando una configuración no segura 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. - 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. + Cuando se deserializa una entrada que no es de confianza, no es seguro permitir la deserialización de tipos arbitrarios. Cuando utilice la deserialización de JsonSerializer, use TypeNameHandling.None, o bien, para valores distintos de None, restrinja los tipos deserializados con SerializationBinder. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Asegurarse de que JsonSerializer tiene una configuración segura al deserializar + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Falta el atributo HttpVerb para los métodos de acción All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Todos los métodos que crean, editan, eliminan o modifican de otro modo los datos, lo hacen en la sobrecarga de [HttpPost] del método, que debe protegerse de la falsificación de solicitudes con el atributo antifalsificación. La ejecución de GET debe ser una operación segura que no tenga efectos secundarios y no modifique los datos guardados. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + El método de acción {0} debe especificar el tipo de solicitud HTTP de forma explícita. @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Establecer HttpOnly en true para 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. - 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. + Como medida de defensa exhaustiva, asegúrese de que las cookies HTTP sensibles a la seguridad estén marcadas como HttpOnly. Esto indica que los exploradores web deben impedir que posibles scripts tengan acceso a las cookies. Los scripts malintencionados insertados son una forma habitual de robar cookies. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie.HttpOnly se establece en false o no se establece cuando se usa HttpCookie. Asegúrese de que las cookies sensibles a la seguridad se marcan como HttpOnly para evitar que posibles scripts malintencionados roben las cookies @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Usar tokens antifalsificación en los controladores de ASP.NET Core MVC Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + Controlar una solicitud POST, PUT, PATCH o DELETE sin validar un token antifalsificación puede suponer una vulnerabilidad a los ataques de falsificación de solicitudes entre sitios. En este tipo de ataques, se pueden enviar solicitudes malintencionadas de un usuario autenticado al controlador de ASP.NET Core MVC. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + El método {0} controla una solicitud de {1} sin validar un token antifalsificación. También debe asegurarse de que el formulario HTML envíe un token antifalsificación. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Usar el atributo DefaultDllImportSearchPaths para P/Invoke 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. - 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. + De forma predeterminada, los métodos de P/Invoke que usan DllImportAttribute sondean una serie de directorios, incluido el directorio de trabajo actual para cargar la biblioteca. Esto puede suponer un problema de seguridad para algunas aplicaciones y dar lugar a que se intercepten archivos .dll. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + El método {0} no ha usado el atributo DefaultDllImportSearchPaths para P/Invoke. @@ -589,7 +589,7 @@ Higher-frequency periodic activity will keep the CPU busy and interfere with power-saving idle timers that turn off the display and hard disks. - Una actividad periódica más frecuente hará que la CPU no esté disponible e interferirá con los temporizadores de inactividad para ahorro de energía que apagan el monitor y los discos duros. + Una actividad periódica más frecuente ocupará la CPU e interferirá con los temporizadores de inactividad para ahorro de energía que apagan el monitor y los discos duros. @@ -1029,7 +1029,7 @@ 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. - El método "{0}" no es seguro al deserializar datos que no son de confianza con JavaScriptSerializer inicializado con SimpleTypeResolver. Asegúrese de que se ha inicializado JavaScriptSerializer sin especificar JavaScriptTypeResolver, o de que se ha inicializado con JavaScriptTypeResolver que limita los tipos de objetos en el grafo de objetos deserializados. + El método "{0}" no es seguro cuando se deserializan datos que no son de confianza con JavaScriptSerializer inicializado con SimpleTypeResolver. Asegúrese de que se ha inicializado JavaScriptSerializer sin especificar JavaScriptTypeResolver o de que se ha inicializado con un JavaScriptTypeResolver que limite los tipos de objeto en el grafo de objetos deserializados. @@ -1039,7 +1039,7 @@ 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. - El método "{0}" no es seguro al deserializar datos que no son de confianza con JavaScriptSerializer inicializado con SimpleTypeResolver. Inicialice JavaScriptSerializer sin JavaScriptTypeResolver especificado o inicialice con JavaScriptTypeResolver que limita los tipos de objetos en el grafo de objetos deserializados. + El método "{0}" no es seguro cuando se deserializan datos que no son de confianza con JavaScriptSerializer inicializado con SimpleTypeResolver. Inicialice JavaScriptSerializer sin especificar JavaScriptTypeResolver, o bien inicialícelo con un JavaScriptTypeResolver que limite los tipos de objeto en el grafo de objetos deserializados. @@ -1049,37 +1049,37 @@ 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. - 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. + Cuando se deserializa una entrada que no es de confianza, no es seguro permitir la deserialización de tipos arbitrarios. Cuando utilice JsonSerializerSettings, utilice TypeNameHandling.None, o bien, para valores distintos de None, restrinja los tipos deserializados con SerializationBinder. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + No use clases JsonSerializerSettings no seguras 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. - 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. + Cuando se deserializa una entrada que no es de confianza, no es seguro permitir la deserialización de tipos arbitrarios. Cuando utilice JsonSerializerSettings, asegúrese de que se especifica TypeNameHandling.None, o bien, para valores distintos de None, asegúrese de que se especifica un SerializationBinder que restrinja los tipos deserializados. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Asegúrese de que las clases JsonSerializerSettings son seguras 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. - 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. + La deserialización de JSON cuando se usa un valor TypeNameHandling distinto de None puede no ser segura. Si necesita detectar la deserialización de Json.NET cuando no se especifica un objeto SerializationBinder, deshabilite la regla CA2326 y habilite las reglas CA2327, CA2328, CA2329 y CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + La deserialización de JSON cuando se usa un valor TypeNameHandling distinto de None puede no ser segura. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + No usar valores TypeNameHandling distintos de None @@ -1319,7 +1319,7 @@ 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. - Al extraer archivos de un elemento de archivo y usar la ruta de acceso de dicho elemento, compruebe si la ruta es segura. La ruta de acceso de archivo puede ser relativa y dirigir el acceso del sistema de archivos fuera de la ruta de destino esperada del sistema de archivos, lo que provoca cambios malintencionados de la configuración y la ejecución remota de código mediante la técnica de "lay-and-wait". + Al extraer archivos de un elemento de archivo y usar la ruta de acceso de dicho elemento, compruebe si la ruta es segura. La ruta de acceso de archivo puede ser relativa y dirigir el acceso del sistema de archivos fuera de la ruta de destino esperada del sistema de archivos, lo que provoca cambios malintencionados de la configuración y la ejecución remota de código mediante la técnica que consiste en establecer y esperar. @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + No codificar la clave de cifrado de forma rígida SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + La propiedad Key de SymmetricAlgorithm o el parámetro rgbKey de un método no deben ser nunca un valor codificado de forma rígida. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Se encontró una posible vulnerabilidad de seguridad por la que podría contaminarse "{0}" en el método "{1}" con una clave codificada de forma rígida de "{2}" en el método "{3}". diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf index 5cb3b00947..577959801a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Les anciennes versions du protocole TLS (Transport Layer Security) sont moins sécurisées que TLS 1.2 et TLS 1.3, et sont plus susceptibles de comporter de nouvelles vulnérabilités. Évitez les anciennes versions de protocole pour réduire les risques. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + La version '{0}' du protocole TLS (Transport Layer Security) est dépréciée. Utilisez 'None' pour laisser le système d'exploitation choisir une version. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + N'utilisez pas de valeurs dépréciées pour SslProtocols @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Ne pas utiliser de sélection aléatoire non sécurisée {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} est un générateur de nombres aléatoires non sécurisé. Utilisez des générateurs de nombres aléatoires sécurisés de manière chiffrée quand une sélection aléatoire est nécessaire pour la sécurité Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + L'utilisation d'un générateur de nombres pseudo-aléatoires faible au niveau du chiffrement peut permettre à un attaquant de prédire la génération d'une valeur dont la sécurité est critique. Utilisez un générateur de nombres aléatoires fort au niveau du chiffrement si une valeur imprévisible est nécessaire, ou vérifiez qu'aucun nombre pseudo-aléatoire faible n'est utilisé dans le cadre d'opérations dont la sécurité est critique. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Ne pas utiliser de valeur non sécurisée pour DllImportSearchPath 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. - 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. + Il existe peut-être une DLL malveillante dans les répertoires de recherche de DLL par défaut. De même, en fonction de l'emplacement d'exécution de votre application, il peut exister une DLL malveillante dans le répertoire de l'application. Utilisez une valeur pour DllImportSearchPath qui spécifie un chemin de recherche explicite à la place. Vous pouvez configurer les indicateurs DllImportSearchPath que cette règle recherche dans .editorconfig. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Utilisation d'une valeur de DllImportSearchPath non sécurisée {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Les versions actuelles du protocole TLS (Transport Layer Security) peuvent être dépréciées si des vulnérabilités sont détectées. Évitez de coder en dur les valeurs de SslProtocols pour que votre application reste sécurisée. Utilisez 'None' pour laisser le système d'exploitation choisir une version. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Évitez de coder en dur les valeurs '{0}' de SslProtocols pour que votre application reste sécurisée de manière durable. Utilisez 'None' pour laisser le système d'exploitation choisir une version. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Évitez de coder en dur les valeurs de SslProtocols 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. - 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. + Quand vous désérialisez une entrée non fiable, autoriser la désérialisation de types arbitraires n'est pas une action sécurisée. Quand vous désérialisez JsonSerializer, utilisez TypeNameHandling.None, ou pour les valeurs autres que None, restreignez les types désérialisés avec SerializationBinder. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + N'effectuez pas de désérialisation avec JsonSerializer à l'aide d'une configuration non sécurisée 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. - 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. + Quand vous désérialisez une entrée non fiable, autoriser la désérialisation de types arbitraires n'est pas une action sécurisée. Quand vous désérialisez JsonSerializer, utilisez TypeNameHandling.None, ou pour les valeurs autres que None, restreignez les types désérialisés avec SerializationBinder. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Vérifiez que JsonSerializer a une configuration sécurisée au moment de la désérialisation + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Attribut HttpVerb manquant pour les méthodes d'action All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Toutes les méthodes permettant de créer, modifier ou supprimer des données, ou de les changer de quelque façon que ce soit, le font dans la surcharge [HttpPost] de la méthode, laquelle doit être protégée avec l'attribut antifalsification relatif à la falsification de requête. L'exécution d'une opération GET doit être une opération sécurisée qui n'a aucun effet secondaire et ne modifie pas vos données persistantes. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + La méthode d'action {0} doit spécifier explicitement le genre de requête HTTP @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Affectez la valeur true à HttpOnly pour 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. - 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. + En tant que mesure de défense renforcée, vérifiez que les cookies HTTP dont la sécurité est critique sont marqués avec HttpOnly. Cela indique aux navigateurs web qu'ils doivent interdire aux scripts d'accéder aux cookies. L'injection de scripts malveillants est un moyen courant de voler des cookies. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie.HttpOnly a la valeur false ou n'est pas défini du tout durant l'utilisation d'un HttpCookie. Vérifiez que les cookies dont la sécurité est critique sont marqués avec HttpOnly pour empêcher les scripts malveillants de les voler @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Utilisez des jetons antifalsification dans les contrôleurs ASP.NET Core MVC Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + Le traitement d'une requête POST, PUT, PATCH ou DELETE sans validation d'un jeton antifalsification peut être vulnérable aux attaques par falsification de requête intersites. Une attaque par falsification de requête intersites peut envoyer des requêtes malveillantes de la part d'un utilisateur authentifié à votre contrôleur ASP.NET Core MVC. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + La méthode {0} traite une requête {1} sans validation de jeton antifalsification. Vous devez également vérifier que votre formulaire HTML envoie un jeton antifalsification. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Utilisez l'attribut DefaultDllImportSearchPaths pour les P/Invoke 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. - 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. + Par défaut, les P/Invoke qui utilisent DllImportAttribute sondent un certain nombre de répertoires, notamment le répertoire de travail actuel de la bibliothèque à charger. Cela peut poser un problème de sécurité pour certaines applications, et se traduire par un détournement de DLL. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + La méthode {0} n'a pas utilisé l'attribut DefaultDllImportSearchPaths pour les P/Invoke. @@ -589,7 +589,7 @@ Higher-frequency periodic activity will keep the CPU busy and interfere with power-saving idle timers that turn off the display and hard disks. - Une activité périodique très fréquente sollicite l'UC et interfère avec les minuteurs d'inactivité qui déclenchent la mise en veille de l'écran et des disques durs pour économiser de l'énergie. + Une activité régulière à plus grande fréquence occupe le processeur et interfère avec les minuteurs d'inactivité qui déclenchent la mise en veille de l'écran et des disques durs pour économiser de l'énergie. @@ -1029,7 +1029,7 @@ 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. - La méthode « {0} » n'est pas sécurisée durant la désérialisation de données non fiables à l'aide d'un JavaScriptSerializer initialisé avec un SimpleTypeResolver. Vérifiez que JavaScriptSerializer est initialisé sans JavaScriptTypeResolver ou avec un JavaScriptTypeResolver qui limite ces types d'objets dans le graphe d'objet désérialisé. + La méthode '{0}' n'est pas sécurisée durant la désérialisation de données non fiables à l'aide d'un JavaScriptSerializer initialisé avec un SimpleTypeResolver. Vérifiez que JavaScriptSerializer est initialisé sans JavaScriptTypeResolver, ou qu'il est initialisé avec un JavaScriptTypeResolver qui limite les types des objets dans le graphe d'objet désérialisé. @@ -1039,7 +1039,7 @@ 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. - La méthode « {0} » n'est pas sécurisée durant la désérialisation de données non fiables à l'aide d'un JavaScriptSerializer initialisé avec un SimpleTypeResolver. Initialisez JavaScriptSerializer sans JavaScriptTypeResolver ou avec un JavaScriptTypeResolver qui limite ces types d'objets dans le graphe d'objet désérialisé. + La méthode '{0}' n'est pas sécurisée durant la désérialisation de données non fiables à l'aide d'un JavaScriptSerializer initialisé avec un SimpleTypeResolver. Initialisez JavaScriptSerializer sans JavaScriptTypeResolver, ou initialisez un JavaScriptTypeResolver qui limite les types des objets dans le graphe d'objet désérialisé. @@ -1049,37 +1049,37 @@ 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. - 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. + Quand vous désérialisez une entrée non fiable, autoriser la désérialisation de types arbitraires n'est pas une action sécurisée. Quand vous utilisez JsonSerializerSettings, utilisez TypeNameHandling.None, ou pour les valeurs autres que None, restreignez les types désérialisés avec SerializationBinder. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + N'utilisez pas de JsonSerializerSettings non sécurisé 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. - 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. + Quand vous désérialisez une entrée non fiable, autoriser la désérialisation de types arbitraires n'est pas une action sécurisée. Quand vous utilisez JsonSerializerSettings, vérifiez que TypeNameHandling.None est spécifié. Pour les valeurs autres que None, vérifiez que SerializationBinder est spécifié afin de restreindre les types désérialisés. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Vérifiez la sécurisation de JsonSerializerSettings 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. - 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. + Si vous désérialisez JSON quand vous utilisez une autre valeur que None pour TypeNameHandling, cela peut présenter un risque de sécurité. Si vous devez plutôt détecter la désérialisation de Json.NET quand aucun SerializationBinder n'est spécifié, désactivez la règle CA2326, et activez les règles CA2327, CA2328, CA2329 et CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + Si vous désérialisez JSON quand vous utilisez une autre valeur que None pour TypeNameHandling, cela peut présenter un risque de sécurité. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + N'utilisez pas d'autre valeur que None pour TypeNameHandling @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Ne pas coder en dur la clé de chiffrement SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + La propriété .Key de SymmetricAlgorithm ou le paramètre rgbKey d'une méthode ne doivent jamais correspondre à une valeur codée en dur. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Une vulnérabilité potentielle liée à la sécurité a été détectée. '{0}' dans la méthode '{1}' peut être altéré par une clé codée en dur en provenance de '{2}' dans la méthode '{3}' diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf index e0c1492e5e..4b6f02be6e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Le versioni precedenti del protocollo Transport Layer Security (TLS) sono meno sicure rispetto a TLS 1.2 e TLS 1.3 e presentano maggiori probabilità di includere nuove vulnerabilità. Evitare le versioni precedenti del protocollo per ridurre al minimo i rischi. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + La versione '{0}' del protocollo Transport Layer Security è deprecata. Usare 'None' per consentire al sistema operativo di scegliere una versione. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Non usare valori SslProtocols deprecati @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Non usare la casualità non sicura {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} è un generatore di numeri casuali non sicuro. Usare generatori di numeri casuali sicuri dal punto di vista della crittografia quando per motivi di sicurezza è richiesta la casualità Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + L'uso di un generatore di numeri pseudo-casuali vulnerabile dal punto di vista della crittografia può consentire a un utente malintenzionato di prevedere il valore sensibile alla sicurezza che verrà generato. Se è richiesto un valore non prevedibile, usare un generatore di numeri casuali sicuro dal punto di vista della crittografia oppure verificare che i numeri pseudo-casuali vulnerabili non vengano usati in modo sensibile per la sicurezza. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Non usare il valore DllImportSearchPath non sicuro 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. - 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. + Nelle directory di ricerca DLL predefinite potrebbe essere presente una DLL dannosa oppure, a seconda della posizione di esecuzione dell'applicazione, nella directory dell'applicazione potrebbe essere presente una DLL dannosa. Usare un valore DllImportSearchPath che specifica un percorso di ricerca esplicito. I flag DllImportSearchPath cercati da questa regola possono essere configurati nel file con estensione editorconfig. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Uso del valore {0} non sicuro di DllImportSearchPath Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Le versioni correnti del protocollo Transport Layer Security potrebbero diventare deprecate se vengono trovate vulnerabilità. Per garantire la protezione dell'applicazione, evitare di impostare i valori SslProtocols come hardcoded. Usare 'None' per consentire al sistema operativo di scegliere una versione. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Evitare di impostare i valori '{0}' di SslProtocols come hardcoded per garantire che l'applicazione rimanga protetta in futuro. Usare 'None' per consentire al sistema operativo di scegliere una versione. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Evitare di impostare i valori di SslProtocols come hardcoded 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. - 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. + Quando si deserializza input non attendibile, non è sicuro consentire la deserializzazione di tipi arbitrari. Quando si deserializza con JsonSerializer, usare TypeNameHandling.None oppure, per valori diversi da None, limitare i tipi deserializzati con un elemento SerializationBinder. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + Non deserializzare con JsonSerializer usando una configurazione non sicura 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. - 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. + Quando si deserializza input non attendibile, non è sicuro consentire la deserializzazione di tipi arbitrari. Quando si deserializza con JsonSerializer, usare TypeNameHandling.None oppure, per valori diversi da None, limitare i tipi deserializzati con un elemento SerializationBinder. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Assicurarsi che la configurazione di JsonSerializer sia sicura durante la deserializzazione + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Attributo HttpVerb mancante per i metodi di azione All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Tutti i metodi che consentono di creare, modificare, eliminare o cambiare in altro modo i dati usano l'overload [HttpPost] del metodo, che deve essere protetto dalla falsificazione delle richieste con l'apposito attributo antifalsificazione. L'esecuzione di un'operazione GET deve essere un'operazione sicura che non presenta effetti collaterali e non modifica i dati persistenti. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + Il metodo di azione {0} deve specificare in modo esplicito il tipo della richiesta HTTP @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Impostare HttpOnly su true per 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. - 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. + Come ulteriore misura di difesa, assicurarsi che i cookie HTTP sensibili alla sicurezza siano contrassegnati come HttpOnly. In questo modo il Web browser non consentirà agli script di accedere ai cookie. Il modo più comune per appropriarsi dei cookie consiste nell'usare script in cui viene inserito codice dannoso. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie.HttpOnly è impostato su false o non è impostato affatto quando si usa un elemento HttpCookie. Assicurarsi che i cookie sensibili alla sicurezza siano contrassegnati come HttpOnly per impedire a script dannosi di appropriarsi dei cookie @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Usare token antifalsificazione nei controller MVC ASP.NET Core Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + La gestione di una richiesta POST, PUT, PATCH o DELETE senza la convalida di un token antifalsificazione può essere vulnerabile ad attacchi di tipo richiesta intersito falsa. In un attacco di questo tipo vengono inviate richieste dannose da un utente autenticato al controller MVC ASP.NET Core. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + Il metodo {0} gestisce una richiesta {1} senza eseguire la convalida del token antifalsificazione. È necessario assicurarsi anche che il modulo HTML invii un token antifalsificazione. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Usare l'attributo DefaultDllImportSearchPaths per i P/Invoke 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. - 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. + Per impostazione predefinita, i P/Invoke che usano DllImportAttribute esaminano un certo numero di directory, tra cui la directory di lavoro corrente per la libreria da caricare. Per alcune applicazioni questo comportamento può costituire un problema di sicurezza che permette di assumere il controllo delle DLL. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + Il metodo {0} non ha usato l'attributo DefaultDllImportSearchPaths per i P/Invoke. @@ -589,7 +589,7 @@ Higher-frequency periodic activity will keep the CPU busy and interfere with power-saving idle timers that turn off the display and hard disks. - Un'attività periodica più frequente tiene occupata la CPU e interferisce con i timer di inattività per il risparmio di energia che disattivano lo schermo e i dischi rigidi. + Un'attività periodica più frequente tiene la CPU occupata e interferisce con i timer di inattività per il risparmio di energia che disattivano lo schermo e i dischi rigidi. @@ -1029,7 +1029,7 @@ 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. - Il metodo '{0}' non è sicuro quando si deserializzano dati non attendibili con un elemento JavaScriptSerializer inizializzato con un elemento SimpleTypeResolver. Assicurarsi che l'elemento JavaScriptSerializer venga inizializzato senza specificare un elemento JavaScriptTypeResolver oppure che venga inizializzato con un elemento JavaScriptTypeResolver che limita tale tipo di oggetti nell'oggetto grafico deserializzato. + Il metodo '{0}' non è sicuro quando si deserializzano dati non attendibili con un elemento JavaScriptSerializer inizializzato con un elemento SimpleTypeResolver. Assicurarsi che l'elemento JavaScriptSerializer venga inizializzato senza specificare un elemento JavaScriptTypeResolver oppure che venga inizializzato con un elemento JavaScriptTypeResolver che limita i tipi di oggetti nell'oggetto grafico deserializzato. @@ -1039,7 +1039,7 @@ 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. - Il metodo '{0}' non è sicuro quando si deserializzano dati non attendibili con un elemento JavaScriptSerializer inizializzato con un elemento SimpleTypeResolver. Inizializzare JavaScriptSerializer senza specificare un elemento JavaScriptTypeResolver oppure inizializzarlo con un elemento JavaScriptTypeResolver che limita tale tipo di oggetti nell'oggetto grafico deserializzato. + Il metodo '{0}' non è sicuro quando si deserializzano dati non attendibili con un elemento JavaScriptSerializer inizializzato con un elemento SimpleTypeResolver. Inizializzare JavaScriptSerializer senza specificare un elemento JavaScriptTypeResolver oppure inizializzarlo con un elemento JavaScriptTypeResolver che limita i tipi di oggetti nell'oggetto grafico deserializzato. @@ -1049,37 +1049,37 @@ 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. - 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. + Quando si deserializza input non attendibile, non è sicuro consentire la deserializzazione di tipi arbitrari. Quando si usa JsonSerializerSettings, usare TypeNameHandling.None oppure, per valori diversi da None, limitare i tipi deserializzati con un elemento SerializationBinder. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Non usare l'elemento JsonSerializerSettings non sicuro 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. - 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. + Quando si deserializza input non attendibile, non è sicuro consentire la deserializzazione di tipi arbitrari. Quando si usa JsonSerializerSettings, assicurarsi che TypeNameHandling.None sia specificato oppure, per valori diversi da None, assicurarsi che sia specificato un elemento SerializationBinder per limitare i tipi deserializzati. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Assicurarsi che l'elemento JsonSerializerSettings sia sicuro 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. - 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. + La deserializzazione di JSON quando si usa un valore TypeNameHandling diverso da None può essere insicura. Se è necessario rilevare invece la deserializzazione di JSON.NET quando non è specificato alcun oggetto SerializationBinder, disabilitare la regola CA2326 e abilitare le regole CA2327, CA2328, CA2329 e CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + La deserializzazione di JSON quando si usa un valore TypeNameHandling diverso da None può essere insicura. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + Non usare valori di TypeNameHandling diversi da None @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Non impostare la chiave di crittografia come hardcoded SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + La proprietà .Key di SymmetricAlgorithm o il parametro rgbKey di un metodo non deve essere mai essere un valore hardcoded. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + È stata trovata una potenziale vulnerabilità di sicurezza in cui '{0}' nel metodo '{1}' può essere contaminato dalla chiave hardcoded di '{2}' nel metodo '{3}' diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf index c1fec88046..70ddc58d05 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + トランスポート層セキュリティ (TLS) の以前のプロトコル バージョンは、TLS 1.2 および TLS 1.3 よりも安全性が低く、新しい脆弱性が見つかる可能性が高くなります。リスクを最小限に抑えるため、以前のプロトコル バージョンは使用しないでください。 Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + トランスポート層セキュリティ プロトコルのバージョン '{0}' は非推奨です。オペレーティング システムがバージョンを選択できるようにするには、'None' を使用します。 Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + SslProtocols の非推奨の値を使用しない @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + 安全でないランダム度を使用しない {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} は安全でない乱数ジェネレーターです。セキュリティにランダム度が必要な場合に、暗号化によってセキュリティで保護された乱数ジェネレーターを使用します Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + 暗号強度の低い擬似乱数ジェネレーターを使用すると、セキュリティ上注意が必要などのような値が生成されるかを攻撃者が予測できる可能性があります。予測できない値が必要な場合は暗号強度の高い乱数ジェネレーターを使用するか、または暗号強度の低い疑似乱数がセキュリティ上注意が必要な形で使用されていないことを確認してください。 Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + 安全でない DllImportSearchPath 値を使用しない 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. - 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. + 既定の DLL 検索ディレクトリ内に悪意のある DLL が存在する可能性があります。または、アプリケーションが実行されている場所に応じて、アプリケーションのディレクトリに悪意のある DLL が存在する可能性があります。代わりに、明示的な検索パスを指定する DllImportSearchPath 値を使用してください。この規則で検索される DllImportSearchPath フラグは、.editorconfig で構成できます。 Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + 安全でない DllImportSearchPath 値 {0} の使用 Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + 現在のトランスポート層セキュリティ プロトコルのバージョンに脆弱性が見つかると、非推奨になる可能性があります。アプリケーションのセキュリティを維持するために、SslProtocols の値をハードコードしないでください。オペレーティング システムがバージョンを選択できるようにするには、'None' を使用します。 Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + 今後のアプリケーションのセキュリティを確保するため、SslProtocols '{0}' をハードコードしないでください。オペレーティング システムがバージョンを選択できるようにするには、'None' を使用します。 Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + ハードコードされた SslProtocols の値を使用しない 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. - 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. + 信頼されていない入力を逆シリアル化するときに、任意の型の逆シリアル化を許可することは安全ではありません。逆シリアル化 JsonSerializer を使用する場合は TypeNameHandling.None を使用し、None 以外の値の場合は SerializationBinder を使用して逆シリアル化の種類を制限します。 Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + 安全でない構成を使用している JsonSerializer で逆シリアル化をしない 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. - 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. + 信頼されていない入力を逆シリアル化するときに、任意の型の逆シリアル化を許可することは安全ではありません。逆シリアル化 JsonSerializer を使用する場合は TypeNameHandling.None を使用し、None 以外の値の場合は SerializationBinder を使用して逆シリアル化の種類を制限します。 Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + 逆シリアル化するときに JsonSerializer に安全な構成があることを確認する + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + アクション メソッドの HttpVerb 属性がない All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + データの作成、編集、削除、または変更を行うすべてのメソッドでは、メソッドの [HttpPost] オーバーロードでそれらの操作が実行されます。これは、リクエスト フォージェリからの偽造防止属性を使用して保護する必要があります。取得操作の実行は副作用がなく、持続データを変更しない安全な操作である必要があります。 Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + アクション メソッド {0} では、HTTP 要求の種類を明示的に指定する必要があります @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + HttpCookie で HttpOnly を true に設定する 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. - 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. + 高度な防御手段として、セキュリティ上注意が必要な HTTP Cookie が、必ず HttpOnly としてマークされるようにしてください。これは、スクリプトから Cookie へのアクセスを Web ブラウザーで許可してはならないことを示しています。挿入された悪意のあるスクリプトは、Cookie を盗むための一般的な方法です。 HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie を使用している場合、HttpCookie.HttpOnly は false に設定されるか、まったく設定されません。悪意のあるスクリプトによって Cookie が盗まれないようにするために、セキュリティ上注意が必要な Cookie が、必ず HttpOnly としてマークされるようにしてください @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + ASP.NET Core MVC コントローラーで偽造防止トークンを使用する Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + 偽造防止トークンを検証せずに POST、PUT、PATCH、DELETE 要求を処理すると、クロスサイト リクエスト フォージェリ攻撃に対して脆弱になる可能性があります。クロスサイト リクエスト フォージェリ攻撃では、認証されたユーザーから ASP.NET Core MVC コントローラーに悪意のある要求が送信される可能性があります。 Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + メソッド {0} では、偽造防止トークンの検証を実行せずに {1} 要求が処理されます。また、HTML フォームで偽造防止トークンが送信されるようにする必要もあります。 Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + P/Invoke に対して DefaultDllImportSearchPaths 属性を使用する 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. - 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. + 既定では、DllImportAttribute を使用している P/Invoke は、ライブラリが読み込むための現在の作業ディレクトリを含むいくつかのディレクトリを精査します。これは特定のアプリケーションでセキュリティ上の問題を引き起こし、DLL のハイジャックにつながる可能性があります。 The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + メソッド {0} で、P/Invoke に対して DefaultDllImportSearchPaths 属性が使用されませんでした。 @@ -1029,7 +1029,7 @@ 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. - SimpleTypeResolver で初期化された JavaScriptSerializer で信頼されていないデータを逆シリアル化している場合、メソッド '{0}' は安全ではありません。JavaScriptTypeResolver が指定されずに JavaScriptSerializer が初期化されていること、または逆シリアル化されたオブジェクト グラフ内のオブジェクトの種類を制限する JavaScriptTypeResolver で初期化されていることを確認してください。 + SimpleTypeResolver で初期化された JavaScriptSerializer で信頼されていないデータを逆シリアル化している場合、メソッド '{0}' は安全ではありません。JavaScriptTypeResolver が指定されずに JavaScriptSerializer が初期化されていること、または逆シリアル化されたオブジェクト グラフ内のオブジェクトの種類を制限する JavaScriptTypeResolver で初期化されていることをご確認ください。 @@ -1039,7 +1039,7 @@ 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. - SimpleTypeResolver で初期化された JavaScriptSerializer で信頼されていないデータを逆シリアル化している場合、メソッド '{0}' は安全ではありません。JavaScriptTypeResolver を指定せずに JavaScriptSerializer を初期化するか、逆シリアル化されたオブジェクト グラフ内のオブジェクトの種類を制限する JavaScriptTypeResolver で初期化します。 + SimpleTypeResolver で初期化された JavaScriptSerializer で信頼されていないデータを逆シリアル化している場合、メソッド '{0}' は安全ではありません。JavaScriptTypeResolver を指定せずに JavaScriptSerializer を初期化するか、逆シリアル化されたオブジェクト グラフ内のオブジェクトの種類を制限する JavaScriptTypeResolver で初期化します。 @@ -1049,37 +1049,37 @@ 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. - 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. + 信頼されていない入力を逆シリアル化するときに、任意の型の逆シリアル化を許可することは安全ではありません。JsonSerializerSettings を使用する場合は TypeNameHandling.None を使用し、None 以外の値の場合は SerializationBinder を使用して逆シリアル化の種類を制限します。 Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + 安全でない JsonSerializerSettings を使用しない 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. - 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. + 信頼されていない入力を逆シリアル化するときに、任意の型の逆シリアル化を許可することは安全ではありません。JsonSerializerSettings を使用する場合は TypeNameHandling.None が指定されていること、None 以外の値の場合は SerializationBinder を指定して逆シリアル化の種類が制限されていることをご確認ください。 Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + JsonSerializerSettings がセキュリティで保護されていることの確認 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. - 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. + None 以外の TypeNameHandling 値を使用する場合の JSON の逆シリアル化は、安全でない可能性があります。SerializationBinder が指定されていないときに Json.NET の逆シリアル化を検出する必要がある場合は、規則 CA2326 を無効にして、規則 CA2327、CA2328、CA2329、CA2330 を有効にしてください。 Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + None 以外の TypeNameHandling 値を使用する場合の JSON の逆シリアル化は、安全でない可能性があります。 Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + None 以外の TypeNameHandling 値を使用しないでください @@ -1319,7 +1319,7 @@ 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. - アーカイブからファイルを抽出し、アーカイブ アイテムのパスを使用するときは、パスが安全であるかどうかを確認します。アーカイブ パスは相対パスの場合があり、想定されるファイル システムのターゲット パス以外でファイル システムへのアクセスを引き起こす可能性があります。これは、lay-and-wait の技法によって悪意のある構成変更とリモート コードの実行につながります。 + アーカイブからファイルを抽出し、アーカイブ アイテムのパスを使用するときは、パスが安全であるかどうかを確認します。アーカイブ パスは相対パスの場合があり、想定されるファイル システムのターゲット パス以外でファイル システムへのアクセスが可能になる可能性があります。これは、lay-and-wait の技法によって悪意のある構成変更とリモート コードの実行につながります。 @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + 暗号化キーをハード コードしない SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + SymmetricAlgorithm の .Key プロパティまたはメソッドの rgbKey パラメーターをハードコードされた値にすることはできません。 Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + 潜在的なセキュリティの脆弱性が見つかりました。メソッド '{1}' の '{0}' は、メソッド '{3}' の '{2}' からのハードコードされたキーによって悪用される可能性があります diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf index 559c5f2635..b3c339624c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + TLS(전송 계층 보안)의 이전 프로토콜 버전은 TLS 1.2 및 TLS 1.3보다 보안 수준이 낮으며 새로운 취약성이 발생할 가능성이 더 높습니다. 위험을 최소화하려면 이전 프로토콜 버전을 사용하지 마세요. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + 전송 계층 보안 프로토콜 버전 '{0}'은(는) 사용되지 않습니다. 운영 체제에서 버전을 선택하도록 하려면 '없음'을 사용하세요. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + 사용되지 않는 SslProtocols 값 사용 안 함 @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + 안전하지 않은 임의성 사용 안 함 {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0}은(는) 안전하지 않은 난수 생성기입니다. 보안을 위해 임의성이 필요한 경우 암호화된 보안 난수 생성기를 사용합니다. Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + 암호화가 약한 의사 난수 생성기를 사용하면 공격자가 생성되는 보안에 중요한 값을 예측할 수 있습니다. 예측 불가능한 값이 필요한 경우 암호화가 강한 난수 생성기를 사용하거나, 약한 의사 난수가 보안에 중요한 방식으로 사용되지 않도록 하세요. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + 안전하지 않은 DllImportSearchPath 값 사용 안 함 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. - 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. + 기본 DLL 검색 디렉터리에 악성 DLL이 있을 수 있습니다. 또는 애플리케이션이 실행되는 위치에 따라 애플리케이션의 디렉터리에 악성 DLL이 있을 수 있습니다. 대신 명시적 검색 경로를 지정하는 DllImportSearchPath 값을 사용합니다. 이 규칙이 검색하는 DllImportSearchPath 플래그는 .editorconfig에서 구성할 수 있습니다. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + 안전하지 않은 DllImportSearchPath 값 {0} 사용 Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + 취약성이 발견되면 현재 전송 계층 보안 프로토콜 버전이 사용되지 않을 수 있습니다. 애플리케이션을 안전하게 유지하려면 SslProtocols 값을 하드 코딩하지 않습니다. 운영 체제에서 버전을 선택하도록 하려면 '없음'을 사용합니다. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + 앞으로 애플리케이션을 안전하게 유지하려면 SslProtocols '{0}'을(를) 하드 코딩하지 마세요. 운영 체제에서 버전을 선택하도록 하려면 '없음'을 사용하세요. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + 하드 코딩된 SslProtocols 값 방지 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. - 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. + 신뢰할 수 없는 입력을 deserialize하는 경우 deserialize되는 임의 형식을 허용하는 것은 안전하지 않습니다. JsonSerializer를 deserialize하는 경우 TypeNameHandling.None을 사용하고, 또는 None 이외의 값에 대해 SerializationBinder를 사용하여 deserialize된 형식을 제한하세요. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + 안전하지 않은 구성을 사용하여 JsonSerializer로 deserialize 안 함 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. - 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. + 신뢰할 수 없는 입력을 deserialize하는 경우 deserialize되는 임의 형식을 허용하는 것은 안전하지 않습니다. JsonSerializer를 deserialize하는 경우 TypeNameHandling.None을 사용하고, 또는 None 이외의 값에 대해 SerializationBinder를 사용하여 deserialize된 형식을 제한하세요. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + deserialize할 때 JsonSerializer에 보안 구성이 있는지 확인 + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + 작업 메서드의 HttpVerb 특성 누락 All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + 데이터를 생성, 편집, 삭제 또는 수정하는 모든 메서드는 위조 방지 특성을 사용하여 요청 위조로부터 보호되어야 하는 메서드의 [HttpPost] 오버로드에서 해당 작업을 수행합니다. GET 작업 수행은 부작용이 없고 영구 데이터를 수정하지 않는 안전한 작업이어야 합니다. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + 작업 메서드 {0}은(는) Http 요청 종류를 명시적으로 지정해야 합니다. @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + HttpCookie에 대해 HttpOnly를 true로 설정 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. - 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. + 심층 방어 수단으로 보안에 중요한 HTTP 쿠키가 HttpOnly로 표시되어 있는지 확인합니다. 이는 웹 브라우저에서 스크립트가 쿠키에 액세스하는 것을 허용하지 않아야 함을 나타냅니다. 삽입된 악성 스크립트는 쿠키를 도용하는 일반적인 방법입니다. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie를 사용할 경우 HttpCookie.HttpOnly가 false로 설정되거나, 설정되지 않습니다. 악성 스크립트가 쿠키를 도용하지 못하도록 하려면 보안에 중요한 쿠키가 HttpOnly로 표시되어 있는지 확인하세요. @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + ASP.NET Core MVC 컨트롤러에서 위조 방지 토큰 사용 Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + 위조 방지 토큰의 유효성을 검사하지 않고 POST, PUT, PATCH 또는 DELETE 요청을 처리하면 교차 사이트 요청 위조 공격에 취약할 수 있습니다. 교차 사이트 요청 위조 공격은 인증된 사용자의 악성 요청을 ASP.NET Core MVC 컨트롤러로 보낼 수 있습니다. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + {0} 메서드는 위조 방지 토큰 유효성 검사를 수행하지 않고 {1} 요청을 처리합니다. 또한 HTML 양식이 위조 방지 토큰을 보내는지 확인해야 합니다. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + P/Invokes에 DefaultDllImportSearchPaths 특성 사용 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. - 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. + 기본적으로 DllImportAttribute를 사용하는 P/Invokes는 로드할 라이브러리의 현재 작업 디렉터리를 비롯한 여러 디렉터리를 프로브합니다. 이는 특정 애플리케이션에서 DLL 하이재킹으로 이어지는 보안 문제가 될 수 있습니다. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + {0} 메서드는 P/Invokes에 DefaultDllImportSearchPaths 특성을 사용하지 않았습니다. @@ -1029,7 +1029,7 @@ 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. - SimpleTypeResolver로 초기화된 JavaScriptSerializer로 신뢰할 수 없는 데이터를 deserialize하는 경우 '{0}' 메서드는 안전하지 않습니다. JavaScriptSerializer가 JavaScriptTypeResolver가 지정되지 않은 상태로 초기화되었거나 deserialize된 개체 그래프에서 해당 개체 형식을 제한하는 JavaScriptTypeResolver로 초기화되었는지 확인하세요. + SimpleTypeResolver로 초기화된 JavaScriptSerializer로 신뢰할 수 없는 데이터를 deserialize하는 경우 '{0}' 메서드는 안전하지 않습니다. JavaScriptSerializer가 JavaScriptTypeResolver가 지정되지 않은 상태로 초기화되었거나 deserialize된 개체 그래프에서 해당 개체 형식을 제한하는 JavaScriptTypeResolver로 초기화되었는지 확인하세요. @@ -1039,7 +1039,7 @@ 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. - SimpleTypeResolver로 초기화된 JavaScriptSerializer로 신뢰할 수 없는 데이터를 deserialize하는 경우 '{0}' 메서드는 안전하지 않습니다. JavaScriptTypeResolver가 지정되지 않은 상태로 JavaScriptSerializer를 초기화하거나 deserialize된 개체 그래프에서 해당 개체 형식을 제한하는 JavaScriptTypeResolver로 초기화하세요. + SimpleTypeResolver로 초기화된 JavaScriptSerializer로 신뢰할 수 없는 데이터를 deserialize하는 경우 '{0}' 메서드는 안전하지 않습니다. JavaScriptTypeResolver가 지정되지 않은 상태로 JavaScriptSerializer를 초기화하거나 deserialize된 개체 그래프에서 해당 개체 형식을 제한하는 JavaScriptTypeResolver로 초기화하세요. @@ -1049,37 +1049,37 @@ 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. - 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. + 신뢰할 수 없는 입력을 deserialize하는 경우 deserialize되는 임의 형식을 허용하는 것은 안전하지 않습니다. JsonSerializerSettings를 사용하는 경우 TypeNameHandling.None을 사용하고, 또는 None 이외의 값에 대해 SerializationBinder를 사용하여 deserialize된 형식을 제한하세요. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + 안전하지 않은 JsonSerializerSettings를 사용하지 마세요. 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. - 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. + 신뢰할 수 없는 입력을 deserialize하는 경우 deserialize되는 임의 형식을 허용하는 것은 안전하지 않습니다. JsonSerializerSettings를 사용하는 경우 TypeNameHandling.None이 지정되었는지 확인하고, 또는 None 이외의 값에 대해 SerializationBinder가 지정되어 deserialize된 형식을 제한하는지 확인하세요. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + JsonSerializerSettings가 안전한지 확인하세요. 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. - 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. + None 이외의 TypeNameHandling 값을 사용하는 경우 JSON deserialize가 안전하지 않을 수 있습니다. SerializationBinder가 지정되지 않았을 때 대신 Json.NET deserialization을 검색해야 하는 경우 CA2326 규칙을 사용하지 않도록 설정하고 CA2327, CA2328, CA2329, CA2330 규칙을 사용하도록 설정합니다. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + None 이외의 TypeNameHandling 값을 사용하는 경우 JSON deserialize가 안전하지 않을 수 있습니다. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + None 이외의 TypeNameHandling 값을 사용하지 마세요. @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + 암호화 키 하드 코딩 안 함 SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + SymmetricAlgorithm의 .Key 속성 또는 메서드의 rgbKey 매개 변수는 하드 코딩된 값이어서는 안 됩니다. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + '{1}' 메서드의 '{0}'이(가) '{3}' 메서드의 '{2}'에서 하드 코딩된 키에 의해 감염될 수 있는 잠재적인 보안 취약성이 발견되었습니다. diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf index 3d8013cba6..21c0ceb63e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Starsze wersje protokołu Transport Layer Security (TLS) są mniej bezpieczne niż TLS 1.2 i TLS 1.3 i mogą być bardziej podatne na luki w zabezpieczeniach. Aby zminimalizować ryzyko, unikaj używania starszych wersji protokołu. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + Wersja protokołu Transport Layer Security „{0}” jest przestarzała. Użyj opcji „Brak”, aby umożliwić systemowi operacyjnemu wybranie wersji. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Nie używaj przestarzałych wartości SslProtocols @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Nie używaj niezabezpieczonej losowości {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} to niezabezpieczony generator liczb losowych. Użyj kryptograficznie zabezpieczonego generatora liczb losowych, gdy losowość jest wymagana ze względów bezpieczeństwa. Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + Użycie kryptograficznie słabego generatora liczb pseudolosowych może umożliwić osobie atakującej przewidzenie, jaka wartość wpływająca na zabezpieczenia zostanie wygenerowana. Użyj kryptograficznie silnego generatora liczb losowych, jeśli jest wymagana wartości niemożliwa do przewidzenia, lub upewnij się, że liczby pseudolosowe nie są używane w przypadku wartości wpływających na zabezpieczenia . Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Nie używaj niebezpiecznej wartości DllImportSearchPath 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. - 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. + W domyślnych katalogach wyszukiwania bibliotek DLL może znajdować się złośliwa biblioteka DLL albo, w zależności od tego, z jakiej lokalizacji jest uruchamiana aplikacja, złośliwa biblioteka DLL może znajdować się w katalogu aplikacji. W zastępstwie użyj wartości DllImportSearchPath, która określa jawną ścieżkę wyszukiwania. Flagi DllImportSearchPath, które wyszukuje ta reguła, można skonfigurować w pliku .editorconfig. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Użycie niebezpiecznej wartości DllImportSearchPath {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Bieżące wersje protokołu Transport Layer Security mogą zostać uznane za przestarzałe w przypadku znalezienia luk w zabezpieczeniach. Unikaj kodowania na stałe wartości SslProtocols, aby zachować bezpieczeństwo aplikacji. Użyj opcji „Brak”, aby umożliwić systemowi operacyjnemu wybranie wersji. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Unikaj kodowania na stałe wartości SslProtocols „{0}”, aby zapewnić bezpieczeństwo aplikacji w przyszłości. Użyj opcji „Brak”, aby umożliwić systemowi operacyjnemu wybranie wersji. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Unikaj kodowania na stałe wartości SslProtocols 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. - 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. + Podczas deserializacji niezaufanych danych wejściowych zezwolenie na deserializację dowolnych typów jest mało bezpieczne. W przypadku deserializacji typu JsonSerializer użyj wartości TypeNameHandling.None lub, w przypadku wartości innych niż None, użyj elementu SerializationBinder w celu ograniczenia typów deserializowanych. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + Nie wykonuj deserializacji typu JsonSerializer przy użyciu niezabezpieczonej konfiguracji 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. - 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. + Podczas deserializacji niezaufanych danych wejściowych zezwolenie na deserializację dowolnych typów jest mało bezpieczne. W przypadku deserializacji typu JsonSerializer użyj wartości TypeNameHandling.None lub, w przypadku wartości innych niż None, użyj elementu SerializationBinder w celu ograniczenia typów deserializowanych. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Upewnij się, że element JsonSerializer ma bezpieczną konfigurację podczas deserializacji + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Pomiń atrybut HttpVerb dla metod akcji All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Wszystkie metody, które tworzą, edytują, usuwają lub w inny sposób modyfikują dane, dokonują tego w przeciążeniu [HttpPost] metody, która musi być chroniona przy użyciu atrybutu zabezpieczającego przed fałszerstwem przez sfałszowanie żądania. Wykonanie operacji GET powinno być bezpieczną operacją, która nie ma żadnych efektów ubocznych i nie powoduje modyfikacji utrwalonych danych. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + Metoda akcji {0} musi jawnie określać rodzaj żądania Http @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Ustaw element HttpOnly na wartość true dla elementu 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. - 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. + W celu zapewnienia kompleksowej ochrony upewnij się, że wpływające na zabezpieczenia pliki cookie protokołu HTTP są oznaczone jako HttpOnly. Oznacza to, że przeglądarki internetowe powinny uniemożliwić skryptom uzyskiwanie dostępu do tych plików cookie. Wstrzykiwanie złośliwych skryptów to typowy sposób kradzieży plików cookie. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + Właściwość HttpCookie.HttpOnly jest ustawiana na wartość false lub nie jest konfigurowana wcale w przypadku używania elementu HttpCookie. Upewnij się, że wpływające na zabezpieczenia pliki cookie są oznaczone jako HttpOnly, aby uniemożliwić złośliwym skryptom kradzież plików cookie @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Użyj tokenów zabezpieczających przed fałszerstwem w kontrolerach MVC ASP.NET Core Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + Obsługa żądania POST, PUT, PATCH lub DELETE bez weryfikacji tokenu zabezpieczającego przed fałszerstwem może prowadzić do podatności na ataki z wykorzystaniem fałszerstwa żądania międzywitrynowego. Atak z wykorzystaniem fałszerstwa żądania międzywitrynowego może wysyłać złośliwe żądania od uwierzytelnionego użytkownika do kontrolera MVC ASP.NET Core. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + Metoda {0} obsługuje żądanie {1} bez przeprowadzania weryfikacji tokenu zabezpieczającego przed fałszerstwem. Należy również upewnić się, że formularz HTML wysyła token zabezpieczający przed fałszerstwem. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Użyj atrybutu DefaultDllImportSearchPaths dla elementów P/Invoke 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. - 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. + Domyślnie elementy P/Invoke korzystające z atrybutu DllImportAttribute sondują określoną liczbę katalogów, w tym bieżący katalog roboczy biblioteki do załadowania. Może to stanowić problem z zabezpieczeniami dla pewnych aplikacji i prowadzić do przejęcia biblioteki DLL. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + Metoda {0} nie korzystała z atrybutu DefaultDllImportSearchPaths dla elementów P/Invoke. @@ -1029,7 +1029,7 @@ 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. - Metoda „{0}” jest niezabezpieczona podczas deserializacji niezaufanych danych za pomocą klasy JavaScriptSerializer zainicjowanej z klasą SimpleTypeResolver. Upewnij się, że klasa JavaScriptSerializer jest inicjowana bez określonej klasy JavaScriptTypeResolver lub inicjowana z klasą JavaScriptTypeResolver, która ogranicza te typy obiektów na wykresie obiektu po deserializacji. + Metoda „{0}” jest niezabezpieczona podczas deserializacji niezaufanych danych za pomocą klasy JavaScriptSerializer zainicjowanej z klasą SimpleTypeResolver. Upewnij się, że klasa JavaScriptSerializer jest inicjowana bez określonej klasy JavaScriptTypeResolver lub inicjowana z klasą JavaScriptTypeResolver, która ogranicza typy obiektów na wykresie obiektu po deserializacji. @@ -1039,7 +1039,7 @@ 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. - Metoda „{0}” jest niezabezpieczona podczas deserializacji niezaufanych danych za pomocą klasy JavaScriptSerializer zainicjowanej z klasą SimpleTypeResolver. Zainicjuj klasę JavaScriptSerializer bez określonej klasy JavaScriptTypeResolver lub zainicjuj ją z klasą JavaScriptTypeResolver, która ogranicza te typy obiektów na wykresie obiektu po deserializacji. + Metoda „{0}” jest niezabezpieczona podczas deserializacji niezaufanych danych za pomocą klasy JavaScriptSerializer zainicjowanej z klasą SimpleTypeResolver. Zainicjuj klasę JavaScriptSerializer bez określonej klasy JavaScriptTypeResolver lub zainicjuj ją z klasą JavaScriptTypeResolver, która ogranicza typy obiektów na wykresie obiektu po deserializacji. @@ -1049,37 +1049,37 @@ 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. - 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. + Podczas deserializacji niezaufanych danych wejściowych zezwolenie na deserializację dowolnych typów jest mało bezpieczne. W przypadku korzystania z klasy JsonSerializerSettings użyj wartości TypeNameHandling.None lub, w przypadku wartości innych niż None, użyj elementu SerializationBinder w celu ograniczenia typów deserializowanych. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Nie używaj niezabezpieczonej klasy JsonSerializerSettings 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. - 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. + Podczas deserializacji niezaufanych danych wejściowych zezwolenie na deserializację dowolnych typów jest niezabezpieczone. W przypadku korzystania z klasy JsonSerializerSettings upewnij się, że określono wartość TypeNameHandling.None lub, w przypadku wartości innych niż None, upewnij się, że określono element SerializationBinder, aby ograniczyć typy deserializowane. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Upewnij się, że klasa JsonSerializerSettings jest zabezpieczona 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. - 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. + Deserializacja danych JSON, gdy używana jest wartość TypeNameHandling inna niż None, może być niebezpieczna. Jeśli zamiast tego potrzebujesz wykrywać deserializację Json.NET, gdy nie jest określona wartość SerializationBinder, wyłącz regułę CA2326 i włącz reguły CA2327, CA2328, CA2329 i CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + Deserializacja danych JSON, gdy używana jest wartość TypeNameHandling inna niż None, może być niebezpieczna. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + Nie używaj wartości TypeNameHandling innych niż None @@ -1319,7 +1319,7 @@ 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. - Podczas wyodrębniania plików z archiwum i używania ścieżki elementu archiwum sprawdź, czy ścieżka jest bezpieczna. Ścieżka archiwum może być ścieżką względną i może prowadzić do dostępu do systemu plików poza oczekiwaną ścieżką docelową systemu plików, prowadząc do złośliwej zmiany konfiguracji i zdalnego wykonania kodu za pomocą techniki lay-and-wait. + Podczas wyodrębniania plików z archiwum i używania ścieżki elementu archiwum sprawdź, czy ścieżka jest bezpieczna. Ścieżka archiwum może być ścieżką względną i może prowadzić do dostępu do systemu plików poza oczekiwaną ścieżką docelową systemu plików, doprowadzając do złośliwej zmiany konfiguracji i zdalnego wykonania kodu za pomocą techniki „podłóż i zaczekaj”. @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Nie koduj na stałe klucza szyfrowania SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + Właściwość .Key elementu SymmetricAlgorithm lub parametr rgbKey metody nigdy nie powinny być wartością zakodowaną na stałe. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Znaleziono potencjalną lukę w zabezpieczeniach, gdzie element „{0}” w metodzie „{1}” może zostać zanieczyszczony zakodowanym na stałe kluczem z elementu „{2}” w metodzie „{3}”. diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf index fc77cd9eea..d296a2caff 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Versões de protocolo mais antigas do TLS (protocolo TLS) são menos seguras do que TLS 1.2 e TLS 1.3, e a probabilidade de que tenham novas vulnerabilidades é maior. Evite versões de protocolo mais antigas para minimizar o risco. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + A versão do protocolo TLS '{0}' foi preterida. Use 'None' para permitir que o Sistema Operacional escolha uma versão. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Não usar valores de SslProtocols preteridos @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Não usar aleatoriedade não segura {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} é um gerador de números aleatórios inseguro. Usar geradores de números aleatórios criptograficamente seguros quando a aleatoriedade for necessária para segurança Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + O uso de um gerador de números pseudoaleatórios criptograficamente fraco pode permitir que um invasor preveja qual valor de segurança confidencial será gerado. Use um gerador de números aleatórios criptograficamente forte se for necessário um valor imprevisível ou garanta que os números pseudoaleatórios fracos não sejam usados de uma maneira sensível à segurança. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Não usar valor DllImportSearchPath não seguro 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. - 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. + Pode haver uma DLL mal-intencionada nos diretórios de pesquisa de DLL padrão. Ou, dependendo do local de onde o seu aplicativo é executado, pode haver uma DLL mal-intencionada no diretório do aplicativo. Em vez disso, use um valor de DllImportSearchPath que especifique um caminho de pesquisa explícito. Os sinalizadores DllImportSearchPath pelos quais esta regra procura podem ser configurados em .editorconfig. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Uso de valor DllImportSearchPath não seguro {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + As versões atuais do protocolo TLS poderão ser preteridas se forem localizadas vulnerabilidades. Evite codificar valores de SslProtocols para manter o seu aplicativo seguro. Use 'None' para permitir que o Sistema Operacional escolha uma versão. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Evite codificar SslProtocols '{0}' para garantir que o seu aplicativo permaneça seguro no futuro. Use 'None' para permitir que o Sistema Operacional escolha uma versão. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Evitar valores SslProtocols codificados 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. - 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. + Ao desserializar uma entrada não confiável, não é seguro permitir que tipos arbitrários sejam desserializados. Ao usar a desserialização por JsonSerializer, use TypeNameHandling.None ou, para valores diferentes de None, restrinja os tipos desserializados com um SerializationBinder. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + Não desserializar com JsonSerializer usando uma configuração insegura 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. - 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. + Ao desserializar uma entrada não confiável, não é seguro permitir que tipos arbitrários sejam desserializados. Ao usar a desserialização por JsonSerializer, use TypeNameHandling.None ou, para valores diferentes de None, restrinja os tipos desserializados com um SerializationBinder. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Verificar se JsonSerializer tem uma configuração segura durante a desserialização + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Atributo HttpVerb ignorado para métodos de ação All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Todos os métodos que criam, editam, excluem ou modificam de qualquer forma os dados fazem isso na sobrecarga [HttpPost] do método, que precisa ser protegida com o atributo antifalsificação contra a falsificação de solicitações. A execução de uma operação GET deve ser uma operação segura que não tenha efeitos colaterais e não modifique os seus dados persistentes. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + O método de ação {0} precisa especificar explicitamente o tipo de solicitação HTTP @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Definir HttpOnly como true para 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. - 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. + Como medida de defesa completa, verifique se os cookies HTTP confidenciais de segurança estão marcados como HttpOnly. Isso indica que os navegadores da Web devem impedir que os scripts acessem os cookies. Scripts mal-intencionados injetados são uma maneira comum de roubar cookies. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie.HttpOnly está definido como false ou não foi definido durante o uso de um HttpCookie. Verifique se os cookies confidenciais de segurança estão marcados como HttpOnly para impedir que scripts mal-intencionados roubem os cookies @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Usar tokens antifalsificação em controladores MVC do ASP.NET Core Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + A manipulação de uma solicitação de POST, PUT, PATCH ou DELETE sem a validação de um token antifalsificação pode ser vulnerável a ataques de falsificação de solicitações intersite. Um ataque de falsificação de solicitações intersite pode enviar solicitações mal-intencionadas de um usuário autenticado para o seu controlador MVC ASP.NET Core. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + O método {0} lida com uma solicitação de {1} sem executar a validação de token antifalsificação. Também é necessário garantir que o seu formulário em HTML envie um token antifalsificação. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Use o atributo DefaultDllImportSearchPaths para P/Invokes 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. - 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. + Por padrão, P/Invokes que usam DllImportAttribute investigam diversos diretórios, incluindo o diretório de trabalho atual, para a biblioteca carregar. Isso pode ser um problema de segurança para determinados aplicativos, levando ao sequestro de DLL. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + O método {0} não usou o atributo DefaultDllImportSearchPaths para P/Invokes. @@ -749,7 +749,7 @@ Dispose methods should call base class dispose - Os métodos Dispose devem chamar o descarte da classe base + Métodos Dispose devem chamar o descarte da classe base @@ -1029,7 +1029,7 @@ 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. - O método '{0}' não é seguro durante a desserialização dos dados não confiáveis com um JavaScriptSerializer inicializado com um SimpleTypeResolver. Verifique se o JavaScriptSerializer é inicializado sem um JavaScriptTypeResolver especificado ou inicializado com um JavaScriptTypeResolver que limita aqueles tipos de objetos no grafo de objeto desserializado. + O método '{0}' não é seguro durante a desserialização de dados não confiáveis com um JavaScriptSerializer inicializado com um SimpleTypeResolver. Verifique se o JavaScriptSerializer é inicializado sem um JavaScriptTypeResolver especificado ou inicializado com um JavaScriptTypeResolver que limita os tipos de objetos no gráfico de objeto desserializado. @@ -1039,7 +1039,7 @@ 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. - O método '{0}' não é seguro durante a desserialização dos dados não confiáveis com um JavaScriptSerializer inicializado com um SimpleTypeResolver. Inicialize o JavaScriptSerializer sem um JavaScriptTypeResolver especificado ou inicialize-o com um JavaScriptTypeResolver que limita aqueles tipos de objetos no grafo de objeto desserializado. + O método '{0}' não é seguro durante a desserialização de dados não confiáveis com um JavaScriptSerializer inicializado com um SimpleTypeResolver. Inicialize o JavaScriptSerializer sem um JavaScriptTypeResolver especificado ou inicialize com um JavaScriptTypeResolver que limita os tipos de objetos no gráfico de objeto desserializado. @@ -1049,37 +1049,37 @@ 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. - 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. + Ao desserializar uma entrada não confiável, não é seguro permitir que tipos arbitrários sejam desserializados. Ao usar JsonSerializerSettings, use TypeNameHandling.None ou, para valores diferentes de None, restrinja os tipos desserializados com um SerializationBinder. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Não use JsonSerializerSettings não seguro 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. - 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. + Ao desserializar uma entrada não confiável, não é seguro permitir que tipos arbitrários sejam desserializados. Ao usar JsonSerializerSettings, verifique se TypeNameHandling.None está especificado ou, para valores diferentes de None, verifique se um SerializationBinder está especificado para restringir tipos desserializados. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Verifique se os JsonSerializerSettings são seguros 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. - 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. + A desserialização do JSON ao usar um valor TypeNameHandling diferente de None pode não ser segura. Se você precisar detectar a desserialização do Json.NET quando um SerializationBinder não for especificado, desabilite a regra CA2326 e habilite as regras CA2327, CA2328, CA2329 e CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + A desserialização do JSON ao usar um valor TypeNameHandling diferente de None pode não ser segura. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + Não use valores TypeNameHandling diferentes de None @@ -1319,7 +1319,7 @@ 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. - Ao extrair arquivos de um arquivo morto e usar o caminho do item de arquivo morto, verifique se o caminho é seguro. O caminho do arquivo morto pode ser relativo e levar ao acesso ao sistema de arquivos fora do caminho de destino do sistema de arquivos esperado, causando alterações maliciosas na configuração e a execução remota de código por meio da técnica de espera passiva. + Ao extrair arquivos de um arquivo morto e usar o caminho do item do arquivo morto, verifique se o caminho é seguro. O caminho do arquivo morto pode ser relativo e levar ao acesso ao sistema de arquivos fora do caminho de destino do sistema de arquivos esperado, causando alterações mal-intencionadas de configuração e execução remota de código por meio da técnica de espera passiva. @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Não Codificar a Chave de Criptografia SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + A propriedade .Key de SymmetricAlgorithm ou o parâmetro rgbKey de um método nunca devem ser um valor codificado. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Foi localizada uma possível vulnerabilidade de segurança na qual '{0}' no método '{1}' pode ter sido afetado pela chave codificada de '{2}' no método '{3}' diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf index c89f49fe4d..2bec0c1223 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Более старые версии протокола TLS менее безопасны, чем TLS 1.2 и TLS 1.3 и скорее всего имеют новые уязвимости. Избегайте использования ранних версий протокола, чтобы минимизировать риски. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + Версия протокола TLS "{0}" является устаревшей. Используйте "None", чтобы операционная система самостоятельно выбрала версию протокола. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Не используйте устаревшие значения параметра SslProtocols @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Не используйте небезопасные генераторы случайных чисел. {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} является небезопасным генератором случайных чисел. Если случайные числа требуются для обеспечения безопасности, используйте криптографически безопасные генераторы случайных чисел. Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + Использование криптографически слабого генератора псевдослучайных чисел может позволить злоумышленнику предсказать, какое значение, чувствительное к безопасности, будет создаваться. Используйте криптографически надежный генератор случайных чисел, если требуется непрогнозируемое значение, или убедитесь, что слабые псевдослучайные числа не используются для обеспечения безопасности. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Не используйте небезопасное значение DllImportSearchPath. 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. - 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. + В каталогах поиска DLL по умолчанию может присутствовать вредоносная библиотека DLL. Или в зависимости от места запуска приложения вредоносная библиотека DLL может присутствовать в каталоге приложения. Вместо этого используйте значение DllImportSearchPath, определяющее путь поиска явным образом. Флаги DllImportSearchPath, поиск которых осуществляет это правило, могут быть настроены в файле EDITORCONFIG. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Использование небезопасного значения DllImportSearchPath {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Текущие версии протокола TLS могут стать нерекомендуемыми при обнаружении уязвимостей. Не следует жестко задавать значения параметра SslProtocols, чтобы в будущем приложение также оставалось безопасным. Используйте значение "None", чтобы операционная система самостоятельно выбрала версию протокола. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Не следует жестко задавать значение параметра SslProtocols "{0}", чтобы в будущем приложение также оставалось безопасным. Используйте значение "None", чтобы операционная система самостоятельно выбрала версию протокола. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Не следует жестко задавать значение параметра SslProtocols 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. - 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. + При десериализации ненадежных входных данных разрешать десериализацию произвольных типов небезопасно. При использовании десериализации JsonSerializer укажите TypeNameHandling.None, а для значений, отличных от None, ограничьте десериализованные типы с помощью SerializationBinder. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + Не выполняйте десериализацию с JsonSerializer при использовании небезопасной конфигурации 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. - 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. + При десериализации ненадежных входных данных разрешать десериализацию произвольных типов небезопасно. При использовании десериализации JsonSerializer укажите TypeNameHandling.None, а для значений, отличных от None, ограничьте десериализованные типы с помощью SerializationBinder. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Убедитесь, что конфигурация JsonSerializer является безопасной при десериализации. + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Отсутствует атрибут HttpVerb для методов действия. All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Все методы, которые создают, изменяют, удаляют или иным образом модифицируют данные, делают это в перегрузке [HttpPost] метода, которую необходимо защитить от подделки запроса с помощью атрибута для защиты от подделки. Выполнение операции GET должно быть безопасным, не должно иметь побочных эффектов и не должно изменять сохраненные данные. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + В методе действия {0} необходимо указать тип HTTP-запроса явным образом. @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + Установите для параметра HttpOnly объекта HttpCookie значение true 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. - 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. + В качестве меры углубленной защиты убедитесь, что файлы cookie HTTP с конфиденциальной информацией о безопасности помечены как HttpOnly. Это означает, что веб-браузеры должны запретить сценариям доступ к файлам cookie. Внедрение вредоносных сценариев является распространенным способом кражи файлов cookie. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie.HttpOnly имеет значение false или значение не задано при использовании HttpCookie. Убедитесь, что файлы cookie с конфиденциальными сведениями безопасности помечены как HttpOnly, чтобы избежать кражи файлов cookie вредоносными сценариями. @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + Используйте маркеры для защиты от подделки в контроллерах MVC ASP.NET Core. Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + Обработка запроса POST, PUT, PATCH или DELETE без проверки маркера для защиты от подделки может стать уязвимой для атак с использованием подделки межсайтовых запросов. Атаки с использованием подделки межсайтовых запросов позволяют отправлять вредоносные запросы от пользователя, прошедшего проверку подлинности, в контроллер MVC ASP.NET Core. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + Метод {0} обрабатывает запрос {1} без проверки маркера для защиты от подделки. Также убедитесь в том, что HTML-форма отправляет маркер для защиты от подделки. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + Используйте атрибут DefaultDllImportSearchPaths для P/Invokes. 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. - 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. + По умолчанию P/Invokes, использующий атрибут DllImportAttribute, проверяет наличие загружаемой библиотеки в нескольких каталогах, включая рабочий каталог. Это может быть проблемой безопасности для некоторых приложений и привести к захвату DLL. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + Метод {0} не использовал атрибут DefaultDllImportSearchPaths для P/Invokes. @@ -1029,7 +1029,7 @@ 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. - Метод "{0}" является небезопасным при десериализации ненадежных данных с помощью JavaScriptSerializer, который был инициализирован с указанием SimpleTypeResolver. Убедитесь, что JavaScriptSerializer был инициализирован без указания JavaScriptTypeResolver или с указанием JavaScriptTypeResolver, который ограничивает типы объектов в десериализованном графе объектов. + Метод "{0}" является небезопасным при десериализации ненадежных данных с помощью JavaScriptSerializer, который был инициализирован с указанием SimpleTypeResolver. Убедитесь, что JavaScriptSerializer был инициализирован без указания JavaScriptTypeResolver или с указанием JavaScriptTypeResolver, который ограничивает типы объектов в десериализованном графе объектов. @@ -1039,7 +1039,7 @@ 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. - Метод "{0}" является небезопасным при десериализации ненадежных данных с помощью JavaScriptSerializer, который был инициализирован с указанием SimpleTypeResolver. Инициализируйте JavaScriptSerializer без указания JavaScriptTypeResolver или с указанием JavaScriptTypeResolver, который ограничивает типы объектов в десериализованном графе объектов. + Метод "{0}" является небезопасным при десериализации ненадежных данных с помощью JavaScriptSerializer, который был инициализирован с указанием SimpleTypeResolver. Инициализируйте JavaScriptSerializer без указания JavaScriptTypeResolver или с указанием JavaScriptTypeResolver, который ограничивает типы объектов в десериализованном графе объектов. @@ -1049,37 +1049,37 @@ 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. - 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. + При десериализации ненадежных входных данных разрешение десериализации произвольных типов является небезопасным. При использовании JsonSerializerSettings укажите TypeNameHandling.None, а для значений, отличных от None, ограничьте десериализованные типы с помощью SerializationBinder. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Не используйте небезопасный JsonSerializerSettings 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. - 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. + При десериализации ненадежных входных данных разрешение десериализации произвольных типов является небезопасным. При использовании JsonSerializerSettings убедитесь, что указан TypeNameHandling.None, а для значений, отличных от None, убедитесь, что указан SerializationBinder для ограничения десериализованных типов. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + Убедитесь, что JsonSerializerSettings безопасны. 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. - 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. + Десериализация JSON при использовании значения TypeNameHandling, отличного от "None", может быть небезопасной. Если необходимо обнаружить десериализацию Json.NET в том случае, если SerializationBinder не указан, отключите правило CA2326 и включите правила CA2327, CA2328, CA2329 и CA2330. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + Десериализация JSON при использовании значения TypeNameHandling, отличного от "None", может быть небезопасной. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + Не используйте значения TypeNameHandling, отличные от "None" @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Не используйте жестко заданный ключ шифрования. SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + Свойство .Key симметричного алгоритма и параметр rgbKey метода не могут быть жестко заданными значениями. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + Обнаружена потенциальная уязвимость безопасности, заключающаяся в том, что "{0}" в методе "{1}" может быть изменен с использованием жестко заданного ключа из "{2}" в методе "{3}". diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf index c0241e6b0d..9eebfc5ae6 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + Aktarım Katmanı Güvenliği'nin (TLS) eski protokol sürümleri TLS 1.2 ve TLS 1.3'ten daha az güvenli olduğundan yeni güvenlik açıkları oluşma olasılığı daha yüksektir. Riski en aza indirmek için eski protokol sürümlerini kullanmaktan kaçının. Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + Aktarım Katmanı Güvenliği protokol sürümü '{0}' kullanımdan kaldırılmış. İşletim Sistemi'nin sürüm seçmesine izin vermek için 'Yok' seçeneğini belirleyin. Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + Kullanımdan kaldırılmış SslProtocols değerlerini kullanma @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + Güvenli olmayan rastgelelik kullanmayın {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0}, güvenli olmayan bir rastgele sayı üreticidir. Güvenlik için rastgelelik gerekli olduğundan şifreli olarak güvenli rastgele sayı üreticileri kullanın Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + Şifreleme açısından zayıf olan bir boş rastgele sayı oluşturucu kullanmak, saldırganın, oluşturulacak güvenlik açısından hassas değeri tahmin etmesine olanak sağlayabilir. Tahmin edilemeyen bir değer gerekiyorsa şifreleme açısından güçlü bir rastgele sayı oluşturucuyu kullanın veya zayıf boş rastgele sayıların güvenlik gerektiren işlemlerde kullanılmadığından emin olun. Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + Güvenli olmayan DllImportSearchPath değeri kullanmayın 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. - 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. + Varsayılan arama dizinlerinde zararlı bir DLL olabilir veya uygulamanızın çalıştığı konuma bağlı olarak uygulama dizininde zararlı bir DLL olabilir. Bunun yerine açık bir arama yolu belirten DllImportSearchPath değeri kullanın. Bu kuralın aradığı DllImportSearchPath bayrakları .editorconfig içinde yapılandırılabilir. Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + Güvenli olmayan DllImportSearchPath değeri {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + Güvenlik açıkları bulunursa, geçerli Aktarım Katmanı Güvenliği protokol sürümleri kullanımdan kaldırılmış olabilir. Uygulamanızın güvenliğini sağlamak için sabit kodlanmış SslProtocols değerleri kullanmaktan kaçının. İşletim Sisteminin bir sürüm seçmesi için 'Yok' seçeneğini belirleyin. Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + Uygulamanızın ileride de güvenli kalmasını sağlamak için sabit kodlanmış SslProtocols '{0}' kullanmaktan kaçının. İşletim Sisteminin bir sürüm seçmesi için 'Yok' seçeneğini belirleyin. Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + Sabit kodlanmış SslProtocols değerlerinden kaçının 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. - 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. + Güvenilmeyen girişler seri durumdan çıkarılırken, rastgele türlerin seri durumdan çıkarılmasına izin vermek güvenli değildir. JsonSerializer seri durumdan çıkarılırken TypeNameHandling.None kullanın veya Hiçbiri dışındaki değerler için, SerializationBinder ile seri durumdan çıkarılan türleri kısıtlayın. Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + Güvenli olmayan yapılandırma kullanarak JsonSerializer ile seri durumdan kaldırmayın 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. - 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. + Güvenilmeyen girişler seri durumdan çıkarılırken, rastgele türlerin seri durumdan çıkarılmasına izin vermek güvenli değildir. JsonSerializer seri durumdan çıkarılırken TypeNameHandling.None kullanın veya Hiçbiri dışındaki değerler için, SerializationBinder ile seri durumdan çıkarılan türleri kısıtlayın. Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + Seri durumdan kaldırırken JsonSerializer'ın güvenli yapılandırmaya sahip olduğundan emin olun + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + Eylem metotları için HttpVerb özniteliği eksik All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + Metodun [HttpPost] aşırı yüklemesinde verileri oluşturan, düzenleyen, silen veya değiştiren tüm metotların, istek sahteciliğine karşı sahteciliğe karşı koruma özniteliği ile korunması gerekir. GET işlemi, yan etki içermeyen ve kalıcı verilerinizi değiştirmeyen güvenli bir işlem olmalıdır. Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + Eylem metodu {0} için HTTP isteği türünün açık olarak belirtilmesi gerekir @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + HttpCookie için HttpOnly'yi true olarak ayarlayın 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. - 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. + Derinlik ölçümü savunması olarak, güvenlik açısından önemli HTTP tanımlama bilgilerinin HttpOnly biçiminde işaretlendiğinden emin olun. Bu, web tarayıcılarının betiklerin tanımlama bilgilerine erişmesini engelleyeceğini belirtir. Eklenmiş kötü amaçlı betikler, tanımlama bilgilerini çalmak için kullanılan yaygın bir yoldur. HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + HttpCookie kullanılırken HttpCookie.HttpOnly false olarak ayarlandı veya hiç ayarlanamadı. Kötü amaçlı betiklerin tanımlama bilgilerini çalmasını engellemek için, güvenlik açısından önemli tanımlama bilgilerinin HttpOnly olarak işaretlendiğinden emin olun @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + ASP.NET Core MVC denetleyicilerinde sahtecilik önleme belirteçleri kullanın Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + POST, PUT, PATCH veya DELETE isteğini sahtecilik önleme belirtecini doğrulamadan işlemek, sizi siteler arası istek sahteciliği saldırılarına karşı savunmasız bırakır. Siteler arası istek sahteciliği saldırısı, kimliği doğrulanmamış kullanıcıdan ASP.NET Core MVC denetleyicinize kötü amaçlı istekler gönderebilir. Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + {0} metodu, {1} isteğini sahtecilik önleme belirtecini doğrulamadan işler. Ayrıca HTML formunuzun sahtecilik önleme belirteci gönderdiğinden emin olmanız gerekir. Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + P/Invokes için DefaultDllImportSearchPaths özniteliğini kullan 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. - 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. + DllImportAttribute kullanan P/Invokesusing varsayılan olarak, yüklenecek kitaplığın geçerli çalışma dizini de dahil olmak üzere birkaç dizini araştırır. Bu, belirli uygulamalar için DLL'nin ele geçirilmesine yol açan bir güvenlik sorunu olabilir. The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + {0} metodu P/Invokes için DefaultDllImportSearchPaths özniteliğini kullanmadı. @@ -749,7 +749,7 @@ Dispose methods should call base class dispose - Dispose metotları Dispose temel sınıfını çağırmalıdır + Atma yöntemleri taban sınıf atmayı çağırmalıdır @@ -1029,7 +1029,7 @@ 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. - '{0}' metodu, SimpleTypeResolver ile başlatılmış bir JavaScriptSerializer ile güvenilmeyen veriler seri durumdan çıkarılırken güvenli değil. JavaScriptSerializer'ın JavaScriptTypeResolver belirtilmeden başlatıldığından veya seri durumdan çıkarılan nesne grafındaki nesne türlerini sınırlayan bir JavaScriptTypeResolver ile başlatıldığından emin olun. + '{0}' metodu, SimpleTypeResolver ile başlatılmış bir JavaScriptSerializer ile güvenilmeyen veriler seri durumdan çıkarılırken güvenli değil. JavaScriptSerializer'ın JavaScriptTypeResolver belirtilmeden başlatıldığından veya seri durumdan çıkarılan nesne grafındaki nesne türlerini sınırlayan bir JavaScriptTypeResolver ile başlatıldığından emin olun. @@ -1039,7 +1039,7 @@ 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. - '{0}' metodu, SimpleTypeResolver ile başlatılmış bir JavaScriptSerializer ile güvenilmeyen veriler seri durumdan çıkarılırken güvenli değil. JavaScriptSerializer'ı JavaScriptTypeResolver belirtilmeden başlatın veya seri durumdan çıkarılan nesne grafındaki nesne türlerini sınırlayan bir JavaScriptTypeResolver ile başlatın. + '{0}' metodu, SimpleTypeResolver ile başlatılmış bir JavaScriptSerializer ile güvenilmeyen veriler seri durumdan çıkarılırken güvenli değil. JavaScriptSerializer'ı JavaScriptTypeResolver belirtilmeden başlatın veya seri durumdan çıkarılan nesne grafındaki nesne türlerini sınırlayan bir JavaScriptTypeResolver ile başlatın. @@ -1049,37 +1049,37 @@ 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. - 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. + Güvenilmeyen girişler seri durumdan kaldırılırken, rastgele türlerin seri durumdan çıkarılmasına izin vermek güvenli değildir. JsonSerializerSettings kullanılırken, TypeNameHandling.None kullanın veya Hiçbiri dışındaki değerler için, SerializationBinder ile seri durumda çıkarılan türleri kısıtlayın. Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + Güvenli olmayan JsonSerializerSettings kullanmayın 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. - 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. + Güvenilmeyen girişler seri durumdan kaldırılırken, rastgele türlerin seri durumdan çıkarılmasına izin vermek güvenli değildir. JsonSerializerSettings kullanılırken, TypeNameHandling.None belirtildiğinden veya Hiçbiri dışındaki değerler için, seri durumda çıkarılan türleri kısıtlamak için SerializationBinder belirtildiğinden emin olun. Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + JsonSerializerSettings'in güvenli olduğundan emin olun 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. - 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. + None dışında bir TypeNameHandling değeri kullanılırken JSON'nin seri durumundan çıkarılması güvenli olmayabilir. SerializationBinder belirtilmediğinde, Json.NET'in seri durumundan çıkarılmasının algılanması gerekiyorsa, CA2326 kuralını devre dışı bırakıp CA2327, CA2328, CA2329 ve CA2330 kurallarını etkinleştirin. Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + None dışında bir TypeNameHandling değeri kullanılırken JSON'nin seri durumundan çıkarılması güvenli olmayabilir. Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + None dışında bir TypeNameHandling değeri kullanmayın @@ -1319,7 +1319,7 @@ 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. - Bir arşivden dosya ayıklarken ve arşiv öğesinin yolunu kullanırken yolun güvenli olup olmadığını denetleyin. Arşiv yolu göreli olabilir ve beklenen dosya sistemi hedef yolunun dışında bir dosya sistemine yönlendirerek düzenleme ve bekleme tekniği aracılığıyla kötü amaçlı değişikliklere ve uzaktan kod yürütmeye yol açabilir. + Bir arşivden dosya ayıklarken ve arşiv öğesinin yolunu kullanırken yolun güvenli olup olmadığını denetleyin. Arşiv yolu göreli olabilir ve beklenen dosya sistemi hedef yolunun dışında bir dosya sistemi erişimine yönlendirebilir. Bu durum, düzenleme ve bekleme tekniği aracılığıyla kötü amaçlı yapılandırma değişikliklerine ve uzaktan kod yürütmeye yol açabilir. @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + Şifreleme Anahtarını Sabit Kodlama SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + SymmetricAlgorithm'in .Key özelliği veya bir metodun rgbKey parametresi hiçbir zaman sabit kodlanmış bir değer olamaz. Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + '{1}' metodundaki '{0}' öğesinin, '{3}' metodundaki '{2}' öğesinde bulunan sabit kodlanmış anahtar nedeniyle zarar görmüş olabileceği olası güvenlik açığı bulundu. @@ -1599,7 +1599,7 @@ {0} created with a weak hash algorithm. Use SHA256, SHA384, or SHA512 to create a strong key from a password - {0} zayıf bir karma algoritmasıyla oluşturuldu. Bir paroladan güçlü bir anahtar oluşturmak için SHA256, SHA384 veya SHA512 kullanın + {0} zayıf bir karma algoritmasıyla oluşturuldu. Paroladan güçlü bir anahtar oluşturmak için SHA256, SHA384 veya SHA512 kullanın diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf index 2d92ca25ab..34382b1ca0 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + 旧协议版本的传输层安全性(TLS)不如 TLS 1.2 和 TLS 1.3 安全,更有可能存在新的漏洞。请避免使用旧协议版本,以将风险降至最低。 Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + 传输层安全协议版本“{0}”已被弃用。请使用“无”,让操作系统选择一个版本。 Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + 请勿使用已弃用的 SslProtocols 值 @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + 请勿使用不安全的随机性 {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} 是不安全的随机数生成器。当需要随机性以确保安全性时,请使用加密的安全随机数生成器 Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + 使用加密的弱伪随机数生成器,攻击者可以预测将生成何种安全敏感值。如果需要不可预测的值,请使用加密的强随机数生成器,或确保不以安全敏感的方式使用弱伪随机数。 Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + 请勿使用不安全的 DllImportSearchPath 值 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. - 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. + 默认 DLL 搜索目录中可能有恶意 DLL。或者,根据应用程序的运行位置,应用程序的目录中可能有恶意 DLL。请改为使用指定显式搜索路径的 DllImportSearchPath 值。可在 .editorconfig 中配置此规则查找的 DllImportSearchPath 标志。 Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + 使用了不安全的 DllImportSearchPath 值 {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + 如果发现漏洞,则当前传输层安全协议版本可能会被弃用。请避免硬编码 SslProtocols 值,以确保应用程序安全。请使用“无”,让操作系统选择一个版本。 Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + 请避免硬编码 SslProtocols“{0}”,以确保应用程序在将来保持安全。请使用“无”,让操作系统选择一个版本。 Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + 避免硬编码的 SslProtocols 值 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. - 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. + 对不信任的输入进行反序列化时,允许反序列化任意类型这一行为是不安全的。使用反序列化 JsonSerializer 时,请使用 TypeNameHandling.None;对于“无”以外的值,请使用 SerializationBinder 限制反序列化的类型。 Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + 请勿使用不安全的配置对 JsonSerializer 进行反序列化 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. - 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. + 对不信任的输入进行反序列化时,允许反序列化任意类型这一行为是不安全的。使用反序列化 JsonSerializer 时,请使用 TypeNameHandling.None;对于“无”以外的值,请使用 SerializationBinder 限制反序列化的类型。 Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + 请确保在反序列化时 JsonSerializer 具有安全配置 + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + 缺少操作方法的 HttpVerb 属性 All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + 创建、编辑、删除或以其他方式修改数据的所有方法都在方法的 [HttpPost] 重载中执行,这需要使用来自请求伪造的防伪造属性来保护。执行 GET 操作应是不具有任何副作用且不会修改永久性数据的安全操作。 Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + 操作方法 {0} 需要显式指定 Http 请求类型 @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + 将 HttpCookie 的 HttpOnly 设置为 true 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. - 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. + 作为深度防御措施,请确保将安全敏感的 HTTP cookie 标记为 HttpOnly。这表示 Web 浏览器应禁止脚本访问 cookie。注入的恶意脚本是窃取 cookie 的常用方法。 HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + 使用 HttpCookie 时,HttpCookie.HttpOnly 被设置为 false 或根本不设置。请确保安全敏感的 cookie 标记为 HttpOnly,以防止恶意脚本窃取 cookie @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + 在 ASP.NET Core MVC 控制器中使用防伪造令牌 Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + 在未验证防伪造令牌的情况下处理 POST、PUT、PATCH 或 DELETE 请求可能易受跨站点请求伪造攻击。跨站点请求伪造攻击可将来自已通过身份验证的用户的恶意请求发送到 ASP.NET Core MVC 控制器。 Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + 方法 {0} 在不执行防伪造令牌验证的情况下处理 {1} 请求。你还需要确保 HTML 窗体发送防伪造令牌。 Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + 对 P/Invoke 使用 DefaultDllImportSearchPaths 属性 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. - 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. + 默认情况下,使用 DllImportAttribute 探测的 P/Invoke 包含许多目录,包括要加载的库的当前工作目录。对于某些应用程序,这可能是一个安全问题,它会导致 DLL 劫持。 The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + 方法 {0} 未对 P/Invoke 使用 DefaultDllImportSearchPaths 属性。 @@ -589,7 +589,7 @@ Higher-frequency periodic activity will keep the CPU busy and interfere with power-saving idle timers that turn off the display and hard disks. - 频率较高的定期活动会使 CPU 处于繁忙状态并且干扰具有节能功能(关闭显示器和硬盘)的空闲计时器。 + 频率较高的定期活动会使 CPU 处于忙状态并且干扰具有节能功能(关闭显示器和硬盘)的空闲计时器。 @@ -1029,7 +1029,7 @@ 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. - 使用通过 SimpleTypeResolver 初始化的 JavaScriptSerializer 反序列化不可信数据时,{0} 方法不安全。请确保初始化 JavaScriptSerializer 但不指定 JavaScriptTypeResolver,或使用限制为反序列化对象图形中的对象类型的 JavaScriptTypeResolver 初始化该对象。 + 使用通过 SimpleTypeResolver 初始化的 JavaScriptSerializer 反序列化不可信数据时,{0} 方法不安全。请确保初始化 JavaScriptSerializer 但不指定 JavaScriptTypeResolver,或使用限制为反序列化对象图形中的对象类型的 JavaScriptTypeResolver 初始化该对象。 @@ -1039,7 +1039,7 @@ 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. - 使用通过 SimpleTypeResolver 初始化的 JavaScriptSerializer 反序列化不可信数据时,{0} 方法不安全。请初始化 JavaScriptSerializer 但不指定 JavaScriptTypeResolver,或使用限制为反序列化对象图形中的对象类型的 JavaScriptTypeResolver 初始化该对象。 + 使用通过 SimpleTypeResolver 初始化的 JavaScriptSerializer 反序列化不可信数据时,{0} 方法不安全。请初始化 JavaScriptSerializer 但不指定 JavaScriptTypeResolver,或使用限制为反序列化对象图形中的对象类型的 JavaScriptTypeResolver 初始化该对象。 @@ -1049,37 +1049,37 @@ 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. - 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. + 对不信任的输入进行反序列化时,允许反序列化任意类型这一行为是不安全的。使用 JsonSerializerSettings 时,请使用 TypeNameHandling.None;对于不是“无”的值,请使用 SerializationBinder 限制反序列化的类型。 Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + 请勿使用不安全的 JsonSerializerSettings 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. - 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. + 对不信任的输入进行反序列化时,允许反序列化任意类型这一行为是不安全的。使用 JsonSerializerSettings 时,请确保已指定 TypeNameHandling.None;对于不是“无”的值,请确保指定了 SerializationBinder 来限制反序列化的类型。 Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + 请确保 JsonSerializerSetting 是安全的 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. - 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. + 使用“无”以外的 TypeNameHandling 值时,进行 JSON 反序列化可能不安全。如需在未指定 SerializationBinder 时检测 Json.NET 反序列化,请禁用规则 CA2326 并启用规则 CA2327、CA2328、CA2329 和 CA2330。 Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + 使用“无”以外的 TypeNameHandling 值时,进行 JSON 反序列化可能不安全。 Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + 请勿使用“无”以外的 TypeNameHandling 值 @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + 请勿硬编码加密密钥 SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + SymmetricAlgorithm 的 .Key 属性或方法的 rgbKey 参数永远都不得是硬编码值。 Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + 找到了潜在安全漏洞,其中方法“{1}”中的“{0}”可能会受到方法“{3}”中“{2}”的硬编码密钥污染。 diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf index b17bba6a7d..30f02ac6cc 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf @@ -4,17 +4,17 @@ Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. - Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. + 較舊的通訊協定版本的傳輸層安全性 (TLS) 比 TLS 1.2 和 TLS 1.3 不安全,而且更可能有新的弱點。請避免較舊的通訊協定版本,以將風險降至最低。 Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. - Transport Layer Security protocol version '{0}' is deprecated. Use 'None' to let the Operating System choose a version. + 傳輸層安全性通訊協定版本 '{0}' 已淘汰。請使用 'None' 讓作業系統選擇版本。 Do not use deprecated SslProtocols values - Do not use deprecated SslProtocols values + 不要使用已淘汰的 SslProtocols 值 @@ -64,92 +64,92 @@ Do not use insecure randomness - Do not use insecure randomness + 不要使用不安全的隨機性 {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security - {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security + {0} 是不安全的亂數產生器。當安全性需要隨機性時,使用密碼編譯亂數產生器 Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. - Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security sensitive manner. + 使用密碼編譯弱式虛擬亂數產生器,可能會讓攻擊者預測產生的安全性敏感性值。請在需要無法預測的值,或是要確保非以安全性敏感性方式使用弱式虛擬亂數時,使用密碼編譯強式亂數產生器。 Do not use unsafe DllImportSearchPath value - Do not use unsafe DllImportSearchPath value + 不要使用不安全的 DllImportSearchPath 值 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. - 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. + 預設 DLL 搜尋目錄中可能有惡意的 DLL。或者,視應用程式的執行位置而定,應用程式的目錄中可能有惡意的 DLL。請改用指定明確搜尋路徑的 DllImportSearchPath 值。此規則尋找的 DllImportSearchPath 旗標可在 .editorconfig 中設定。 Use of unsafe DllImportSearchPath value {0} - Use of unsafe DllImportSearchPath value {0} + 使用不安全的 DllImportSearchPath 值 {0} Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. - Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. + 若發現弱點,則目前的傳輸層安全性通訊協定版本可能會受到淘汰。請避免硬式編碼 SslProtocols 值來確保應用程式安全。請使用 'None' 讓作業系統選擇版本。 Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. - Avoid hardcoding SslProtocols '{0}' to ensure your application remains secure in the future. Use 'None' to let the Operating System choose a version. + 請避免硬式編碼 SslProtocols '{0}',以確保應用程式在未來的安全性。請使用 'None' 讓作業系統選擇版本。 Avoid hardcoded SslProtocols values - Avoid hardcoded SslProtocols values + 避免硬式編碼 SslProtocols 值 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. - 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. + 將不信任的輸入還原序列化時,允許將任意類型還原序列化是不安全的。當使用還原序列化 JsonSerializer 時,請使用 TypeNameHandling.None,或對 None 以外的值使用 SerializationBinder 來限制還原序列化類型。 Do not deserialize with JsonSerializer using an insecure configuration - Do not deserialize with JsonSerializer using an insecure configuration + 不要使用不安全的組態以 JsonSerializer 還原序列化 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. - 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. + 將不信任的輸入還原序列化時,允許將任意類型還原序列化是不安全的。當使用還原序列化 JsonSerializer 時,請使用 TypeNameHandling.None,或對 None 以外的值使用 SerializationBinder 來限制還原序列化類型。 Ensure that JsonSerializer has a secure configuration when deserializing - Ensure that JsonSerializer has a secure configuration when deserializing + 還原序列化時,請確認 JsonSerializer 有安全的組態 + + + + Ensure HttpClient certificate revocation list check is not disabled + Ensure HttpClient certificate revocation list check is not disabled + + + + HttpClient may be created without enabling CheckCertificateRevocationList + HttpClient may be created without enabling CheckCertificateRevocationList Miss HttpVerb attribute for action methods - Miss HttpVerb attribute for action methods + 缺少動作方法的 HttpVerb 屬性 All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. - All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. + 建立、編輯、刪除或修改資料的所有方法,都會在方法的 [HttpPost] 多載中進行,其需要由反偽造屬性保護免受偽造要求侵害。執行 GET 作業是安全的操作,沒有任何副作用且不會修改保存的資料。 Action method {0} needs to specify the Http request kind explictly - Action method {0} needs to specify the Http request kind explictly - - - - Ensure HttpClient certificate revocation list check is not disabled - Ensure HttpClient certificate revocation list check is not disabled - - - - HttpClient may be created without enabling CheckCertificateRevocationList - HttpClient may be created without enabling CheckCertificateRevocationList + 動作方法 {0} 必須明確指定 Http 要求類型 @@ -224,17 +224,17 @@ Set HttpOnly to true for HttpCookie - Set HttpOnly to true for HttpCookie + 針對 HttpCookie 將 HttpOnly 設為 true 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. - 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. + 請確保安全性敏感性 HTTP Cookie 已標記為 HttpOnly,以防止全面性的測量。這代表 Web 瀏覽器應禁止指令碼存取 Cookie。插入的惡意指令碼是竊取 Cookie 的常見方式。 HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies - HttpCookie.HttpOnly is set to false or not set at all when using an HttpCookie. Ensure security sensitive cookies are marked as HttpOnly to prevent malicious scripts from stealing the cookies + 使用 HttpCookie 時,HttpCookie.HttpOnly 設為 false 或完全未設定。請確保安全性敏感性 Cookie 已標記為 HttpOnly,以避免惡意指令碼竊取 Cookie。 @@ -269,32 +269,32 @@ Use antiforgery tokens in ASP.NET Core MVC controllers - Use antiforgery tokens in ASP.NET Core MVC controllers + 使用 ASP.NET Core MVC 控制器中的 antiforgery 權杖 Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. - Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. + 在不驗證 antiforgery 權杖的情況下處理 POST、PUT、PATCH 或 DELETE 要求,可能會容易受到跨站台偽造要求攻擊。跨站台偽造要求攻擊可將惡意要求從已驗證的使用者傳送到 ASP.NET Core MVC 控制器。 Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. - Method {0} handles a {1} request without performing antiforgery token validation. You also need to ensure that your HTML form sends an antiforgery token. + 方法 {0} 會在不驗證 antiforgery 權杖的情況下處理 {1} 要求。您也必須確保 HTML 表單傳送 antiforgery 權杖。 Use DefaultDllImportSearchPaths attribute for P/Invokes - Use DefaultDllImportSearchPaths attribute for P/Invokes + 針對 P/Invoke 使用 DefaultDllImportSearchPaths 屬性 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. - 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. + 根據預設,使用 DllImportAttribute 的 P/Invoke 會探查許多目錄,包括目前正在運作的目錄以供程式庫載入。這可能成為部分應用程式的安全性問題,導致 DLL 劫持。 The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. - The method {0} didn't use DefaultDllImportSearchPaths attribute for P/Invokes. + 方法 {0} 未針對 P/Invoke 使用 DefaultDllImportSearchPaths 屬性。 @@ -1004,12 +1004,12 @@ 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. - 還原序列化不受信任的資料時,方法 '{0}' 不安全。如果您需要改為偵測 BinaryFormatter 還原序列化,而不想要設定 SerializationBinder,則請停用規則 CA2300,並啟用規則 CA2301 和 CA2302。 + 將不受信任的資料還原序列化時,方法 '{0}' 不安全。如果您需要改為偵測 BinaryFormatter 還原序列化,而不想要設定 SerializationBinder,則請停用規則 CA2300,並啟用規則 CA2301 和 CA2302。 The method '{0}' is insecure when deserializing untrusted data. - 還原序列化不受信任的資料時,方法 '{0}' 不安全。 + 將不受信任的資料還原序列化時,方法 '{0}' 不安全。 @@ -1029,7 +1029,7 @@ 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. - 若使用以 SimpleTypeResolver 初始化的 JavaScriptSerializer 來將未受信任的資料還原序列化,方法 '{0}' 會不安全。請確認 JavaScriptSerializer 在初始化時未指定 JavaScriptTypeResolver,或使用在還原序列化物件圖形中限制該物件類型的 JavaScriptTypeResolver。 + 若使用以 SimpleTypeResolver 初始化的 JavaScriptSerializer 來將未受信任的資料還原序列化,方法 '{0}' 會不安全。請確認 JavaScriptSerializer 在初始化時未指定 JavaScriptTypeResolver,或使用在還原序列化物件圖形中限制該物件類型的 JavaScriptTypeResolver。 @@ -1039,7 +1039,7 @@ 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. - 若使用以 SimpleTypeResolver 初始化的 JavaScriptSerializer 來將未受信任的資料還原序列化,方法 '{0}' 會不安全。請在未指定 JavaScriptTypeResolver 的情況下將 JavaScriptSerializer 初始化,或以在還原序列化物件圖形中限制該物件類型的 JavaScriptTypeResolver 初始化。 + 若使用以 SimpleTypeResolver 初始化的 JavaScriptSerializer 來將未受信任的資料還原序列化,方法 '{0}' 會不安全。請在未指定 JavaScriptTypeResolver 的情況下將 JavaScriptSerializer 初始化,或以在還原序列化物件圖形中限制該物件類型的 JavaScriptTypeResolver 初始化。 @@ -1049,42 +1049,42 @@ 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. - 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. + 將不信任的輸入還原序列化時,允許將任意類型還原序列化是不安全的。當使用 JsonSerializerSettings 時,請使用 TypeNameHandling.None,或對 None 以外的值使用 SerializationBinder 來限制還原序列化類型。 Do not use insecure JsonSerializerSettings - Do not use insecure JsonSerializerSettings + 請勿使用不安全的 JsonSerializerSettings 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. - 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. + 將不信任的輸入還原序列化時,允許將任意類型還原序列化是不安全的。當使用 JsonSerializerSettings 時,請確保指定 TypeNameHandling.None,或對 None 以外的值確保指定 SerializationBinder 來限制還原序列化類型。 Ensure that JsonSerializerSettings are secure - Ensure that JsonSerializerSettings are secure + 確保 JsonSerializerSettings 是安全的 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. - 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. + 使用非 None 的 TypeNameHandling 值時,將 JSON 還原序列化可能不安全。若您需要在未指定 SerializationBinder 時,偵測 Json.NET 還原序列化,請停用規則 CA2326,並啟用規則 CA2327、CA2328、CA2329 及 CA2330。 Deserializing JSON when using a TypeNameHandling value other than None can be insecure. - Deserializing JSON when using a TypeNameHandling value other than None can be insecure. + 使用非 None 的 TypeNameHandling 值時,將 JSON 還原序列化可能不安全。 Do not use TypeNameHandling values other than None - Do not use TypeNameHandling values other than None + 請勿使用非 None 的 TypeNameHandling 值 The method '{0}' is insecure when deserializing untrusted data. - 還原序列化不受信任的資料時,方法 '{0}' 不安全。 + 將不受信任的資料還原序列化時,方法 '{0}' 不安全。 @@ -1114,12 +1114,12 @@ 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. - 還原序列化不受信任的資料時,方法 '{0}' 不安全。如果您需要改為偵測 NetDataContractSerializer 還原序列化,而不想要設定 SerializationBinder,則請停用規則 CA2310,並啟用規則 CA2311 和 CA2312。 + 將不受信任的資料還原序列化時,方法 '{0}' 不安全。如果您需要改為偵測 NetDataContractSerializer 還原序列化,而不想要設定 SerializationBinder,則請停用規則 CA2310,並啟用規則 CA2311 和 CA2312。 The method '{0}' is insecure when deserializing untrusted data. - 還原序列化不受信任的資料時,方法 '{0}' 不安全。 + 將不受信任的資料還原序列化時,方法 '{0}' 不安全。 @@ -1129,7 +1129,7 @@ The method '{0}' is insecure when deserializing untrusted data. - 還原序列化不受信任的資料時,方法 '{0}' 不安全。 + 將不受信任的資料還原序列化時,方法 '{0}' 不安全。 @@ -1429,17 +1429,17 @@ Do Not Hard Code Encryption Key - Do Not Hard Code Encryption Key + 不要硬式編碼加密金鑰 SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. - SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. + SymmetricAlgorithm 的 .Key 屬性,或方法的 rgbKey 參數不應為硬式編碼值。 Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' - Potential security vulnerability was found where '{0}' in method '{1}' may be tainted by hardcoded key from '{2}' in method '{3}' + 發現潛在的安全性弱點,方法 '{1}' 中的 '{0}' 可能受來自方法 '{3}' 中 '{2}' 由硬式編碼的金鑰所感染。 diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index 2a423ea253..3f9db3e2e9 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -63,7 +63,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 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. | +63 | [CA3061](https://docs.microsoft.com/visualstudio/code-quality/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). | @@ -71,25 +71,25 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 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. | +71 | [CA5363](https://docs.microsoft.com/visualstudio/code-quality/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. | +77 | [CA5369](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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. | +88 | [CA5380](https://docs.microsoft.com/visualstudio/code-quality/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](https://docs.microsoft.com/visualstudio/code-quality/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. | @@ -97,7 +97,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 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 | False | 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 | [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | 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 | False | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | 99 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | 100 | CA5392 | 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. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index 42a27ec48e..5587bf239f 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -1015,6 +1015,7 @@ "shortDescription": "Do Not Add Schema By URL", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca3061", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1163,6 +1164,7 @@ "shortDescription": "Do Not Disable Request Validation", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5363", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1272,6 +1274,7 @@ "shortDescription": "Use XmlReader For Deserialize", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5369", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1290,6 +1293,7 @@ "shortDescription": "Use XmlReader For Validating Reader", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5370", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1308,6 +1312,7 @@ "shortDescription": "Use XmlReader For Schema Read", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5371", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1326,6 +1331,7 @@ "shortDescription": "Use XmlReader For XPathDocument", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5372", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1344,6 +1350,7 @@ "shortDescription": "Do not use obsolete key derivation function", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5373", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1474,6 +1481,7 @@ "shortDescription": "Do Not Add Certificates To Root Store", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5380", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1493,6 +1501,7 @@ "shortDescription": "Ensure Certificates Are Not Added To Root Store", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5381", "properties": { "category": "Security", "isEnabledByDefault": true, @@ -1643,6 +1652,7 @@ "shortDescription": "Do Not Add Archive Item's Path To The Target File System Path", "fullDescription": "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.", "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca5389", "properties": { "category": "Security", "isEnabledByDefault": false, diff --git a/src/Microsoft.NetCore.Analyzers/Setup/source.extension.vsixmanifest b/src/Microsoft.NetCore.Analyzers/Setup/source.extension.vsixmanifest index 6a27987764..29a369af9e 100644 --- a/src/Microsoft.NetCore.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/Microsoft.NetCore.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Microsoft.NetCore Analyzers Analyzers for .NetCore APIs. + EULA.rtf diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs index ade2943bd3..e3f09a4789 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs @@ -198,17 +198,17 @@ public static class {className} public override string GetOperatorCode(BinaryOperatorKind binaryOperatorKind) { - switch (binaryOperatorKind) + return binaryOperatorKind switch { - case BinaryOperatorKind.Add: return "+"; - case BinaryOperatorKind.Equals: return "=="; - case BinaryOperatorKind.GreaterThan: return ">"; - case BinaryOperatorKind.GreaterThanOrEqual: return ">="; - case BinaryOperatorKind.LessThan: return "<"; - case BinaryOperatorKind.LessThanOrEqual: return "<="; - case BinaryOperatorKind.NotEquals: return "!="; - default: throw new ArgumentOutOfRangeException(nameof(binaryOperatorKind), binaryOperatorKind, $"Invalid value: {binaryOperatorKind}"); - } + BinaryOperatorKind.Add => "+", + BinaryOperatorKind.Equals => "==", + BinaryOperatorKind.GreaterThan => ">", + BinaryOperatorKind.GreaterThanOrEqual => ">=", + BinaryOperatorKind.LessThan => "<", + BinaryOperatorKind.LessThanOrEqual => "<=", + BinaryOperatorKind.NotEquals => "!=", + _ => throw new ArgumentOutOfRangeException(nameof(binaryOperatorKind), binaryOperatorKind, $"Invalid value: {binaryOperatorKind}"), + }; } public override string GetPredicateCode() => "_ => true"; @@ -345,17 +345,17 @@ End Namespace public override string GetOperatorCode(BinaryOperatorKind binaryOperatorKind) { - switch (binaryOperatorKind) + return binaryOperatorKind switch { - case BinaryOperatorKind.Add: return "+"; - case BinaryOperatorKind.Equals: return "="; - case BinaryOperatorKind.GreaterThan: return ">"; - case BinaryOperatorKind.GreaterThanOrEqual: return ">="; - case BinaryOperatorKind.LessThan: return "<"; - case BinaryOperatorKind.LessThanOrEqual: return "<="; - case BinaryOperatorKind.NotEquals: return "<>"; - default: throw new ArgumentOutOfRangeException(nameof(binaryOperatorKind), binaryOperatorKind, $"Invalid value: {binaryOperatorKind}"); - } + BinaryOperatorKind.Add => "+", + BinaryOperatorKind.Equals => "=", + BinaryOperatorKind.GreaterThan => ">", + BinaryOperatorKind.GreaterThanOrEqual => ">=", + BinaryOperatorKind.LessThan => "<", + BinaryOperatorKind.LessThanOrEqual => "<=", + BinaryOperatorKind.NotEquals => "<>", + _ => throw new ArgumentOutOfRangeException(nameof(binaryOperatorKind), binaryOperatorKind, $"Invalid value: {binaryOperatorKind}"), + }; } public override string GetPredicateCode() => "Function(x) True"; diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Security/DoNotInstallRootCertTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Security/DoNotInstallRootCertTests.cs index 1f05d92125..a109388ec2 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Security/DoNotInstallRootCertTests.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Security/DoNotInstallRootCertTests.cs @@ -8,6 +8,7 @@ namespace Microsoft.NetCore.Analyzers.Security.UnitTests { + [Trait(Traits.DataflowAnalysis, Traits.Dataflow.PropertySetAnalysis)] public class DoNotInstallRootCertTests : DiagnosticAnalyzerTestBase { [Fact] diff --git a/src/Microsoft.NetFramework.Analyzers/Core/xlf/MicrosoftNetFrameworkAnalyzersResources.pl.xlf b/src/Microsoft.NetFramework.Analyzers/Core/xlf/MicrosoftNetFrameworkAnalyzersResources.pl.xlf index 8ae3f31b59..42e83a5137 100644 --- a/src/Microsoft.NetFramework.Analyzers/Core/xlf/MicrosoftNetFrameworkAnalyzersResources.pl.xlf +++ b/src/Microsoft.NetFramework.Analyzers/Core/xlf/MicrosoftNetFrameworkAnalyzersResources.pl.xlf @@ -54,7 +54,7 @@ A method in a type that inherits from System.EnterpriseServices.ServicedComponent is marked by using System.Web.Services.WebMethodAttribute. Because WebMethodAttribute and a ServicedComponent method have conflicting behavior and requirements for context and transaction flow, the behavior of the method will be incorrect in some scenarios. - Metoda w typie dziedziczącym z elementu System.EnterpriseServices.ServicedComponent jest oznaczona za pomocą elementu System.Web.Services.WebMethodAttribute. Ponieważ metody WebMethodAttribute oraz ServicedComponent mają sprzeczne zachowania i wymagania dotyczące kontekstu i przepływu transakcji, zachowanie metody w niektórych scenariuszach będzie niepoprawne. + Metoda w typie dziedziczącym z elementu System.EnterpriseServices.ServicedComponent jest oznaczona za pomocą elementu System.Web.Services.WebMethodAttribute. Ponieważ metody WebMethodAttribute oraz ServicedComponent mają będące w konflikcie zachowania i wymagania dotyczące kontekstu i przepływu transakcji, zachowanie metody w niektórych scenariuszach będzie niepoprawne. diff --git a/src/Microsoft.NetFramework.Analyzers/Setup/source.extension.vsixmanifest b/src/Microsoft.NetFramework.Analyzers/Setup/source.extension.vsixmanifest index 7ea671af4d..6ca2b55f05 100644 --- a/src/Microsoft.NetFramework.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/Microsoft.NetFramework.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Microsoft.NetFramework Analyzers Analyzers for APIs specific to the full .NetFramework which are not present in .NetCore + EULA.rtf diff --git a/src/PerformanceSensitiveAnalyzers/Setup/source.extension.vsixmanifest b/src/PerformanceSensitiveAnalyzers/Setup/source.extension.vsixmanifest index bfabb136d6..b9615764f5 100644 --- a/src/PerformanceSensitiveAnalyzers/Setup/source.extension.vsixmanifest +++ b/src/PerformanceSensitiveAnalyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ PerformanceSensitive Analyzers PerformanceSensitive Analyzers + EULA.rtf diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.cs.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.cs.xlf index 25b881f026..dfd42c6ed4 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.cs.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.cs.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + Řešení musí obsahovat dva soubory typu AdditionalFiles: PublicAPI.Unshipped.txt a PublicAPI.Shipped.txt. Nejméně jeden z těchto souborů chybí nebo nemá správný typ. One or both of the public API files are missing - One or both of the public API files are missing + Chybí nejméně jeden soubor veřejného rozhraní API diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.de.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.de.xlf index bea87f5f14..5659185474 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.de.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.de.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + Die Projektmappe muss zwei Dateien mit dem Typ "AdditionalFiles" enthalten: "PublicAPI.Unshipped.txt" und "PublicAPI.Shipped.txt". txt. Mindestens eine dieser Dateien fehlt oder weist den falschen Typ auf. One or both of the public API files are missing - One or both of the public API files are missing + Mindestens eine der öffentlichen API-Dateien fehlt. diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.es.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.es.xlf index 8da1702465..40576dd444 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.es.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.es.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + La solución debe contener dos archivos con el tipo "AdditionalFiles": PublicAPI.Unshipped.txt y PublicAPI.Shipped.txt. Al menos uno de estos archivos falta o tiene un tipo incorrecto. One or both of the public API files are missing - One or both of the public API files are missing + Faltan los dos archivos de la API pública o uno de ellos diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.fr.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.fr.xlf index b67edeb9a8..96fa542929 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.fr.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.fr.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + La solution doit contenir deux fichiers ayant le type "AdditionalFiles" : PublicAPI.Unshipped.txt et PublicAPI.Shipped.txt. L'un de ces fichiers est manquant, ou son type est incorrect. One or both of the public API files are missing - One or both of the public API files are missing + Il manque l'un des deux fichiers d'API publiques, ou les deux diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.it.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.it.xlf index c7d950375b..484fae257f 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.it.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.it.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + La soluzione deve contenere due file con il tipo "AdditionalFiles": PublicAPI.unshipped.txt e PublicAPI.shipped.txt. Almeno uno di questi file manca o è di tipo errato. One or both of the public API files are missing - One or both of the public API files are missing + Uno o entrambi i file dell'API pubblica sono mancanti diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ja.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ja.xlf index 4b9278eedd..53a2fea465 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ja.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ja.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + ソリューションには、種類が "AdditionalFiles" の 2 つのファイル (PublicAPI.Unshipped.txt と PublicAPI.Shipped.txt) が含まれている必要があります。これらのファイルのうち少なくとも 1 つが見つからないか、種類が正しくありません。 One or both of the public API files are missing - One or both of the public API files are missing + パブリック API ファイルの 1 つまたは両方が見つからない diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ko.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ko.xlf index 7a4e6b00c6..5f8ac46335 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ko.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ko.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + 솔루션에 "AdditionalFiles": PublicAPI.Unshipped.txt 및 PublicAPI.Shipped.txt 형식의 파일이 두 개 포함되어야 합니다. 이러한 파일 중 하나 이상이 없거나 형식이 잘못되었습니다. One or both of the public API files are missing - One or both of the public API files are missing + 공용 API 파일 중 하나 또는 둘 다 없습니다. diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pl.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pl.xlf index 4af3f230d8..863be26a91 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pl.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pl.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + Rozwiązanie musi zawierać dwa pliki typu „AdditionalFiles”: PublicAPI.Unshipped.txt i PublicAPI.Shipped.txt. Brakuje co najmniej jednego z tych plików lub ma on nieprawidłowy typ. One or both of the public API files are missing - One or both of the public API files are missing + Brakuje co najmniej jednego pliku publicznego interfejsu API diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pt-BR.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pt-BR.xlf index 93925323bd..ead2a81642 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pt-BR.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.pt-BR.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + A solução precisa conter dois arquivos com o tipo "AdditionalFiles": PublicAPI.Unshipped.txt e PublicAPI.Shipped.txt. Pelo menos um desses arquivos está ausente ou tem o tipo errado. One or both of the public API files are missing - One or both of the public API files are missing + Um ou ambos os arquivos de API pública estão ausentes diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ru.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ru.xlf index 41fdf2f28f..fc7d347b98 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ru.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.ru.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + Решение должно содержать два файла с типом "AdditionalFiles": PublicAPI.Unshipped.txt и PublicAPI.Shipped.txt. По меньшей мере один из этих файлов отсутствует или имеет неправильный тип. One or both of the public API files are missing - One or both of the public API files are missing + Отсутствует один или оба файла открытого API diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.tr.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.tr.xlf index 53ff967711..8c3f42c835 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.tr.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.tr.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + Çözüm, "AdditionalFiles" türüne sahip iki dosya içermelidir: PublicAPI.Unshipped.txt ve PublicAPI.Shipped.txt. Bu dosyalardan en az biri eksik veya yanlış türe sahip. One or both of the public API files are missing - One or both of the public API files are missing + Ortak API dosyalarından biri veya her ikisi de eksik diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hans.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hans.xlf index 97d742f33d..ccb65e353b 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hans.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hans.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + 解决方案必须包含两个具有类型 "AdditionalFiles" 的文件(PublicAPI.Unshipped.txt 和 PublicAPI.Shipped.txt)。其中至少有一个文件缺失或类型错误。 One or both of the public API files are missing - One or both of the public API files are missing + 缺少一个或两个公共 API 文件 @@ -99,7 +99,7 @@ Symbol '{0}' is part of the declared API, but is either not public or could not be found - 符号“{0}”是已声明 API 的一部分,但此符号为非公共或无法找到 + 符号“{0}”是已声明 API 的一部分,但此符号不是公共符号或无法找到 diff --git a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hant.xlf b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hant.xlf index b42ea13470..a9e6f24b7c 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hant.xlf +++ b/src/PublicApiAnalyzers/Core/Analyzers/xlf/PublicApiAnalyzerResources.zh-Hant.xlf @@ -69,12 +69,12 @@ The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. - The solution must contain two files with the type "AdditionalFiles": PublicAPI.Unshipped.txt and PublicAPI.Shipped.txt. At least one of these files is missing or has the wrong type. + 解決方案必須包含兩個類型為 "AdditionalFiles" 的檔案: PublicAPI.Unshipped.txt 與 PublicAPI.Shipped.txt。其中至少缺少一個檔案或檔案類型錯誤。 One or both of the public API files are missing - One or both of the public API files are missing + 缺少兩個公用 API 檔案的其中一個或兩者 diff --git a/src/PublicApiAnalyzers/Setup/source.extension.vsixmanifest b/src/PublicApiAnalyzers/Setup/source.extension.vsixmanifest index 3cbe554eb3..e9d7673aed 100644 --- a/src/PublicApiAnalyzers/Setup/source.extension.vsixmanifest +++ b/src/PublicApiAnalyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Public API Analyzers Public API Analyzers + EULA.rtf diff --git a/src/ReleaseNotesUtil/FixerExtensions.cs b/src/ReleaseNotesUtil/FixerExtensions.cs index 519baa2b60..f259708a23 100644 --- a/src/ReleaseNotesUtil/FixerExtensions.cs +++ b/src/ReleaseNotesUtil/FixerExtensions.cs @@ -77,6 +77,31 @@ private static bool HasImplementation(CodeFixProvider fixer) return ilInstructionCount != 177; } + // See if the method body is: + // { + // return Task.CompletedTask; + // } + byte[] methodBodyIL = method?.GetMethodBody()?.GetILAsByteArray(); + if (methodBodyIL != null + && methodBodyIL.Length == 6 + && methodBodyIL[0] == 0x28 // call + && methodBodyIL[5] == 0x2a) // ret + { + if (!BitConverter.IsLittleEndian) + { + Array.Reverse(methodBodyIL, 1, sizeof(Int32)); + } + + int metadataToken = BitConverter.ToInt32(methodBodyIL, 1); + MethodBase calledMethod = method.Module.ResolveMethod(metadataToken); + if (calledMethod != null + && calledMethod.DeclaringType.FullName == "System.Threading.Tasks.Task" + && calledMethod.Name == "get_CompletedTask") + { + return false; + } + } + return true; } } diff --git a/src/ReleaseNotesUtil/Program.cs b/src/ReleaseNotesUtil/Program.cs index 72244b9806..63b96d61ab 100644 --- a/src/ReleaseNotesUtil/Program.cs +++ b/src/ReleaseNotesUtil/Program.cs @@ -49,8 +49,11 @@ private static void PrintUsage() private static void GetRulesJson(string nugetInstalledPackagesPath, string version, string outputPath) { IEnumerable dllPaths = GetFxCopAnalyzerBinaries(nugetInstalledPackagesPath, version); - RuleFileContent ruleFileContent = new RuleFileContent(); - ruleFileContent.Rules = GetRules(dllPaths); + RuleFileContent ruleFileContent = new RuleFileContent + { + Rules = GetRules(dllPaths) + }; + ruleFileContent.Rules.Sort(CategoryThenIdComparer.Instance); WriteRuleFileContent(ruleFileContent, outputPath); } @@ -64,13 +67,13 @@ private static void GetRulesJson(string nugetInstalledPackagesPath, string versi RuleFileContent newContent = ReadRuleFileContent(newRulesJsonPath); // If we have the latest rules, we can backfill missing help link URLs. - if (!String.IsNullOrWhiteSpace(latestRulesJsonPath)) + if (!string.IsNullOrWhiteSpace(latestRulesJsonPath)) { RuleFileContent latestContent = ReadRuleFileContent(latestRulesJsonPath); Dictionary latestRulesById = latestContent.Rules.ToDictionary(r => r.Id); foreach (RuleInfo rule in oldContent.Rules.Concat(newContent.Rules)) { - if (String.IsNullOrWhiteSpace(rule.HelpLink) + if (string.IsNullOrWhiteSpace(rule.HelpLink) && latestRulesById.TryGetValue(rule.Id, out RuleInfo latestRule)) { rule.HelpLink = latestRule.HelpLink; diff --git a/src/Roslyn.Diagnostics.Analyzers/Setup/source.extension.vsixmanifest b/src/Roslyn.Diagnostics.Analyzers/Setup/source.extension.vsixmanifest index cc9e71212b..2553038194 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/Roslyn.Diagnostics.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Roslyn.Diagnostics Analyzers Roslyn.Diagnostics Analyzers + EULA.rtf diff --git a/src/Text.Analyzers/Setup/source.extension.vsixmanifest b/src/Text.Analyzers/Setup/source.extension.vsixmanifest index 455b83205c..5dc90b1a95 100644 --- a/src/Text.Analyzers/Setup/source.extension.vsixmanifest +++ b/src/Text.Analyzers/Setup/source.extension.vsixmanifest @@ -5,6 +5,7 @@ Text Analyzers Text Analyzers + EULA.rtf diff --git a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs index 1762693410..5efce04998 100644 --- a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs +++ b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs @@ -222,17 +222,13 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) "AString", (PointsToAbstractValue pointsToAbstractValue) => { - switch (pointsToAbstractValue.NullState) + return pointsToAbstractValue.NullState switch { - case NullAbstractValue.Null: - return PropertySetAbstractValueKind.Unflagged; - case NullAbstractValue.NotNull: - return PropertySetAbstractValueKind.Flagged; - case NullAbstractValue.MaybeNull: - return PropertySetAbstractValueKind.MaybeFlagged; - default: - return PropertySetAbstractValueKind.Unknown; - } + NullAbstractValue.Null => PropertySetAbstractValueKind.Unflagged, + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Flagged, + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, + _ => PropertySetAbstractValueKind.Unknown, + }; })), new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( // When TypeToTrack.Method() is invoked, need to evaluate its state. @@ -242,15 +238,12 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }), new HazardousUsageEvaluator( // When OtherClass.OtherMethod() is invoked, evaluate its "TypeToTrack t" argument. "OtherClass", @@ -262,15 +255,12 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }), new HazardousUsageEvaluator( // When OtherClass.StaticMethod() is invoked, evaluate its "TypeToTrack staticMethodParameter" argument. "OtherClass", @@ -282,15 +272,12 @@ public static void StaticMethod(TestTypeToTrack staticMethodParameter) // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -415,21 +402,13 @@ void TestMethod() if (method.Parameters.Length >= 2) { // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. - switch (argumentPointsToAbstractValues[2].NullState) + kind = argumentPointsToAbstractValues[2].NullState switch { - case NullAbstractValue.Null: - kind = PropertySetAbstractValueKind.Unflagged; - break; - case NullAbstractValue.NotNull: - kind = PropertySetAbstractValueKind.Flagged; - break; - case NullAbstractValue.MaybeNull: - kind = PropertySetAbstractValueKind.MaybeFlagged; - break; - default: - kind = PropertySetAbstractValueKind.Unknown; - break; - } + NullAbstractValue.Null => PropertySetAbstractValueKind.Unflagged, + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Flagged, + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, + _ => PropertySetAbstractValueKind.Unknown, + }; } return PropertySetAbstractValue.GetInstance(kind); @@ -439,17 +418,13 @@ void TestMethod() "AString", (PointsToAbstractValue pointsToAbstractValue) => { - switch (pointsToAbstractValue.NullState) + return pointsToAbstractValue.NullState switch { - case NullAbstractValue.Null: - return PropertySetAbstractValueKind.Unflagged; - case NullAbstractValue.NotNull: - return PropertySetAbstractValueKind.Flagged; - case NullAbstractValue.MaybeNull: - return PropertySetAbstractValueKind.MaybeFlagged; - default: - return PropertySetAbstractValueKind.Unknown; - } + NullAbstractValue.Null => PropertySetAbstractValueKind.Unflagged, + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Flagged, + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, + _ => PropertySetAbstractValueKind.Unknown, + }; })), new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( @@ -459,15 +434,12 @@ void TestMethod() // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -560,15 +532,12 @@ void TestMethod() // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -635,15 +604,12 @@ void TestMethod() // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -897,15 +863,12 @@ void TestMethod() // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -1003,15 +966,12 @@ void TestMethod() // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -1071,17 +1031,13 @@ TestTypeToTrackWithConstructor GetTestType() "AString", (PointsToAbstractValue pointsToAbstractValue) => { - switch (pointsToAbstractValue.NullState) + return pointsToAbstractValue.NullState switch { - case NullAbstractValue.Null: - return PropertySetAbstractValueKind.Unflagged; - case NullAbstractValue.NotNull: - return PropertySetAbstractValueKind.Flagged; - case NullAbstractValue.MaybeNull: - return PropertySetAbstractValueKind.MaybeFlagged; - default: - return PropertySetAbstractValueKind.Unknown; - } + NullAbstractValue.Null => PropertySetAbstractValueKind.Unflagged, + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Flagged, + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, + _ => PropertySetAbstractValueKind.Unknown, + }; })), new HazardousUsageEvaluatorCollection( new HazardousUsageEvaluator( @@ -1089,15 +1045,12 @@ TestTypeToTrackWithConstructor GetTestType() (PropertySetAbstractValue abstractValue) => { // With only one property being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] @@ -1181,34 +1134,26 @@ object TestMethod() "AString", (PointsToAbstractValue pointsToAbstractValue) => { - switch (pointsToAbstractValue.NullState) + return pointsToAbstractValue.NullState switch { - case NullAbstractValue.Null: - return PropertySetAbstractValueKind.Unflagged; - case NullAbstractValue.NotNull: - return PropertySetAbstractValueKind.Flagged; - case NullAbstractValue.MaybeNull: - return PropertySetAbstractValueKind.MaybeFlagged; - default: - return PropertySetAbstractValueKind.Unknown; - } + NullAbstractValue.Null => PropertySetAbstractValueKind.Unflagged, + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Flagged, + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, + _ => PropertySetAbstractValueKind.Unknown, + }; }, propertyIndex: 0), // Both AString and AnObject point to index 0. new PropertyMapper( // Definitely null => unflagged, definitely non-null => flagged, otherwise => maybe. "AnObject", (PointsToAbstractValue pointsToAbstractValue) => { - switch (pointsToAbstractValue.NullState) + return pointsToAbstractValue.NullState switch { - case NullAbstractValue.Null: - return PropertySetAbstractValueKind.Unflagged; - case NullAbstractValue.NotNull: - return PropertySetAbstractValueKind.Flagged; - case NullAbstractValue.MaybeNull: - return PropertySetAbstractValueKind.MaybeFlagged; - default: - return PropertySetAbstractValueKind.Unknown; - } + NullAbstractValue.Null => PropertySetAbstractValueKind.Unflagged, + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Flagged, + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, + _ => PropertySetAbstractValueKind.Unknown, + }; }, propertyIndex: 0)), // Both AString and AnObject point to index 0. new HazardousUsageEvaluatorCollection( @@ -1219,15 +1164,12 @@ object TestMethod() // When doing this for reals, need to examine the method to make sure we're looking at the right method and arguments. // With only underlying value (from the two "aliased" properties) being tracked, this is straightforward. - switch (abstractValue[0]) + return (abstractValue[0]) switch { - case PropertySetAbstractValueKind.Flagged: - return HazardousUsageEvaluationResult.Flagged; - case PropertySetAbstractValueKind.MaybeFlagged: - return HazardousUsageEvaluationResult.MaybeFlagged; - default: - return HazardousUsageEvaluationResult.Unflagged; - } + PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged, + PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged, + _ => HazardousUsageEvaluationResult.Unflagged, + }; }))); [Fact] diff --git a/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.cs b/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.cs index a88c21b53f..28fba83df8 100644 --- a/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.cs +++ b/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.cs @@ -164,32 +164,24 @@ public static Task ComputeAsync(ISymbol symbol, Compilat internal async static Task ComputeAsync(ISymbol symbol, SemanticModelProvider semanticModelProvider, CancellationToken cancellationToken) { - switch (symbol.Kind) + return symbol.Kind switch { - case SymbolKind.Assembly: - return await AssemblyMetricData.ComputeAsync((IAssemblySymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.Assembly => await AssemblyMetricData.ComputeAsync((IAssemblySymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - case SymbolKind.Namespace: - return await NamespaceMetricData.ComputeAsync((INamespaceSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.Namespace => await NamespaceMetricData.ComputeAsync((INamespaceSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - case SymbolKind.NamedType: - return await NamedTypeMetricData.ComputeAsync((INamedTypeSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.NamedType => await NamedTypeMetricData.ComputeAsync((INamedTypeSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - case SymbolKind.Method: - return await MethodMetricData.ComputeAsync((IMethodSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.Method => await MethodMetricData.ComputeAsync((IMethodSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - case SymbolKind.Property: - return await PropertyMetricData.ComputeAsync((IPropertySymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.Property => await PropertyMetricData.ComputeAsync((IPropertySymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - case SymbolKind.Field: - return await FieldMetricData.ComputeAsync((IFieldSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.Field => await FieldMetricData.ComputeAsync((IFieldSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - case SymbolKind.Event: - return await EventMetricData.ComputeAsync((IEventSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false); + SymbolKind.Event => await EventMetricData.ComputeAsync((IEventSymbol)symbol, semanticModelProvider, cancellationToken).ConfigureAwait(false), - default: - throw new NotSupportedException(); - } + _ => throw new NotSupportedException(), + }; } internal static async Task> ComputeAsync(IEnumerable children, SemanticModelProvider semanticModelProvider, CancellationToken cancellationToken) diff --git a/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs b/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs index bdf905e246..e9b13ff950 100644 --- a/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs +++ b/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs @@ -305,15 +305,12 @@ internal static void RemoveContainingTypes(ISymbol symbol, ImmutableHashSet GetParameters(this ISymbol member) { - switch (member.Kind) + return member.Kind switch { - case SymbolKind.Method: - return ((IMethodSymbol)member).Parameters; - case SymbolKind.Property: - return ((IPropertySymbol)member).Parameters; - default: - return ImmutableArray.Empty; - } + SymbolKind.Method => ((IMethodSymbol)member).Parameters, + SymbolKind.Property => ((IPropertySymbol)member).Parameters, + _ => ImmutableArray.Empty, + }; } } } diff --git a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs index c875b216f5..5e9f1e7ade 100644 --- a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs +++ b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs @@ -532,32 +532,21 @@ public static bool IsWithinLambdaOrLocalFunction(this IOperation operation) public static ITypeSymbol GetPatternType(this IPatternOperation pattern) { - switch (pattern) + return pattern switch { - case IDeclarationPatternOperation declarationPattern: - switch (declarationPattern.DeclaredSymbol) - { - case ILocalSymbol local: - return local.Type; + IDeclarationPatternOperation declarationPattern => declarationPattern.DeclaredSymbol switch + { + ILocalSymbol local => local.Type, - case IDiscardSymbol discard: - return discard.Type; + IDiscardSymbol discard => discard.Type, - default: - // TODO use the new IOperation API 'IDeclarationPatternOperation.MatchedType' when we move the repo - // to use Microsoft.CodeAnalysis 3.0 or greater. - return null; - } + _ => null, + }, - case IConstantPatternOperation constantPattern: - return constantPattern.Value.Type; + IConstantPatternOperation constantPattern => constantPattern.Value.Type, - default: - // Below assert fires for IDiscardPatternOperation. - // https://github.com/dotnet/roslyn-analyzers/issues/2185 tracks enabling this assert. - //Debug.Fail($"Unhandled pattern kind '{pattern.Kind}'"); - return null; - } + _ => null, + }; } /// @@ -612,26 +601,20 @@ public static SyntaxNode GetInstance(this IInvocationOperation invocationOperati public static ISymbol GetReferencedMemberOrLocalOrParameter(this IOperation operation) { - switch (operation) + return operation switch { - case IMemberReferenceOperation memberReference: - return memberReference.Member; + IMemberReferenceOperation memberReference => memberReference.Member, - case IParameterReferenceOperation parameterReference: - return parameterReference.Parameter; + IParameterReferenceOperation parameterReference => parameterReference.Parameter, - case ILocalReferenceOperation localReference: - return localReference.Local; + ILocalReferenceOperation localReference => localReference.Local, - case IParenthesizedOperation parenthesized: - return parenthesized.Operand.GetReferencedMemberOrLocalOrParameter(); + IParenthesizedOperation parenthesized => parenthesized.Operand.GetReferencedMemberOrLocalOrParameter(), - case IConversionOperation conversion: - return conversion.Operand.GetReferencedMemberOrLocalOrParameter(); + IConversionOperation conversion => conversion.Operand.GetReferencedMemberOrLocalOrParameter(), - default: - return null; - } + _ => null, + }; } /// diff --git a/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs b/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs index 7a048c8979..482b8c7387 100644 --- a/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs +++ b/src/Utilities/Compiler/Extensions/ISymbolExtensions.cs @@ -555,20 +555,16 @@ public static ISymbol GetOverriddenMember(this ISymbol symbol) Debug.Assert(symbol != null); Debug.Assert(symbol.IsOverride); - switch (symbol) + return symbol switch { - case IMethodSymbol methodSymbol: - return methodSymbol.OverriddenMethod; + IMethodSymbol methodSymbol => methodSymbol.OverriddenMethod, - case IPropertySymbol propertySymbol: - return propertySymbol.OverriddenProperty; + IPropertySymbol propertySymbol => propertySymbol.OverriddenProperty, - case IEventSymbol eventSymbol: - return eventSymbol.OverriddenEvent; + IEventSymbol eventSymbol => eventSymbol.OverriddenEvent, - default: - throw new NotImplementedException(); - } + _ => throw new NotImplementedException(), + }; } /// @@ -596,53 +592,42 @@ public static bool IsImplementationOfAnyExplicitInterfaceMember(this ISymbol sym public static ITypeSymbol GetMemberOrLocalOrParameterType(this ISymbol symbol) { - switch (symbol.Kind) + return symbol.Kind switch { - case SymbolKind.Local: - return ((ILocalSymbol)symbol).Type; + SymbolKind.Local => ((ILocalSymbol)symbol).Type, - case SymbolKind.Parameter: - return ((IParameterSymbol)symbol).Type; + SymbolKind.Parameter => ((IParameterSymbol)symbol).Type, - default: - return GetMemberType(symbol); - } + _ => GetMemberType(symbol), + }; } public static ITypeSymbol GetMemberType(this ISymbol symbol) { - switch (symbol.Kind) + return symbol.Kind switch { - case SymbolKind.Event: - return ((IEventSymbol)symbol).Type; + SymbolKind.Event => ((IEventSymbol)symbol).Type, - case SymbolKind.Field: - return ((IFieldSymbol)symbol).Type; + SymbolKind.Field => ((IFieldSymbol)symbol).Type, - case SymbolKind.Method: - return ((IMethodSymbol)symbol).ReturnType; + SymbolKind.Method => ((IMethodSymbol)symbol).ReturnType, - case SymbolKind.Property: - return ((IPropertySymbol)symbol).Type; + SymbolKind.Property => ((IPropertySymbol)symbol).Type, - default: - return null; - } + _ => null, + }; } public static bool IsReadOnlyFieldOrProperty(this ISymbol symbol) { - switch (symbol) + return symbol switch { - case IFieldSymbol field: - return field.IsReadOnly; + IFieldSymbol field => field.IsReadOnly, - case IPropertySymbol property: - return property.IsReadOnly; + IPropertySymbol property => property.IsReadOnly, - default: - return false; - } + _ => false, + }; } /// @@ -690,35 +675,29 @@ public static bool IsSymbolWithSpecialDiscardName(this ISymbol symbol) public static bool IsConst(this ISymbol symbol) { - switch (symbol) + return symbol switch { - case IFieldSymbol field: - return field.IsConst; + IFieldSymbol field => field.IsConst, - case ILocalSymbol local: - return local.IsConst; + ILocalSymbol local => local.IsConst, - default: - return false; - } + _ => false, + }; } public static bool IsReadOnly(this ISymbol symbol) { - switch (symbol) + return symbol switch { - case IFieldSymbol field: - return field.IsReadOnly; + IFieldSymbol field => field.IsReadOnly, - case IPropertySymbol property: - return property.IsReadOnly; + IPropertySymbol property => property.IsReadOnly, // TODO: IMethodSymbol and ITypeSymbol also have IsReadOnly in Microsoft.CodeAnalysis 3.x // Add these cases once we move to the required Microsoft.CodeAnalysis.nupkg. - default: - return false; - } + _ => false, + }; } } } diff --git a/src/Utilities/Compiler/Extensions/SymbolVisibility.cs b/src/Utilities/Compiler/Extensions/SymbolVisibility.cs index 66df7d6a9d..c859efc826 100644 --- a/src/Utilities/Compiler/Extensions/SymbolVisibility.cs +++ b/src/Utilities/Compiler/Extensions/SymbolVisibility.cs @@ -26,35 +26,27 @@ internal static class SymbolVisibilityExtensions /// public static bool IsAtLeastAsVisibleAs(this SymbolVisibility typeVisibility, SymbolVisibility comparisonVisibility) { - switch (typeVisibility) + return typeVisibility switch { - case SymbolVisibility.Public: - return true; - case SymbolVisibility.Internal: - return comparisonVisibility != SymbolVisibility.Public; - case SymbolVisibility.Private: - return comparisonVisibility == SymbolVisibility.Private; - default: - throw new ArgumentOutOfRangeException(nameof(typeVisibility), typeVisibility, null); - } + SymbolVisibility.Public => true, + SymbolVisibility.Internal => comparisonVisibility != SymbolVisibility.Public, + SymbolVisibility.Private => comparisonVisibility == SymbolVisibility.Private, + _ => throw new ArgumentOutOfRangeException(nameof(typeVisibility), typeVisibility, null), + }; } public static SymbolVisibilityGroup ToSymbolVisibilityGroup(this SymbolVisibility symbolVisibility) { - switch (symbolVisibility) + return symbolVisibility switch { - case SymbolVisibility.Public: - return SymbolVisibilityGroup.Public; + SymbolVisibility.Public => SymbolVisibilityGroup.Public, - case SymbolVisibility.Internal: - return SymbolVisibilityGroup.Internal; + SymbolVisibility.Internal => SymbolVisibilityGroup.Internal, - case SymbolVisibility.Private: - return SymbolVisibilityGroup.Private; + SymbolVisibility.Private => SymbolVisibilityGroup.Private, - default: - throw new ArgumentOutOfRangeException(nameof(symbolVisibility), symbolVisibility, null); - } + _ => throw new ArgumentOutOfRangeException(nameof(symbolVisibility), symbolVisibility, null), + }; } } } \ No newline at end of file diff --git a/src/Utilities/Compiler/HashUtilities.cs b/src/Utilities/Compiler/HashUtilities.cs index 75a0f04950..7d5c60b7be 100644 --- a/src/Utilities/Compiler/HashUtilities.cs +++ b/src/Utilities/Compiler/HashUtilities.cs @@ -50,7 +50,7 @@ internal static int Combine(ImmutableStack stack, int currentKey) internal static int Combine(ImmutableHashSet set) => Combine(set, 0); internal static int Combine(ImmutableHashSet set, int currentKey) - => Combine(set.Select(element => element.GetHashCode()).Order(), + => Combine(set.Select(element => element?.GetHashCode() ?? 0).Order(), set.Count, currentKey); diff --git a/src/Utilities/Compiler/Options/SymbolVisibilityGroup.cs b/src/Utilities/Compiler/Options/SymbolVisibilityGroup.cs index b3dfbe9288..5903f091c3 100644 --- a/src/Utilities/Compiler/Options/SymbolVisibilityGroup.cs +++ b/src/Utilities/Compiler/Options/SymbolVisibilityGroup.cs @@ -28,20 +28,16 @@ internal static class SymbolVisibilityGroupExtensions { public static bool Contains(this SymbolVisibilityGroup symbolVisibilityGroup, SymbolVisibility symbolVisibility) { - switch (symbolVisibility) + return symbolVisibility switch { - case SymbolVisibility.Public: - return (symbolVisibilityGroup & SymbolVisibilityGroup.Public) != 0; + SymbolVisibility.Public => (symbolVisibilityGroup & SymbolVisibilityGroup.Public) != 0, - case SymbolVisibility.Internal: - return (symbolVisibilityGroup & SymbolVisibilityGroup.Internal) != 0; + SymbolVisibility.Internal => (symbolVisibilityGroup & SymbolVisibilityGroup.Internal) != 0, - case SymbolVisibility.Private: - return (symbolVisibilityGroup & SymbolVisibilityGroup.Private) != 0; + SymbolVisibility.Private => (symbolVisibilityGroup & SymbolVisibilityGroup.Private) != 0, - default: - throw new ArgumentOutOfRangeException(nameof(symbolVisibility), symbolVisibility, null); - } + _ => throw new ArgumentOutOfRangeException(nameof(symbolVisibility), symbolVisibility, null), + }; } } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValue.cs index a60b2f6714..32cacb426c 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValue.cs @@ -7,8 +7,6 @@ using System.Linq; using Analyzer.Utilities; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis { /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs index 4d6007628e..4ab10b9ac9 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs @@ -5,8 +5,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAbstractValue.cs index 8310a30969..4a0a0a2d1f 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAbstractValue.cs @@ -5,8 +5,6 @@ using System.Diagnostics; using Analyzer.Utilities; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis { /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs index 7b62bbb9db..1dfdee42af 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs @@ -384,19 +384,16 @@ bool IsDisposeOwnershipTransfer() return false; } - switch (operation.Parent) + return operation.Parent switch { - case IObjectCreationOperation _: - return DisposeOwnershipTransferAtConstructor || - DisposeOwnershipTransferLikelyTypes.Contains(operation.Parameter.Type); + IObjectCreationOperation _ => DisposeOwnershipTransferAtConstructor || + DisposeOwnershipTransferLikelyTypes.Contains(operation.Parameter.Type), - case IInvocationOperation invocation: - return DisposeOwnershipTransferAtMethodCall || - IsDisposableCreationSpecialCase(invocation.TargetMethod) && DisposeOwnershipTransferLikelyTypes.Contains(operation.Parameter.Type); + IInvocationOperation invocation => DisposeOwnershipTransferAtMethodCall || + IsDisposableCreationSpecialCase(invocation.TargetMethod) && DisposeOwnershipTransferLikelyTypes.Contains(operation.Parameter.Type), - default: - return false; - } + _ => false, + }; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs index 6b53c4adc4..12ea7aef74 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs @@ -9,8 +9,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs index 0876a72593..52074dd3cd 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs @@ -150,19 +150,16 @@ private static bool IsHazardousIfNull(IOperation operation) return false; } - switch (operation.Parent) + return operation.Parent switch { - case IMemberReferenceOperation memberReference: - return memberReference.Instance == operation; + IMemberReferenceOperation memberReference => memberReference.Instance == operation, - case IArrayElementReferenceOperation arrayElementReference: - return arrayElementReference.ArrayReference == operation; + IArrayElementReferenceOperation arrayElementReference => arrayElementReference.ArrayReference == operation, - case IInvocationOperation invocation: - return invocation.Instance == operation; - } + IInvocationOperation invocation => invocation.Instance == operation, - return false; + _ => false, + }; } private void HandlePotentiallyHazardousOperation(IOperation operation, IEnumerable nonValidatedLocations) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs index 47f58350ef..a0a378d865 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs @@ -8,8 +8,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ParameterValidationAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs index 30f2901dcc..d66a8de1ae 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs @@ -6,8 +6,6 @@ using System.Diagnostics; using System.Linq; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis { /// @@ -97,17 +95,14 @@ internal static PointsToAbstractValue Create(ImmutableHashSet } else if (locations.Count > LocationThreshold) { - switch (nullState) + return nullState switch { - case NullAbstractValue.Null: - return UnknownNull; + NullAbstractValue.Null => UnknownNull, - case NullAbstractValue.NotNull: - return UnknownNotNull; + NullAbstractValue.NotNull => UnknownNotNull, - default: - return Unknown; - } + _ => Unknown, + }; } return new PointsToAbstractValue(locations, nullState); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs index f12b6e7c7b..a3e1df3404 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs @@ -227,24 +227,16 @@ private static void ResetAbstractValueIfTracked(AnalysisEntity analysisEntity, P existingValue = defaultPointsToValueGenerator.GetOrCreateDefaultValue(analysisEntity); } - PointsToAbstractValue newPointsToValue; - switch (nullState) + var newPointsToValue = nullState switch { - case NullAbstractValue.Null: - newPointsToValue = existingValue.MakeNull(); - break; + NullAbstractValue.Null => existingValue.MakeNull(), - case NullAbstractValue.NotNull: - newPointsToValue = existingValue.MakeNonNull(); - break; + NullAbstractValue.NotNull => existingValue.MakeNonNull(), - case NullAbstractValue.Invalid: - newPointsToValue = PointsToAbstractValue.Invalid; - break; + NullAbstractValue.Invalid => PointsToAbstractValue.Invalid, - default: - throw new InvalidProgramException(); - } + _ => throw new InvalidProgramException(), + }; targetAnalysisData.SetAbstractValue(analysisEntity, newPointsToValue); AssertValidPointsToAnalysisData(targetAnalysisData); @@ -514,17 +506,14 @@ private static NullAbstractValue NegatePredicateValue(NullAbstractValue value) { Debug.Assert(IsValidValueForPredicateAnalysis(value)); - switch (value) + return value switch { - case NullAbstractValue.Null: - return NullAbstractValue.NotNull; + NullAbstractValue.Null => NullAbstractValue.NotNull, - case NullAbstractValue.NotNull: - return NullAbstractValue.Null; + NullAbstractValue.NotNull => NullAbstractValue.Null, - default: - throw new InvalidProgramException(); - } + _ => throw new InvalidProgramException(), + }; } #endregion @@ -983,20 +972,16 @@ private NullAbstractValue GetNullStateBasedOnInstanceOrReferenceValue(IOperation private PointsToAbstractValue GetValueBasedOnInstanceOrReferenceValue(IOperation referenceOrInstance, IOperation operation, PointsToAbstractValue defaultValue) { NullAbstractValue nullState = GetNullStateBasedOnInstanceOrReferenceValue(referenceOrInstance, operation.Type, defaultValue.NullState); - switch (nullState) + return nullState switch { - case NullAbstractValue.NotNull: - return defaultValue.MakeNonNull(); + NullAbstractValue.NotNull => defaultValue.MakeNonNull(), - case NullAbstractValue.Null: - return defaultValue.MakeNull(); + NullAbstractValue.Null => defaultValue.MakeNull(), - case NullAbstractValue.Invalid: - return PointsToAbstractValue.Invalid; + NullAbstractValue.Invalid => PointsToAbstractValue.Invalid, - default: - return defaultValue; - } + _ => defaultValue, + }; } public override PointsToAbstractValue VisitFieldReference(IFieldReferenceOperation operation, object argument) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs index 7e64b2de71..62ae85b5d9 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs @@ -6,8 +6,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs index a517c4af3f..2552ae6d61 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisContext.cs @@ -11,8 +11,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs index d68a75e2bb..6d50e440f0 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs @@ -22,20 +22,16 @@ internal static class PropertySetCallbacks /// Flagged if null, Unflagged if not null, MaybeFlagged otherwise. public static PropertySetAbstractValueKind FlagIfNull(PointsToAbstractValue pointsToAbstractValue) { - switch (pointsToAbstractValue.NullState) + return pointsToAbstractValue.NullState switch { - case NullAbstractValue.Null: - return PropertySetAbstractValueKind.Flagged; + NullAbstractValue.Null => PropertySetAbstractValueKind.Flagged, - case NullAbstractValue.NotNull: - return PropertySetAbstractValueKind.Unflagged; + NullAbstractValue.NotNull => PropertySetAbstractValueKind.Unflagged, - case NullAbstractValue.MaybeNull: - return PropertySetAbstractValueKind.MaybeFlagged; + NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged, - default: - return PropertySetAbstractValueKind.Unknown; - } + _ => PropertySetAbstractValueKind.Unknown, + }; } /// @@ -45,8 +41,6 @@ public static PropertySetAbstractValueKind FlagIfNull(PointsToAbstractValue poin /// Predicate function to determine if a literal value is bad. /// Mapped kind. /// - /// Null is not handled by this. Look at the if you need to treat null as bad. - /// /// All literal values are bad => Flagged /// Some but not all literal are bad => MaybeFlagged /// All literal values are known and none are bad => Unflagged diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/PooledHashSetExtensions.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/PooledHashSetExtensions.cs index 7c1a9778a7..29ed352f02 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/PooledHashSetExtensions.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/PooledHashSetExtensions.cs @@ -74,7 +74,7 @@ internal static class PooledHashSetExtensions (methodName, argumets) => methodName == o, ImmutableHashSet<(PointsToCheck, string)>.Empty.Add( ( - pointsTos => true, + SourceInfo.AlwaysTruePointsToCheck, TaintedTargetValue.Return )) )) @@ -149,13 +149,13 @@ internal static class PooledHashSetExtensions /// Add SourceInfos which needs PointsToAnalysis checks or ValueContentAnalysis checks and each check taints return value by default. /// public static void AddSourceInfo( - this PooledHashSet builder, - string fullTypeName, - bool isInterface, - string[] taintedProperties, - IEnumerable<(MethodMatcher methodMatcher, PointsToCheck[] pointsToChecks)> taintedMethodsNeedsPointsToAnalysis, - IEnumerable<(MethodMatcher methodMatcher, ValueContentCheck[] valueContentChecks)> taintedMethodsNeedsValueContentAnalysis, - bool taintConstantArray = false) + this PooledHashSet builder, + string fullTypeName, + bool isInterface, + string[] taintedProperties, + IEnumerable<(MethodMatcher methodMatcher, PointsToCheck[] pointsToChecks)> taintedMethodsNeedsPointsToAnalysis, + IEnumerable<(MethodMatcher methodMatcher, ValueContentCheck[] valueContentChecks)> taintedMethodsNeedsValueContentAnalysis, + bool taintConstantArray = false) { SourceInfo metadata = new SourceInfo( fullTypeName, diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SourceInfo.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SourceInfo.cs index 2253c15f40..1ce0b5e1b1 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SourceInfo.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SourceInfo.cs @@ -17,6 +17,10 @@ namespace Analyzer.Utilities.FlowAnalysis.Analysis.TaintedDataAnalysis /// internal class SourceInfo : ITaintedDataInfo, IEquatable { + // TODO: This is just a quick fix for a performance regression. Perhaps we should have a dedicated collection + // of methods which are always tainted. + public static readonly PointsToCheck AlwaysTruePointsToCheck = (ImmutableArray pointsTos) => true; + /// /// Constructs. /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SymbolAccess.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SymbolAccess.cs index 5f1f355de4..4b508da744 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SymbolAccess.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/SymbolAccess.cs @@ -6,8 +6,6 @@ namespace Analyzer.Utilities.FlowAnalysis.Analysis.TaintedDataAnalysis { -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - /// /// Represents an access to a symbol. /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAbstractValue.cs index 31bfbffcc8..938bc1a87b 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAbstractValue.cs @@ -10,8 +10,6 @@ namespace Analyzer.Utilities.FlowAnalysis.Analysis.TaintedDataAnalysis { -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - /// /// Abstract tainted data value shared by a set of one of more instances tracked by . /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysisContext.cs index eafc298d20..85294b2bcb 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysisContext.cs @@ -10,8 +10,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Analyzer.Utilities.FlowAnalysis.Analysis.TaintedDataAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataSymbolMapExtensions.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataSymbolMapExtensions.cs index b2e5d1dc76..5c596c5796 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataSymbolMapExtensions.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataSymbolMapExtensions.cs @@ -72,6 +72,73 @@ internal static class TaintedDataSymbolMapExtensions return taintedTargets != null; } + /// + /// Faster IsSourceMethod(), before using PointsToAnalysis or ValueContentAnalysis. + /// + /// SourceInfos. + /// Invoked ethod to be evaluated. + /// Arguments of the method. + /// Indicates that the invoked method is definitely a tainted data source. + /// Indicates that the invoked method requires PointsToAnalysis for further + /// evaluation. + /// Indicates that the invoked method requires ValueContentAnalysis for further + /// evaluation. + /// True if the invoked method is potentially a tainted data source. + public static bool IsSourceMethodFast( + this TaintedDataSymbolMap sourceSymbolMap, + IMethodSymbol method, + ImmutableArray arguments, + out bool isSourceMethod, + out bool requiresPointsTo, + out bool requiresValueContent) + { + isSourceMethod = false; + requiresPointsTo = false; + requiresValueContent = false; + + foreach (SourceInfo sourceInfo in sourceSymbolMap.GetInfosForType(method.ContainingType)) + { + if (!(requiresPointsTo && isSourceMethod)) + { + foreach ((MethodMatcher methodMatcher, ImmutableHashSet<(PointsToCheck pointsToCheck, string)> pointsToTaintedTargets) in sourceInfo.TaintedMethodsNeedsPointsToAnalysis) + { + if (methodMatcher(method.Name, arguments)) + { + foreach ((PointsToCheck pointsToCheck, string) p in pointsToTaintedTargets) + { + if (p.pointsToCheck == SourceInfo.AlwaysTruePointsToCheck) + { + isSourceMethod = true; + } + else + { + requiresPointsTo = true; + } + } + } + } + } + + if (!requiresValueContent) + { + foreach ((MethodMatcher methodMatcher, ImmutableHashSet<(ValueContentCheck valueContentCheck, string)> valueContentTaintedTargets) in sourceInfo.TaintedMethodsNeedsValueContentAnalysis) + { + if (methodMatcher(method.Name, arguments)) + { + requiresValueContent = true; + } + } + } + + if (requiresPointsTo && requiresValueContent && isSourceMethod) + { + break; + } + } + + return isSourceMethod || requiresPointsTo || requiresValueContent; + } + /// /// Determines if the given property is a tainted data source. /// @@ -131,16 +198,16 @@ out PooledHashSet<(string, string)> taintedParameterPairs) taintedParameterPairs = null; foreach (SourceInfo sourceInfo in sourceSymbolMap.GetInfosForType(method.ContainingType)) { - foreach ((MethodMatcher methodMatcher, ImmutableHashSet<(string source, string end)> sourceToEnds) passerMethod in sourceInfo.TransferMethods) + foreach ((MethodMatcher methodMatcher, ImmutableHashSet<(string source, string end)> sourceToEnds) in sourceInfo.TransferMethods) { - if (passerMethod.methodMatcher(method.Name, arguments)) + if (methodMatcher(method.Name, arguments)) { if (taintedParameterPairs == null) { taintedParameterPairs = PooledHashSet<(string, string)>.GetInstance(); } - taintedParameterPairs.UnionWith(passerMethod.sourceToEnds.Where(s => taintedParameterNames.Contains(s.source))); + taintedParameterPairs.UnionWith(sourceToEnds.Where(s => taintedParameterNames.Contains(s.source))); } } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAbstractValue.cs index bb54585374..499089e6b4 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAbstractValue.cs @@ -10,8 +10,6 @@ using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.Operations; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis { /// @@ -26,6 +24,7 @@ public partial class ValueContentAbstractValue : CacheBasedEquatable.Empty, ValueContainsNonLiteralState.Invalid); public static ValueContentAbstractValue MayBeContainsNonLiteralState { get; } = new ValueContentAbstractValue(ImmutableHashSet.Empty, ValueContainsNonLiteralState.Maybe); public static ValueContentAbstractValue DoesNotContainLiteralOrNonLiteralState { get; } = new ValueContentAbstractValue(ImmutableHashSet.Empty, ValueContainsNonLiteralState.No); + public static ValueContentAbstractValue ContainsNullLiteralState { get; } = new ValueContentAbstractValue(ImmutableHashSet.Create((object)null), ValueContainsNonLiteralState.No); public static ValueContentAbstractValue ContainsEmptyStringLiteralState { get; } = new ValueContentAbstractValue(ImmutableHashSet.Create(string.Empty), ValueContainsNonLiteralState.No); public static ValueContentAbstractValue ContainsZeroIntergralLiteralState { get; } = new ValueContentAbstractValue(ImmutableHashSet.Create(0), ValueContainsNonLiteralState.No); public static ValueContentAbstractValue ContainsOneIntergralLiteralState { get; } = new ValueContentAbstractValue(ImmutableHashSet.Create(1), ValueContainsNonLiteralState.No); @@ -40,6 +39,8 @@ private ValueContentAbstractValue(ImmutableHashSet literalValues, ValueC internal static ValueContentAbstractValue Create(object literal, ITypeSymbol type) { + Debug.Assert(literal != null); + switch (type.SpecialType) { case SpecialType.System_Byte: @@ -79,17 +80,13 @@ private static ValueContentAbstractValue Create(ImmutableHashSet literal { if (literalValues.IsEmpty) { - switch (nonLiteralState) + return nonLiteralState switch { - case ValueContainsNonLiteralState.Undefined: - return UndefinedState; - case ValueContainsNonLiteralState.Invalid: - return InvalidState; - case ValueContainsNonLiteralState.No: - return DoesNotContainLiteralOrNonLiteralState; - default: - return MayBeContainsNonLiteralState; - } + ValueContainsNonLiteralState.Undefined => UndefinedState, + ValueContainsNonLiteralState.Invalid => InvalidState, + ValueContainsNonLiteralState.No => DoesNotContainLiteralOrNonLiteralState, + _ => MayBeContainsNonLiteralState, + }; } else if (literalValues.Count == 1 && nonLiteralState == ValueContainsNonLiteralState.No) { @@ -205,13 +202,13 @@ private static ValueContainsNonLiteralState Merge(ValueContainsNonLiteralState v public bool IsLiteralState => !LiteralValues.IsEmpty && NonLiteralState == ValueContainsNonLiteralState.No; /// - /// For super simple cases: If this abstract value is a single literal, then get that literal value. + /// For super simple cases: If this abstract value is a single non-null literal, then get that literal value. /// /// Type of the expected literal value. - /// Literal value, or its default if not a single literal value. - /// True if a literal value was found, false otherwise. + /// Literal value, or its default if not a single non-null literal value. + /// True if a non-null literal value was found, false otherwise. /// If you're looking for null, you should be looking at . - public bool TryGetSingleLiteral(out T literalValue) + public bool TryGetSingleNonNullLiteral(out T literalValue) { if (!IsLiteralState || LiteralValues.Count != 1) { diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.ValueContentDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.ValueContentDataFlowOperationVisitor.cs index 83fd91230a..06bf6fc6f4 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.ValueContentDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.ValueContentDataFlowOperationVisitor.cs @@ -53,7 +53,9 @@ protected override ValueContentAbstractValue GetAbstractValue(AnalysisEntity ana => CurrentAnalysisData.TryGetValue(analysisEntity, out var value) ? value : ValueDomain.UnknownOrMayBeValue; protected override ValueContentAbstractValue GetAbstractDefaultValue(ITypeSymbol type) - => ValueContentAbstractValue.DoesNotContainLiteralOrNonLiteralState; + => type != null ? + ValueContentAbstractValue.DoesNotContainLiteralOrNonLiteralState : + ValueContentAbstractValue.ContainsNullLiteralState; protected override bool HasAnyAbstractValue(ValueContentAnalysisData data) => data.HasAnyAbstractValue; @@ -158,28 +160,27 @@ public override ValueContentAbstractValue DefaultVisit(IOperation operation, obj _ = base.DefaultVisit(operation, argument); if (operation.Type == null) { - return ValueContentAbstractValue.DoesNotContainLiteralOrNonLiteralState; + return ValueContentAbstractValue.ContainsNullLiteralState; } if (ValueContentAbstractValue.IsSupportedType(operation.Type, out ITypeSymbol valueTypeSymbol)) { - if (operation.ConstantValue.HasValue && operation.ConstantValue.Value != null) + if (operation.ConstantValue.HasValue) { - return ValueContentAbstractValue.Create(operation.ConstantValue.Value, valueTypeSymbol); + return operation.ConstantValue.Value != null ? + ValueContentAbstractValue.Create(operation.ConstantValue.Value, valueTypeSymbol) : + ValueContentAbstractValue.ContainsNullLiteralState; } else { - switch (GetNullAbstractValue(operation)) + return (GetNullAbstractValue(operation)) switch { - case PointsToAnalysis.NullAbstractValue.Invalid: - return ValueContentAbstractValue.InvalidState; + PointsToAnalysis.NullAbstractValue.Invalid => ValueContentAbstractValue.InvalidState, - case PointsToAnalysis.NullAbstractValue.Null: - return ValueContentAbstractValue.DoesNotContainLiteralOrNonLiteralState; + PointsToAnalysis.NullAbstractValue.Null => ValueContentAbstractValue.ContainsNullLiteralState, - default: - return ValueContentAbstractValue.MayBeContainsNonLiteralState; - } + _ => ValueContentAbstractValue.MayBeContainsNonLiteralState, + }; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs index 9d236726e1..5e918cdba0 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs @@ -6,8 +6,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs index daa889c858..d5ecf81969 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs @@ -40,6 +40,7 @@ public abstract class AbstractDataFlowAnalysisContext interproceduralAnalysisDataOpt, InterproceduralAnalysisPredicate interproceduralAnalysisPredicateOpt) { + Debug.Assert(valueDomain != null, "valueDomain must not be null for use in ComputeHashCodeParts"); Debug.Assert(controlFlowGraph != null); Debug.Assert(owningSymbol != null); Debug.Assert(owningSymbol.Kind == SymbolKind.Method || diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.ConstantValueIndex.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.ConstantValueIndex.cs index 9088e4be30..6259cb739e 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.ConstantValueIndex.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.ConstantValueIndex.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - using System; namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow @@ -17,7 +15,6 @@ public ConstantValueIndex(int index) public int Index { get; } -#pragma warning disable CA1307 // Specify StringComparison - string.GetHashCode(StringComparison) not available in all projects that reference this shared project protected override void ComputeHashCodeParts(Action addPart) { addPart(Index.GetHashCode()); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.OperationBasedIndex.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.OperationBasedIndex.cs index 5af242f87f..e4d295a453 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.OperationBasedIndex.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.OperationBasedIndex.cs @@ -3,8 +3,6 @@ using System; using System.Diagnostics; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow { public abstract partial class AbstractIndex diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.SymbolBasedIndex.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.SymbolBasedIndex.cs index a3749202d0..6107f6118b 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.SymbolBasedIndex.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.SymbolBasedIndex.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - using System; namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.cs index 207940d94b..938bb670ab 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractIndex.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow { /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs index d4e19dcf21..a320024512 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs @@ -8,8 +8,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.Operations; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow { /// @@ -142,21 +140,14 @@ public SyntaxNode TryGetNodeToReportDiagnostic(PointsToAnalysisResult pointsToAn SyntaxNode TryGetSyntaxNodeToReportDiagnostic(IOperation creation) { // If any of the argument to creation points to this location, then use the argument. - ImmutableArray arguments; - switch (creation) + var arguments = creation switch { - case IInvocationOperation invocation: - arguments = invocation.Arguments; - break; + IInvocationOperation invocation => invocation.Arguments, - case IObjectCreationOperation objectCreation: - arguments = objectCreation.Arguments; - break; + IObjectCreationOperation objectCreation => objectCreation.Arguments, - default: - arguments = ImmutableArray.Empty; - break; - } + _ => ImmutableArray.Empty, + }; foreach (var argument in arguments) { diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs index 5fe7b1a72d..ef64788607 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs @@ -10,8 +10,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.Operations; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - CacheBasedEquatable handles equality - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow { /// @@ -173,17 +171,14 @@ public bool HasConstantValue { get { - switch (SymbolOpt) + return SymbolOpt switch { - case IFieldSymbol field: - return field.HasConstantValue; + IFieldSymbol field => field.HasConstantValue, - case ILocalSymbol local: - return local.HasConstantValue; + ILocalSymbol local => local.HasConstantValue, - default: - return false; - } + _ => false, + }; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs index 404cd76dc5..b77326f464 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs @@ -4,8 +4,6 @@ using Analyzer.Utilities; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow { /// diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs index 1d38d7646b..930faaf855 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs @@ -638,16 +638,14 @@ bool isPredicateAlwaysFalseForBranch(PredicateValueKind predicateValueKind) { Debug.Assert(branch.ControlFlowConditionKind != ControlFlowConditionKind.None); - switch (predicateValueKind) + return predicateValueKind switch { - case PredicateValueKind.AlwaysFalse: - return branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenTrue; + PredicateValueKind.AlwaysFalse => branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenTrue, - case PredicateValueKind.AlwaysTrue: - return branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenFalse; - } + PredicateValueKind.AlwaysTrue => branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenFalse, - return false; + _ => false, + }; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DictionaryAnalysisData.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DictionaryAnalysisData.cs index 221783414b..3e1209346d 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DictionaryAnalysisData.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DictionaryAnalysisData.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using Analyzer.Utilities.PooledObjects; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable #pragma warning disable CA1710 // Rename DictionaryAnalysisData to end in 'Dictionary' namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs index 1eaa9b45ee..457c21170b 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs @@ -7,8 +7,6 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; -#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable - namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow { ///