Skip to content

Commit a4afa82

Browse files
authored
Enable roslyn analyzers (#1044)
* Add roslyn analyzers and corresponding rules * Fix basic errors spotted by first round of analyzers * Add exception to CA1507
1 parent 0b348d1 commit a4afa82

File tree

13 files changed

+262
-8
lines changed

13 files changed

+262
-8
lines changed

eng/Analyzers.props

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project>
2+
<PropertyGroup>
3+
<CodeAnalysisRuleset>$(MSBuildThisFileDirectory)CodeAnalysis.ruleset</CodeAnalysisRuleset>
4+
<EnableAnalyzers>true</EnableAnalyzers>
5+
</PropertyGroup>
6+
<ItemGroup>
7+
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.0.0-beta3.final" PrivateAssets="all" />
8+
</ItemGroup>
9+
</Project>

eng/CodeAnalysis.Repository.ruleset

Lines changed: 167 additions & 0 deletions
Large diffs are not rendered by default.

eng/CodeAnalysis.Security.ruleset

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?xml version="1.0"?>
2+
<RuleSet Name="Microsoft SDL Roslyn Rules - v9.1"
3+
Description="Microsoft SDL Roslyn Rules - v9.1"
4+
ToolsVersion="14.0">
5+
6+
<Rules AnalyzerId="Microsoft.NetCore.Analyzers" RuleNamespace="Microsoft.NetCore.Analyzers">
7+
<Rule Id="CA2301" Action="Error" /> <!-- Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder -->
8+
<Rule Id="CA2302" Action="Error" /> <!-- Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize -->
9+
<Rule Id="CA2305" Action="Error" /> <!-- Do not use insecure deserializer LosFormatter -->
10+
<Rule Id="CA2311" Action="Error" /> <!-- Do not deserialize without first setting NetDataContractSerializer.Binder -->
11+
<Rule Id="CA2312" Action="Error" /> <!-- Ensure NetDataContractSerializer.Binder is set before deserializing -->
12+
<Rule Id="CA2315" Action="Error" /> <!-- Do not use insecure deserializer ObjectStateFormatter -->
13+
<Rule Id="CA2321" Action="Error" /> <!-- Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver -->
14+
<Rule Id="CA2327" Action="Error" /> <!-- Do not use insecure JsonSerializerSettings -->
15+
<Rule Id="CA2328" Action="Error" /> <!-- Ensure that JsonSerializerSettings are secure -->
16+
<Rule Id="CA2329" Action="Error" /> <!-- Do not deserialize with JsonSerializer using an insecure configuration -->
17+
<Rule Id="CA2330" Action="Error" /> <!-- Ensure that JsonSerializer has a secure configuration when deserializing -->
18+
<Rule Id="CA3061" Action="Error" /> <!-- Do Not Add Schema By URL -->
19+
<Rule Id="CA5350" Action="Error" /> <!-- Do Not Use Weak Cryptographic Algorithms -->
20+
<Rule Id="CA5351" Action="Error" /> <!-- Do Not Use Broken Cryptographic Algorithms -->
21+
<Rule Id="CA5358" Action="Error" /> <!-- Review cipher mode usage with cryptography experts -->
22+
<Rule Id="CA5361" Action="Error" /> <!-- Do Not Disable SChannel Use of Strong Crypto -->
23+
<Rule Id="CA5364" Action="Error" /> <!-- Do Not Use Deprecated Security Protocols -->
24+
<Rule Id="CA5378" Action="Error" /> <!-- Do not disable ServicePointManagerSecurityProtocols -->
25+
<Rule Id="CA5397" Action="Error" /> <!-- Do not use deprecated SslProtocols values -->
26+
<Rule Id="CA2322" Action="Info" /> <!-- Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing -->
27+
<Rule Id="CA3001" Action="Info" /> <!-- Review code for SQL injection vulnerabilities -->
28+
<Rule Id="CA3002" Action="Info" /> <!-- Review code for XSS vulnerabilities -->
29+
<Rule Id="CA3003" Action="Info" /> <!-- Review code for file path injection vulnerabilities -->
30+
<Rule Id="CA3004" Action="Info" /> <!-- Review code for information disclosure vulnerabilities -->
31+
<Rule Id="CA3005" Action="Info" /> <!-- Review code for LDAP injection vulnerabilities -->
32+
<Rule Id="CA3006" Action="Info" /> <!-- Review code for process command injection vulnerabilities -->
33+
<Rule Id="CA3007" Action="Info" /> <!-- Review code for open redirect vulnerabilities -->
34+
<Rule Id="CA3008" Action="Info" /> <!-- Review code for XPath injection vulnerabilities -->
35+
<Rule Id="CA3009" Action="Info" /> <!-- Review code for XML injection vulnerabilities -->
36+
<Rule Id="CA3010" Action="Info" /> <!-- Review code for XAML injection vulnerabilities -->
37+
<Rule Id="CA3011" Action="Info" /> <!-- Review code for DLL injection vulnerabilities -->
38+
<Rule Id="CA3012" Action="Info" /> <!-- Review code for regex injection vulnerabilities -->
39+
<Rule Id="CA5359" Action="Info" /> <!-- Do Not Disable Certificate Validation -->
40+
<Rule Id="CA5380" Action="Info" /> <!-- Do Not Add Certificates To Root Store -->
41+
<Rule Id="CA5381" Action="Info" /> <!-- Ensure Certificates Are Not Added To Root Store -->
42+
<Rule Id="CA5386" Action="Info" /> <!-- Avoid hardcoding SecurityProtocolType value -->
43+
<Rule Id="CA5391" Action="Info" /> <!-- Use antiforgery tokens in ASP.NET Core MVC controllers -->
44+
<Rule Id="CA5395" Action="Info" /> <!-- Miss HttpVerb attribute for action methods -->
45+
<Rule Id="CA5396" Action="Info" /> <!-- Set HttpOnly to true for HttpCookie -->
46+
<Rule Id="CA5398" Action="Info" /> <!-- Avoid hardcoded SslProtocols values -->
47+
</Rules>
48+
49+
<Rules AnalyzerId="Microsoft.NetFramework.Analyzers" RuleNamespace="Microsoft.NetFramework.Analyzers">
50+
<Rule Id="CA2153" Action="Error" /> <!-- Do Not Catch Corrupted State Exceptions -->
51+
<Rule Id="CA3075" Action="Error" /> <!-- Insecure DTD processing in XML -->
52+
<Rule Id="CA3147" Action="Error" /> <!-- Mark Verb Handlers With Validate Antiforgery Token -->
53+
</Rules>
54+
55+
<Rules AnalyzerId="Microsoft.NetFramework.CSharp.Analyzers" RuleNamespace="Microsoft.NetFramework.CSharp.Analyzers">
56+
<Rule Id="CA3076" Action="Error" /> <!-- Insecure XSLT script processing. -->
57+
<Rule Id="CA3077" Action="Error" /> <!-- Insecure Processing in API Design, XmlDocument and XmlTextReader -->
58+
</Rules>
59+
60+
<Rules AnalyzerId="Microsoft.NetFramework.VisualBasic.Analyzers" RuleNamespace="Microsoft.NetFramework.VisualBasic.Analyzers">
61+
<Rule Id="CA3076" Action="Error" /> <!-- Insecure XSLT script processing. -->
62+
<Rule Id="CA3077" Action="Error" /> <!-- Insecure Processing in API Design, XmlDocument and XmlTextReader -->
63+
</Rules>
64+
</RuleSet>

eng/CodeAnalysis.ruleset

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<RuleSet Name="Diagnostics Ruleset"
2+
Description="Diagnostics Ruleset"
3+
ToolsVersion="14.0">
4+
5+
<!-- Define all the analyzer rule actions for this repo. -->
6+
<Include Path="CodeAnalysis.Repository.ruleset" Action="Default" />
7+
8+
<!-- This will override or define all rules needed values to be SDL compliant. -->
9+
<Include Path="CodeAnalysis.Security.ruleset" Action="Default" />
10+
</RuleSet>

src/Directory.Build.props

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,6 @@
2626
<PropertyGroup Condition="'$(TargetFramework)' != 'net462'">
2727
<DebugType>portable</DebugType>
2828
</PropertyGroup>
29+
30+
<Import Project="$(RepositoryEngineeringDir)Analyzers.props" />
2931
</Project>

src/Microsoft.Diagnostics.Monitoring/Logging/LogValuesFormatter.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ namespace Microsoft.Diagnostics.Monitoring
1717
public class LogValuesFormatter
1818
{
1919
private const string NullValue = "(null)";
20-
private static readonly object[] EmptyArray = new object[0];
20+
private static readonly object[] EmptyArray = Array.Empty<object>();
2121
private static readonly char[] FormatDelimiters = { ',', ':' };
2222
private readonly string _format;
2323
private readonly List<string> _valueNames = new List<string>();

src/Microsoft.Diagnostics.Monitoring/Logging/LoggerException.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont
3636
info.AddValue("WatsonBuckets", null, typeof(byte[])); // Do not rename (binary serialization)
3737
}
3838

39+
#pragma warning disable CA1507
3940
public override string Message => _exceptionMessage.GetProperty("Message").GetString();
41+
#pragma warning restore CA1507
4042

4143
public override string StackTrace => _exceptionMessage.GetProperty("VerboseMessage").GetString();
4244

src/Microsoft.Diagnostics.NETCore.Client/DiagnosticsClient/EventPipeSessionConfiguration.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public byte[] SerializeV2()
5050
writer.Write((uint)Format);
5151
writer.Write(RequestRundown);
5252

53-
writer.Write(Providers.Count());
53+
writer.Write(Providers.Count);
5454
foreach (var provider in Providers)
5555
{
5656
writer.Write(provider.Keywords);

src/Microsoft.Diagnostics.Repl/Command/CommandProcessor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ private void Invoke(MethodInfo methodInfo, InvocationContext context)
286286
try
287287
{
288288
// Assumes zero parameter constructor
289-
object instance = _constructor.Invoke(new object[0]);
289+
object instance = _constructor.Invoke(Array.Empty<object>());
290290
SetProperties(context, instance);
291291

292292
object[] arguments = BuildArguments(methodInfo, context);

src/SOS/SOS.Hosting/SOSHost.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,7 @@ internal int GetNumberModules(
510510
out uint loaded,
511511
out uint unloaded)
512512
{
513-
loaded = (uint)DataReader.EnumerateModules().Count();
513+
loaded = (uint)DataReader.EnumerateModules().Count;
514514
unloaded = 0;
515515
return S_OK;
516516
}

src/Tools/dotnet-dump/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ private static Option RunCommand() =>
9393
aliases: new[] { "-c", "--command" },
9494
description: "Run the command on start.")
9595
{
96-
Argument = new Argument<string[]>(name: "command", defaultValue: new string[0]) { Arity = ArgumentArity.ZeroOrMore }
96+
Argument = new Argument<string[]>(name: "command", defaultValue: System.Array.Empty<string>()) { Arity = ArgumentArity.ZeroOrMore }
9797
};
9898
}
9999
}

src/Tools/dotnet-gcdump/DotNetHeapDump/EventPipeDotNetHeapDumper.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ public static bool DumpFromEventPipe(CancellationToken ct, int processID, Memory
190190
{
191191
if (!(e is TaskCanceledException))
192192
{
193-
throw ae;
193+
throw;
194194
}
195195
}
196196
}

src/tests/eventpipe/common/IpcTraceTest.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,12 +252,12 @@ private int Validate()
252252
source.Process();
253253
_droppedEvents = source.EventsLost;
254254
}
255-
catch (Exception e)
255+
catch (Exception)
256256
{
257257
Logger.logger.Log($"Exception thrown while reading; dumping culprit stream to disk...");
258258
eventPipeStream.DumpStreamToDisk();
259259
// rethrow it to fail the test
260-
throw e;
260+
throw;
261261
}
262262
Logger.logger.Log("Stopping stream processing");
263263
Logger.logger.Log($"Dropped {source.EventsLost} events");

0 commit comments

Comments
 (0)