-
Notifications
You must be signed in to change notification settings - Fork 467
/
DoNotUseWeakKDFInsufficientIterationCount.cs
221 lines (193 loc) · 12.4 KB
/
DoNotUseWeakKDFInsufficientIterationCount.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotUseWeakKDFInsufficientIterationCount : DiagnosticAnalyzer
{
internal static DiagnosticDescriptor DefinitelyUseWeakKDFInsufficientIterationCountRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5387",
typeof(SystemSecurityCryptographyResources),
nameof(SystemSecurityCryptographyResources.DefinitelyUseWeakKDFInsufficientIterationCount),
nameof(SystemSecurityCryptographyResources.DefinitelyUseWeakKDFInsufficientIterationCountMessage),
false,
helpLinkUri: null,
descriptionResourceStringName: nameof(SystemSecurityCryptographyResources.DoNotUseWeakKDFInsufficientIterationCountDescription),
customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry);
internal static DiagnosticDescriptor MaybeUseWeakKDFInsufficientIterationCountRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5388",
typeof(SystemSecurityCryptographyResources),
nameof(SystemSecurityCryptographyResources.MaybeUseWeakKDFInsufficientIterationCount),
nameof(SystemSecurityCryptographyResources.MaybeUseWeakKDFInsufficientIterationCountMessage),
false,
helpLinkUri: null,
descriptionResourceStringName: nameof(SystemSecurityCryptographyResources.DoNotUseWeakKDFInsufficientIterationCountDescription),
customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
DefinitelyUseWeakKDFInsufficientIterationCountRule,
MaybeUseWeakKDFInsufficientIterationCountRule);
private const int DefaultIterationCount = 1000;
private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue)
{
switch (propertySetAbstractValue[0])
{
case PropertySetAbstractValueKind.Flagged:
return HazardousUsageEvaluationResult.Flagged;
case PropertySetAbstractValueKind.MaybeFlagged:
return HazardousUsageEvaluationResult.MaybeFlagged;
default:
return HazardousUsageEvaluationResult.Unflagged;
}
}
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
HazardousUsageEvaluatorCollection hazardousUsageEvaluators = new HazardousUsageEvaluatorCollection(
new HazardousUsageEvaluator("GetBytes", HazardousUsageCallback));
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartAnalysisContext.Compilation);
if (!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes, out var rfc2898DeriveBytesTypeSymbol))
{
return;
}
var cancellationToken = compilationStartAnalysisContext.CancellationToken;
var sufficientIterationCount = compilationStartAnalysisContext.Options.GetUnsignedIntegralOptionValue(
optionName: EditorConfigOptionNames.SufficientIterationCountForWeakKDFAlgorithm,
rule: DefinitelyUseWeakKDFInsufficientIterationCountRule,
defaultValue: 100000,
cancellationToken: cancellationToken);
var constructorMapper = new ConstructorMapper(
(IMethodSymbol constructorMethod, IReadOnlyList<ValueContentAbstractValue> argumentValueContentAbstractValues,
IReadOnlyList<PointsToAbstractValue> argumentPointsToAbstractValues) =>
{
var kind = DefaultIterationCount >= sufficientIterationCount ? PropertySetAbstractValueKind.Unflagged : PropertySetAbstractValueKind.Flagged;
if (constructorMethod.Parameters.Length >= 3)
{
if (constructorMethod.Parameters[2].Name == "iterations" &&
constructorMethod.Parameters[2].Type.SpecialType == SpecialType.System_Int32)
{
kind = PropertySetAnalysis.EvaluateLiteralValues(argumentValueContentAbstractValues[2], o => Convert.ToInt32(o) < sufficientIterationCount);
}
}
return PropertySetAbstractValue.GetInstance(kind);
});
var propertyMappers = new PropertyMapperCollection(
new PropertyMapper(
"IterationCount",
(ValueContentAbstractValue valueContentAbstractValue) =>
{
return PropertySetAnalysis.EvaluateLiteralValues(valueContentAbstractValue, o => Convert.ToInt32(o) < sufficientIterationCount);
}));
var rootOperationsNeedingAnalysis = PooledHashSet<(IOperation, ISymbol)>.GetInstance();
compilationStartAnalysisContext.RegisterOperationBlockStartAction(
(OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) =>
{
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation;
if (rfc2898DeriveBytesTypeSymbol.Equals(invocationOperation.Instance?.Type) &&
invocationOperation.TargetMethod.Name == "GetBytes")
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((invocationOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Invocation);
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var argumentOperation = (IArgumentOperation)operationAnalysisContext.Operation;
if (rfc2898DeriveBytesTypeSymbol.Equals(argumentOperation.Parameter.Type))
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((argumentOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Argument);
});
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
PooledDictionary<(Location Location, IMethodSymbol Method), HazardousUsageEvaluationResult> allResults = null;
try
{
lock (rootOperationsNeedingAnalysis)
{
if (!rootOperationsNeedingAnalysis.Any())
{
return;
}
allResults = PropertySetAnalysis.BatchGetOrComputeHazardousUsages(
compilationAnalysisContext.Compilation,
rootOperationsNeedingAnalysis,
WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes,
constructorMapper,
propertyMappers,
hazardousUsageEvaluators,
InterproceduralAnalysisConfiguration.Create(
compilationAnalysisContext.Options,
SupportedDiagnostics,
defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive,
cancellationToken: cancellationToken));
}
if (allResults == null)
{
return;
}
foreach (KeyValuePair<(Location Location, IMethodSymbol Method), HazardousUsageEvaluationResult> kvp
in allResults)
{
DiagnosticDescriptor descriptor;
switch (kvp.Value)
{
case HazardousUsageEvaluationResult.Flagged:
descriptor = DefinitelyUseWeakKDFInsufficientIterationCountRule;
break;
case HazardousUsageEvaluationResult.MaybeFlagged:
descriptor = MaybeUseWeakKDFInsufficientIterationCountRule;
break;
default:
Debug.Fail($"Unhandled result value {kvp.Value}");
continue;
}
compilationAnalysisContext.ReportDiagnostic(
Diagnostic.Create(
descriptor,
kvp.Key.Location,
sufficientIterationCount));
}
}
finally
{
rootOperationsNeedingAnalysis.Free();
allResults?.Free();
}
});
});
}
}
}