/
UseAutoValidateAntiforgeryToken.cs
390 lines (337 loc) · 21.9 KB
/
UseAutoValidateAntiforgeryToken.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class UseAutoValidateAntiforgeryToken : DiagnosticAnalyzer
{
internal static DiagnosticDescriptor UseAutoValidateAntiforgeryTokenRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5391",
typeof(MicrosoftNetCoreAnalyzersResources),
nameof(MicrosoftNetCoreAnalyzersResources.UseAutoValidateAntiforgeryToken),
nameof(MicrosoftNetCoreAnalyzersResources.UseAutoValidateAntiforgeryTokenMessage),
false,
helpLinkUri: null,
descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.UseAutoValidateAntiforgeryTokenDescription),
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor MissHttpVerbAttributeRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5395",
typeof(MicrosoftNetCoreAnalyzersResources),
nameof(MicrosoftNetCoreAnalyzersResources.MissHttpVerbAttribute),
nameof(MicrosoftNetCoreAnalyzersResources.MissHttpVerbAttributeMessage),
false,
helpLinkUri: null,
descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.MissHttpVerbAttributeDescription),
customTags: WellKnownDiagnosticTags.Telemetry);
private static readonly Regex s_AntiForgeryAttributeRegex = new Regex("^[a-zA-Z]*Validate[a-zA-Z]*Anti[Ff]orgery[a-zA-Z]*Attribute$", RegexOptions.Compiled);
private static readonly Regex s_AntiForgeryRegex = new Regex("^[a-zA-Z]*Validate[a-zA-Z]*Anti[Ff]orgery[a-zA-Z]*$", RegexOptions.Compiled);
private static readonly ImmutableHashSet<string> HttpVerbAttributesMarkingOnActionModifyingMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
WellKnownTypeNames.MicrosoftAspNetCoreMvcHttpPostAttribute,
WellKnownTypeNames.MicrosoftAspNetCoreMvcHttpPutAttribute,
WellKnownTypeNames.MicrosoftAspNetCoreMvcHttpDeleteAttribute,
WellKnownTypeNames.MicrosoftAspNetCoreMvcHttpPatchAttribute);
// It is used to translate ConcurrentDictionary into ConcurrentHashset, which is not provided.
private const bool placeholder = true;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
UseAutoValidateAntiforgeryTokenRule,
MissHttpVerbAttributeRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(compilationStartAnalysisContext =>
{
var compilation = compilationStartAnalysisContext.Compilation;
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartAnalysisContext.Compilation);
if (!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcFiltersFilterCollection, out var filterCollectionTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcController, out var controllerTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcControllerBase, out var controllerBaseTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcNonActionAttribute, out var nonActionAttributeTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcRoutingHttpMethodAttribute, out var httpMethodAttributeTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcFiltersIFilterMetadata, out var iFilterMetadataTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreAntiforgeryIAntiforgery, out var iAntiforgeryTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcFiltersIAsyncAuthorizationFilter, out var iAsyncAuthorizationFilterTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcFiltersIAuthorizationFilter, out var iAuthorizationFilterTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask, out var taskTypeSymbol) ||
!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreMvcFiltersAuthorizationFilterContext, out var authorizationFilterContextTypeSymbol))
{
return;
}
var httpVerbAttributeTypeSymbolsAbleToModify = HttpVerbAttributesMarkingOnActionModifyingMethods.Select(
s => wellKnownTypeProvider.TryGetTypeByMetadataName(s, out var attributeTypeSymbol) ? attributeTypeSymbol : null);
if (httpVerbAttributeTypeSymbolsAbleToModify.Any(s => s == null))
{
return;
}
var cancellationToken = compilationStartAnalysisContext.CancellationToken;
var onlyLookAtDerivedClassesOfController = compilationStartAnalysisContext.Options.GetBoolOptionValue(
optionName: EditorConfigOptionNames.ExcludeAspnetCoreMvcControllerBase,
rule: UseAutoValidateAntiforgeryTokenRule,
defaultValue: true,
cancellationToken: cancellationToken);
// A dictionary from method symbol to set of methods calling it directly.
var inverseGraph = new ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>>();
// Ignore cases where a global anti forgery filter is in use.
var hasGlobalAntiForgeryFilter = false;
// Verify that validate anti forgery token attributes are used somewhere within this project,
// to avoid reporting false positives on projects that use an alternative approach to mitigate CSRF issues.
var usingValidateAntiForgeryAttribute = false;
var onAuthorizationAsyncMethodSymbols = new ConcurrentDictionary<IMethodSymbol, bool>();
var actionMethodSymbols = new ConcurrentDictionary<(IMethodSymbol, string), bool>();
var actionMethodNeedAddingHttpVerbAttributeSymbols = new ConcurrentDictionary<IMethodSymbol, bool>();
// Constructing inverse callGraph.
// When it comes to delegate function assignment Del handler = DelegateMethod;, inverse call Graph will add:
// (1) key: method gets called in DelegateMethod, value: handler.
// When it comes to calling delegate function handler(), inverse callGraph will add:
// (1) key: delegate function handler, value: callerMethod.
// (2) key: Invoke(), value: callerMethod.
compilationStartAnalysisContext.RegisterOperationBlockStartAction(
(OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) =>
{
if (hasGlobalAntiForgeryFilter)
{
return;
}
var owningSymbol = operationBlockStartAnalysisContext.OwningSymbol;
inverseGraph.GetOrAdd(owningSymbol, (_) => new ConcurrentDictionary<ISymbol, bool>());
operationBlockStartAnalysisContext.RegisterOperationAction(operationContext =>
{
ISymbol calledSymbol = null;
ConcurrentDictionary<ISymbol, bool> callers = null;
switch (operationContext.Operation)
{
case IInvocationOperation invocationOperation:
calledSymbol = invocationOperation.TargetMethod.OriginalDefinition;
break;
case IFieldReferenceOperation fieldReferenceOperation:
var fieldSymbol = (IFieldSymbol)fieldReferenceOperation.Field;
if (fieldSymbol.Type.TypeKind == TypeKind.Delegate)
{
calledSymbol = fieldSymbol;
break;
}
return;
}
if (calledSymbol == null)
{
return;
}
callers = inverseGraph.GetOrAdd(calledSymbol, (_) => new ConcurrentDictionary<ISymbol, bool>());
callers.TryAdd(owningSymbol, placeholder);
}, OperationKind.Invocation, OperationKind.FieldReference);
});
// Holds if the project has a global anti forgery filter.
compilationStartAnalysisContext.RegisterOperationAction(operationAnalysisContext =>
{
if (hasGlobalAntiForgeryFilter)
{
return;
}
var invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation;
var methodSymbol = invocationOperation.TargetMethod;
if (methodSymbol.Name == "Add" &&
methodSymbol.ContainingType.GetBaseTypesAndThis().Contains(filterCollectionTypeSymbol))
{
var potentialAntiForgeryFilters = invocationOperation
.Arguments
.Where(s => s.Parameter.Name == "filterType")
.Select(s => s.Value)
.OfType<ITypeOfOperation>()
.Select(s => s.TypeOperand)
.Union(methodSymbol.TypeArguments);
foreach (var potentialAntiForgeryFilter in potentialAntiForgeryFilters)
{
if (potentialAntiForgeryFilter.AllInterfaces.Contains(iFilterMetadataTypeSymbol) &&
s_AntiForgeryRegex.IsMatch(potentialAntiForgeryFilter.Name))
{
hasGlobalAntiForgeryFilter = true;
return;
}
else if (potentialAntiForgeryFilter.AllInterfaces.Contains(iAsyncAuthorizationFilterTypeSymbol) ||
potentialAntiForgeryFilter.AllInterfaces.Contains(iAuthorizationFilterTypeSymbol))
{
onAuthorizationAsyncMethodSymbols.TryAdd(
potentialAntiForgeryFilter
.GetMembers()
.OfType<IMethodSymbol>()
.FirstOrDefault(
s => (s.Name == "OnAuthorizationAsync" &&
s.ReturnType.Equals(taskTypeSymbol) ||
s.Name == "OnAuthorization" &&
s.ReturnsVoid) &&
s.Parameters.Length == 1 &&
s.Parameters[0].Type.Equals(authorizationFilterContextTypeSymbol)),
placeholder);
}
}
}
}, OperationKind.Invocation);
compilationStartAnalysisContext.RegisterSymbolAction(symbolAnalysisContext =>
{
if (hasGlobalAntiForgeryFilter)
{
return;
}
var derivedControllerTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol;
var baseTypes = derivedControllerTypeSymbol.GetBaseTypes();
// An subtype of `Microsoft.AspNetCore.Mvc.Controller`, which probably indicates views are used and maybe cookie-based authentication is used and thus CSRF is a concern.
if (baseTypes.Contains(controllerTypeSymbol) ||
(!onlyLookAtDerivedClassesOfController &&
baseTypes.Contains(controllerBaseTypeSymbol)))
{
// The controller class is not protected by a validate anti forgery token attribute.
if (!IsUsingAntiFogeryAttribute(derivedControllerTypeSymbol))
{
foreach (var actionMethodSymbol in derivedControllerTypeSymbol.GetMembers().OfType<IMethodSymbol>())
{
if (actionMethodSymbol.MethodKind == MethodKind.Constructor)
{
continue;
}
if (actionMethodSymbol.IsPublic() &&
!actionMethodSymbol.IsStatic)
{
var hasNonActionAttribute = actionMethodSymbol.HasAttribute(nonActionAttributeTypeSymbol);
var overridenMethodSymbol = actionMethodSymbol as ISymbol;
while (!hasNonActionAttribute && overridenMethodSymbol.IsOverride)
{
overridenMethodSymbol = overridenMethodSymbol.GetOverriddenMember();
if (overridenMethodSymbol.HasAttribute(nonActionAttributeTypeSymbol))
{
hasNonActionAttribute = true;
}
}
// The method has [NonAction].
if (hasNonActionAttribute)
{
continue;
}
// The method is not protected by a validate anti forgery token attribute.
if (!IsUsingAntiFogeryAttribute(actionMethodSymbol))
{
var httpVerbAttributeTypeSymbolAbleToModify = actionMethodSymbol.GetAttributes().FirstOrDefault(s => httpVerbAttributeTypeSymbolsAbleToModify.Contains(s.AttributeClass));
if (httpVerbAttributeTypeSymbolAbleToModify != null)
{
var attributeName = httpVerbAttributeTypeSymbolAbleToModify.AttributeClass.Name;
actionMethodSymbols.TryAdd(
(actionMethodSymbol,
attributeName.EndsWith("Attribute", StringComparison.Ordinal) ? attributeName.Remove(attributeName.Length - "Attribute".Length) : attributeName),
placeholder);
}
else if (!actionMethodSymbol.GetAttributes().Any(s => s.AttributeClass.GetBaseTypes().Contains(httpMethodAttributeTypeSymbol)))
{
actionMethodNeedAddingHttpVerbAttributeSymbols.TryAdd(actionMethodSymbol, placeholder);
}
}
}
}
}
}
}, SymbolKind.NamedType);
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
if (usingValidateAntiForgeryAttribute && !hasGlobalAntiForgeryFilter && (actionMethodSymbols.Any() || actionMethodNeedAddingHttpVerbAttributeSymbols.Any()))
{
var visited = new HashSet<ISymbol>();
var results = new Dictionary<ISymbol, HashSet<ISymbol>>();
if (onAuthorizationAsyncMethodSymbols.Any())
{
foreach (var calleeMethod in inverseGraph.Keys)
{
if (calleeMethod.Name == "ValidateRequestAsync" &&
(calleeMethod.ContainingType.AllInterfaces.Contains(iAntiforgeryTypeSymbol) ||
calleeMethod.ContainingType.Equals(iAntiforgeryTypeSymbol)))
{
FindAllTheSpecifiedCalleeMethods(calleeMethod, visited, results);
if (results.Values.Any(s => s.Any()))
{
return;
}
}
}
}
foreach (var (methodSymbol, attributeName) in actionMethodSymbols.Keys)
{
compilationAnalysisContext.ReportDiagnostic(
methodSymbol.CreateDiagnostic(
UseAutoValidateAntiforgeryTokenRule,
methodSymbol.Name,
attributeName));
}
foreach (var methodSymbol in actionMethodNeedAddingHttpVerbAttributeSymbols.Keys)
{
compilationAnalysisContext.ReportDiagnostic(
methodSymbol.CreateDiagnostic(
MissHttpVerbAttributeRule,
methodSymbol.Name));
}
}
});
// <summary>
// Analyze the method to find all the specified methods that call it, in this case, the specified method symbols are in onAuthorizationAsyncMethodSymbols.
// </summary>
// <param name="methodSymbol">The symbol of the method to be analyzed</param>
// <param name="visited">All the method has been analyzed</param>
// <param name="results">The result is organized by <method to be analyzed, specified methods calling it></param>
void FindAllTheSpecifiedCalleeMethods(ISymbol methodSymbol, HashSet<ISymbol> visited, Dictionary<ISymbol, HashSet<ISymbol>> results)
{
if (visited.Add(methodSymbol))
{
results.Add(methodSymbol, new HashSet<ISymbol>());
if (!inverseGraph.TryGetValue(methodSymbol, out var callingMethods))
{
Debug.Fail(methodSymbol.Name + " was not found in inverseGraph.");
return;
}
foreach (var child in callingMethods.Keys)
{
if (child is IMethodSymbol childMethodSymbol &&
onAuthorizationAsyncMethodSymbols.ContainsKey(childMethodSymbol))
{
results[methodSymbol].Add(child);
}
FindAllTheSpecifiedCalleeMethods(child, visited, results);
if (results.TryGetValue(child, out var result))
{
results[methodSymbol].UnionWith(result);
}
else
{
Debug.Fail(child.Name + " was not found in results.");
}
}
}
}
bool IsUsingAntiFogeryAttribute(ISymbol symbol)
{
if (symbol.GetAttributes().Any(s => s_AntiForgeryAttributeRegex.IsMatch(s.AttributeClass.Name)))
{
usingValidateAntiForgeryAttribute = true;
return true;
}
else
{
return false;
}
}
});
}
}
}