diff --git a/tracer/src/Datadog.Trace.Tools.Analyzers/AspectAnalyzers/ReplaceAspectAnalyzer.cs b/tracer/src/Datadog.Trace.Tools.Analyzers/AspectAnalyzers/ReplaceAspectAnalyzer.cs new file mode 100644 index 000000000000..9f2ad3a0c2fe --- /dev/null +++ b/tracer/src/Datadog.Trace.Tools.Analyzers/AspectAnalyzers/ReplaceAspectAnalyzer.cs @@ -0,0 +1,211 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +#nullable enable +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Datadog.Trace.Tools.Analyzers.AspectAnalyzers; + +/// +/// An analyzer that analyzers aspects that use [AspectMethodInsertAfter] and [AspectMethodInsertBefore] +/// for example, and checks that they are all wrapped in a try-catch block. These methods should never throw +/// so they should always have a try-catch block around them. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public class ReplaceAspectAnalyzer : DiagnosticAnalyzer +{ + /// + /// The diagnostic ID displayed in error messages + /// + public const string DiagnosticId = "DD0005"; + + /// + /// The severity of the diagnostic + /// + public const DiagnosticSeverity Severity = DiagnosticSeverity.Error; + +#pragma warning disable RS2008 // Enable analyzer release tracking for the analyzer project + private static readonly DiagnosticDescriptor MissingTryCatchRule = new( + DiagnosticId, + title: "Aspect is in incorrect format", + messageFormat: "Aspect method bodies should contain a single expression to set the result variable, and then have a try-catch block, and then return the created variable", + category: "Reliability", + defaultSeverity: Severity, + isEnabledByDefault: true, + description: "[AspectCtorReplace] and [AspectMethodReplace] Aspects should guarantee safety if possible. Please execute the target method first, then wrap the remainder of the aspect in a try-catch block, and finally return the variable."); +#pragma warning restore RS2008 + + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(MissingTryCatchRule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + // Consider registering other actions that act on syntax instead of or in addition to symbols + // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/Analyzer%20Actions%20Semantics.md for more information + context.RegisterSyntaxNodeAction(AnalyseMethod, SyntaxKind.MethodDeclaration); + } + + private void AnalyseMethod(SyntaxNodeAnalysisContext context) + { + // assume that generated code is safe, so bail out for perf reasons + if (context.IsGeneratedCode || context.Node is not MethodDeclarationSyntax methodDeclaration) + { + return; + } + + var attributes = methodDeclaration.AttributeLists; + if (!attributes.Any()) + { + // no attributes, let's just bail + return; + } + + var hasAspectAttribute = false; + foreach (var attributeList in attributes) + { + foreach (var attribute in attributeList.Attributes) + { + var name = attribute.Name.ToString(); + if (name is "AspectCtorReplace" or "AspectMethodReplace" + or "AspectCtorReplaceAttribute" or "AspectMethodReplaceAttribute") + { + hasAspectAttribute = true; + break; + } + } + } + + if (!hasAspectAttribute) + { + // not an aspect + return; + } + + var bodyBlock = methodDeclaration.Body; + var isVoidMethod = methodDeclaration.ReturnType is PredefinedTypeSyntax { Keyword.Text: "void" }; + int expectedStatements = isVoidMethod ? 2 : 3; + + if (bodyBlock is null) + { + // If we don't have a bodyBlock, it's probably a lambda or expression bodied member + // These can't have try catch blocks, so we should bail out + var location = methodDeclaration.ExpressionBody?.GetLocation() ?? methodDeclaration.GetLocation(); + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, location)); + return; + } + + if (!bodyBlock.Statements.Any()) + { + // ignore this case, for now, if there's nothing in there, it's safe, and we don't want to hassle users too soon + return; + } + + if (bodyBlock.Statements.Count != expectedStatements) + { + // We require exactly a predefined amount of statements, so this must be an error + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, bodyBlock.GetLocation())); + return; + } + + // check the first statement + if (!isVoidMethod && bodyBlock.Statements[0] is not LocalDeclarationStatementSyntax) + { + // this is an error, and we can't go much further + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, bodyBlock.GetLocation())); + return; + } + + if (bodyBlock.Statements[1] is not TryStatementSyntax tryCatchStatement) + { + // oops, you should have a try block here + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, bodyBlock.GetLocation())); + return; + } + + CatchClauseSyntax? catchClause = null; + var hasFilter = false; + var isSystemException = false; + var isRethrowing = false; + + foreach (var catchSyntax in tryCatchStatement.Catches) + { + catchClause = catchSyntax; + isSystemException = false; + isRethrowing = false; + + // check that it's catching _everything_ + hasFilter = catchClause.Filter is not null; + if (hasFilter) + { + // Skipping because we shouldn't be letting anything through + continue; + } + + var exceptionTypeName = catchSyntax.Declaration?.Type is { } exceptionType + ? context.SemanticModel.GetSymbolInfo(exceptionType).Symbol?.ToString() + : null; + isSystemException = exceptionTypeName is null or "System.Exception"; + if (!isSystemException) + { + // skipping because it's not broad enough + continue; + } + + // final requirement, must not be rethrowing + foreach (var statement in catchSyntax.Block.Statements) + { + if (statement is ThrowStatementSyntax) + { + isRethrowing = true; + break; + } + } + + // if we get here, we know one of the loops is all good, so we can break + break; + } + + if (catchClause is null || hasFilter || !isSystemException || isRethrowing) + { + // oops, no good + var location = catchClause?.GetLocation() ?? tryCatchStatement.GetLocation(); + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, location)); + } + + // final check, do we return the variable? + if (!isVoidMethod) + { + if (bodyBlock.Statements[2] is not ReturnStatementSyntax returnStatement) + { + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, bodyBlock.GetLocation())); + return; + } + + // should be returning the variable + if (returnStatement.Expression is not IdentifierNameSyntax identifierName) + { + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, bodyBlock.GetLocation())); + return; + } + + LocalDeclarationStatementSyntax localDeclaration = (LocalDeclarationStatementSyntax)bodyBlock.Statements[0]; + if (!localDeclaration.Declaration.Variables.Any() + || localDeclaration.Declaration.Variables[0] is not { } variable + || variable.Identifier.ToString() != identifierName.Identifier.ToString()) + { + // not returning the right thing + context.ReportDiagnostic(Diagnostic.Create(MissingTryCatchRule, bodyBlock.GetLocation())); + } + } + } +} diff --git a/tracer/src/Datadog.Trace.Tools.Analyzers/AspectAnalyzers/ReplaceAspectCodeFixProvider.cs b/tracer/src/Datadog.Trace.Tools.Analyzers/AspectAnalyzers/ReplaceAspectCodeFixProvider.cs new file mode 100644 index 000000000000..ea5be4493f7c --- /dev/null +++ b/tracer/src/Datadog.Trace.Tools.Analyzers/AspectAnalyzers/ReplaceAspectCodeFixProvider.cs @@ -0,0 +1,126 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +#nullable enable +using System.Collections.Immutable; +using System.Composition; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Datadog.Trace.Tools.Analyzers.ThreadAbortAnalyzer; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Formatting; + +namespace Datadog.Trace.Tools.Analyzers.AspectAnalyzers; + +/// +/// A CodeFixProvider for the +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ReplaceAspectCodeFixProvider))] +[Shared] +public class ReplaceAspectCodeFixProvider : CodeFixProvider +{ + /// + public sealed override ImmutableArray FixableDiagnosticIds + { + get => ImmutableArray.Create(ReplaceAspectAnalyzer.DiagnosticId); + } + + /// + public sealed override FixAllProvider GetFixAllProvider() + { + // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers + return WellKnownFixAllProviders.BatchFixer; + } + + /// + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + + var diagnostic = context.Diagnostics.First(); + var diagnosticSpan = diagnostic.Location.SourceSpan; + + // Find the methodDeclaration identified by the diagnostic. + var methodDeclaration = root?.FindToken(diagnosticSpan.Start) + .Parent + ?.AncestorsAndSelf() + .OfType() + .First(); + + if (methodDeclaration?.Body is { Statements.Count: >2 } body + && body.Statements[0] is LocalDeclarationStatementSyntax localDeclaration + && body.Statements[body.Statements.Count - 1] is ReturnStatementSyntax { Expression: IdentifierNameSyntax identifierName } + && localDeclaration.Declaration.Variables.Count == 1 + && localDeclaration.Declaration.Variables[0] is { } variable + && variable.Identifier.ToString() == identifierName.Identifier.ToString()) + { + // Register a code action that will invoke the fix. + context.RegisterCodeFix( + CodeAction.Create( + title: "Wrap internals with exception handler", + createChangedDocument: c => AddTryCatch(context.Document, methodDeclaration, c), + equivalenceKey: nameof(ReplaceAspectCodeFixProvider)), + diagnostic); + } + } + + private async Task AddTryCatch(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) + { + // we know we're calling this with something we can fix, + // we just need to work out if we need to wrap the internals in a try-catch + // or add a catch statement + var body = methodDeclaration.Body!; + var localDeclaration = (LocalDeclarationStatementSyntax)body.Statements[0]; + var returnSyntax = (ReturnStatementSyntax)body.Statements[body.Statements.Count - 1]; + TryStatementSyntax tryCatch; + + if (body.Statements.Count == 3 && body.Statements[1] is TryStatementSyntax tryStatementSyntax) + { + tryCatch = tryStatementSyntax; + } + else + { + var block = SyntaxFactory.Block(body.Statements.Skip(1).Take(body.Statements.Count - 2)); + tryCatch = SyntaxFactory.TryStatement().WithBlock(block); + } + + // Add the catch statement to the try-catch block + var parentType = methodDeclaration.AncestorsAndSelf() + .FirstOrDefault(x => x is TypeDeclarationSyntax or RecordDeclarationSyntax or StructDeclarationSyntax); + var typeName = parentType switch + { + StructDeclarationSyntax t => t.Identifier.Text, + RecordDeclarationSyntax t => t.Identifier.Text, + TypeDeclarationSyntax t => t.Identifier.Text, + _ => "UNKNOWN", + }; + + var methodName = methodDeclaration.Identifier.Text; + + var catchDeclaration = SyntaxFactory.CatchDeclaration(SyntaxFactory.IdentifierName("Exception"), SyntaxFactory.Identifier("ex")); + var logExpression = SyntaxFactory.ExpressionStatement( + SyntaxFactory.ParseExpression($$"""IastModule.Log.Error(ex, $"Error invoking {nameof({{typeName}})}.{nameof({{methodName}})}")""")); + + var catchSyntax = SyntaxFactory.CatchClause() + .WithDeclaration(catchDeclaration) + .WithBlock(SyntaxFactory.Block(logExpression)); + + var updatedTryCatch = tryCatch.AddCatches(catchSyntax); + var newBody = SyntaxFactory.Block(localDeclaration, updatedTryCatch, returnSyntax) + .WithAdditionalAnnotations(Formatter.Annotation); + + var newMethodDeclaration = methodDeclaration.WithBody(newBody); + + // replace the syntax and return updated document + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + root = root!.ReplaceNode(methodDeclaration, newMethodDeclaration); + return document.WithSyntaxRoot(root); + } +} diff --git a/tracer/src/Datadog.Trace/Generated/net461/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs b/tracer/src/Datadog.Trace/Generated/net461/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs index 1041a3f633ca..5e1e1e8f9784 100644 --- a/tracer/src/Datadog.Trace/Generated/net461/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs +++ b/tracer/src/Datadog.Trace/Generated/net461/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs @@ -422,8 +422,7 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Concat(System.Object,System.Object,System.Object,System.Object)\",\"\",[0],[False],[None],Default,[])] Concat(System.Object,System.Object,System.Object,System.Object)", " [AspectMethodReplace(\"System.String::Concat(System.String[])\",\"\",[0],[False],[None],Default,[])] Concat(System.String[])", " [AspectMethodReplace(\"System.String::Concat(System.Object[])\",\"\",[0],[False],[None],Default,[])] Concat(System.Object[])", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat2(System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::Substring(System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32)", " [AspectMethodReplace(\"System.String::Substring(System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32,System.Int32)", " [AspectMethodReplace(\"System.String::ToCharArray()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToCharArray(System.String)", @@ -431,8 +430,7 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Join(System.String,System.String[],System.Int32,System.Int32)\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.String[],System.Int32,System.Int32)", " [AspectMethodReplace(\"System.String::Join(System.String,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Object[])", " [AspectMethodReplace(\"System.String::Join(System.String,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.String[])", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::ToUpper()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String)", " [AspectMethodReplace(\"System.String::ToUpper(System.Globalization.CultureInfo)\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String,System.Globalization.CultureInfo)", " [AspectMethodReplace(\"System.String::ToUpperInvariant()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpperInvariant(System.String)", diff --git a/tracer/src/Datadog.Trace/Generated/net6.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs b/tracer/src/Datadog.Trace/Generated/net6.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs index a218dc456b99..a4588db8d23f 100644 --- a/tracer/src/Datadog.Trace/Generated/net6.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs +++ b/tracer/src/Datadog.Trace/Generated/net6.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs @@ -460,8 +460,7 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Concat(System.String,System.String,System.String,System.String)\",\"\",[0],[False],[StringLiterals],Default,[])] Concat(System.String,System.String,System.String,System.String)", " [AspectMethodReplace(\"System.String::Concat(System.String[])\",\"\",[0],[False],[None],Default,[])] Concat(System.String[])", " [AspectMethodReplace(\"System.String::Concat(System.Object[])\",\"\",[0],[False],[None],Default,[])] Concat(System.Object[])", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat2(System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::Substring(System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32)", " [AspectMethodReplace(\"System.String::Substring(System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32,System.Int32)", " [AspectMethodReplace(\"System.String::ToCharArray()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToCharArray(System.String)", @@ -470,11 +469,9 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Join(System.Char,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.String[])", " [AspectMethodReplace(\"System.String::Join(System.Char,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.Object[])", " [AspectMethodReplace(\"System.String::Join(System.Char,System.String[],System.Int32,System.Int32)\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.String[],System.Int32,System.Int32)", -" [AspectMethodReplace(\"System.String::Join(System.Char,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.Collections.IEnumerable)", " [AspectMethodReplace(\"System.String::Join(System.String,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Object[])", " [AspectMethodReplace(\"System.String::Join(System.String,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.String[])", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::ToUpper()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String)", " [AspectMethodReplace(\"System.String::ToUpper(System.Globalization.CultureInfo)\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String,System.Globalization.CultureInfo)", " [AspectMethodReplace(\"System.String::ToUpperInvariant()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpperInvariant(System.String)", @@ -562,8 +559,6 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.String,System.Object[])\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.String,System.Object[])", " [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.Char,System.String[])\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.Char,System.String[])", " [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.Char,System.Object[])\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.Char,System.Object[])", -" [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.Char,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.Char,System.Object)", -" [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.String,System.Object)", "[AspectClass(\"mscorlib,netstandard,System.Runtime\",[None],Sink,[ReflectionInjection])] Datadog.Trace.Iast.Aspects.ActivatorAspect", " [AspectMethodInsertBefore(\"System.Activator::CreateInstance(System.String,System.String)\",\"\",[1,0],[False,False],[None],Default,[])] ReflectionInjectionParam(System.String)", " [AspectMethodInsertBefore(\"System.Activator::CreateInstance(System.String,System.String,System.Object[])\",\"\",[2,1],[False,False],[None],Default,[])] ReflectionInjectionParam(System.String)", diff --git a/tracer/src/Datadog.Trace/Generated/netcoreapp3.1/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs b/tracer/src/Datadog.Trace/Generated/netcoreapp3.1/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs index 4a80425b467f..bde765f70c44 100644 --- a/tracer/src/Datadog.Trace/Generated/netcoreapp3.1/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs +++ b/tracer/src/Datadog.Trace/Generated/netcoreapp3.1/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs @@ -447,8 +447,7 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Concat(System.String,System.String,System.String,System.String)\",\"\",[0],[False],[StringLiterals],Default,[])] Concat(System.String,System.String,System.String,System.String)", " [AspectMethodReplace(\"System.String::Concat(System.String[])\",\"\",[0],[False],[None],Default,[])] Concat(System.String[])", " [AspectMethodReplace(\"System.String::Concat(System.Object[])\",\"\",[0],[False],[None],Default,[])] Concat(System.Object[])", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat2(System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::Substring(System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32)", " [AspectMethodReplace(\"System.String::Substring(System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32,System.Int32)", " [AspectMethodReplace(\"System.String::ToCharArray()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToCharArray(System.String)", @@ -457,11 +456,9 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Join(System.Char,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.String[])", " [AspectMethodReplace(\"System.String::Join(System.Char,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.Object[])", " [AspectMethodReplace(\"System.String::Join(System.Char,System.String[],System.Int32,System.Int32)\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.String[],System.Int32,System.Int32)", -" [AspectMethodReplace(\"System.String::Join(System.Char,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.Collections.IEnumerable)", " [AspectMethodReplace(\"System.String::Join(System.String,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Object[])", " [AspectMethodReplace(\"System.String::Join(System.String,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.String[])", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::ToUpper()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String)", " [AspectMethodReplace(\"System.String::ToUpper(System.Globalization.CultureInfo)\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String,System.Globalization.CultureInfo)", " [AspectMethodReplace(\"System.String::ToUpperInvariant()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpperInvariant(System.String)", @@ -549,8 +546,6 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.String,System.Object[])\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.String,System.Object[])", " [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.Char,System.String[])\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.Char,System.String[])", " [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.Char,System.Object[])\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.Char,System.Object[])", -" [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.Char,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.Char,System.Object)", -" [AspectMethodReplace(\"System.Text.StringBuilder::AppendJoin(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] AppendJoin(System.Text.StringBuilder,System.String,System.Object)", "[AspectClass(\"mscorlib,netstandard,System.Runtime\",[None],Sink,[ReflectionInjection])] Datadog.Trace.Iast.Aspects.ActivatorAspect", " [AspectMethodInsertBefore(\"System.Activator::CreateInstance(System.String,System.String)\",\"\",[1,0],[False,False],[None],Default,[])] ReflectionInjectionParam(System.String)", " [AspectMethodInsertBefore(\"System.Activator::CreateInstance(System.String,System.String,System.Object[])\",\"\",[2,1],[False,False],[None],Default,[])] ReflectionInjectionParam(System.String)", diff --git a/tracer/src/Datadog.Trace/Generated/netstandard2.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs b/tracer/src/Datadog.Trace/Generated/netstandard2.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs index b78d5a119485..eff6b126162c 100644 --- a/tracer/src/Datadog.Trace/Generated/netstandard2.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs +++ b/tracer/src/Datadog.Trace/Generated/netstandard2.0/Datadog.Trace.SourceGenerators/AspectsDefinitionsGenerator/AspectsDefinitions.g.cs @@ -433,21 +433,15 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Concat(System.String,System.String,System.String,System.String)\",\"\",[0],[False],[StringLiterals],Default,[])] Concat(System.String,System.String,System.String,System.String)", " [AspectMethodReplace(\"System.String::Concat(System.String[])\",\"\",[0],[False],[None],Default,[])] Concat(System.String[])", " [AspectMethodReplace(\"System.String::Concat(System.Object[])\",\"\",[0],[False],[None],Default,[])] Concat(System.Object[])", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat2(System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Concat(System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Concat(System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::Substring(System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32)", " [AspectMethodReplace(\"System.String::Substring(System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Substring(System.String,System.Int32,System.Int32)", " [AspectMethodReplace(\"System.String::ToCharArray()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToCharArray(System.String)", " [AspectMethodReplace(\"System.String::ToCharArray(System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToCharArray(System.String,System.Int32,System.Int32)", " [AspectMethodReplace(\"System.String::Join(System.String,System.String[],System.Int32,System.Int32)\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.String[],System.Int32,System.Int32)", -" [AspectMethodReplace(\"System.String::Join(System.Char,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.String[])", -" [AspectMethodReplace(\"System.String::Join(System.Char,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.Object[])", -" [AspectMethodReplace(\"System.String::Join(System.Char,System.String[],System.Int32,System.Int32)\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.String[],System.Int32,System.Int32)", -" [AspectMethodReplace(\"System.String::Join(System.Char,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.Char,System.Collections.IEnumerable)", " [AspectMethodReplace(\"System.String::Join(System.String,System.Object[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Object[])", " [AspectMethodReplace(\"System.String::Join(System.String,System.String[])\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.String[])", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.IEnumerable)", -" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] Join(System.String,System.Collections.IEnumerable)", +" [AspectMethodReplace(\"System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)\",\"\",[0],[False],[None],Default,[])] JoinString(System.String,System.Collections.Generic.IEnumerable)", " [AspectMethodReplace(\"System.String::ToUpper()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String)", " [AspectMethodReplace(\"System.String::ToUpper(System.Globalization.CultureInfo)\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpper(System.String,System.Globalization.CultureInfo)", " [AspectMethodReplace(\"System.String::ToUpperInvariant()\",\"\",[0],[False],[StringLiteral_0],Default,[])] ToUpperInvariant(System.String)", @@ -477,10 +471,6 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.String::Split(System.Char[],System.Int32,System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.Char[],System.Int32,System.StringSplitOptions)", " [AspectMethodReplace(\"System.String::Split(System.String[],System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.String[],System.StringSplitOptions)", " [AspectMethodReplace(\"System.String::Split(System.String[],System.Int32,System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.String[],System.Int32,System.StringSplitOptions)", -" [AspectMethodReplace(\"System.String::Split(System.String,System.Int32,System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.String,System.Int32,System.StringSplitOptions)", -" [AspectMethodReplace(\"System.String::Split(System.String,System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.String,System.StringSplitOptions)", -" [AspectMethodReplace(\"System.String::Split(System.Char,System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.Char,System.StringSplitOptions)", -" [AspectMethodReplace(\"System.String::Split(System.Char,System.Int32,System.StringSplitOptions)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Split(System.String,System.Char,System.Int32,System.StringSplitOptions)", " [AspectMethodReplace(\"System.String::Copy(System.String)\",\"\",[0],[False],[StringLiteral_0],Default,[])] Copy(System.String)", "[AspectClass(\"mscorlib,netstandard,System.Runtime\",[None],Propagation,[])] Datadog.Trace.Iast.Aspects.System.Text.StringBuilderAspects", " [AspectCtorReplace(\"System.Text.StringBuilder::.ctor(System.String)\",\"\",[0],[False],[StringLiteral_1],Default,[])] Init(System.String)", @@ -491,7 +481,6 @@ internal static partial class AspectDefinitions " [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.String)\",\"\",[0],[False],[StringLiteral_1],Default,[])] Append(System.Text.StringBuilder,System.String)", " [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.Text.StringBuilder)\",\"\",[0],[False],[None],Default,[])] Append(System.Text.StringBuilder,System.Text.StringBuilder)", " [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.String,System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_1],Default,[])] Append(System.Text.StringBuilder,System.String,System.Int32,System.Int32)", -" [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.Text.StringBuilder,System.Int32,System.Int32)\",\"\",[0],[False],[StringLiteral_1],Default,[])] Append(System.Text.StringBuilder,System.Text.StringBuilder,System.Int32,System.Int32)", " [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.Char[],System.Int32,System.Int32)\",\"\",[0],[False],[None],Default,[])] Append(System.Text.StringBuilder,System.Char[],System.Int32,System.Int32)", " [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.Object)\",\"\",[0],[False],[None],Default,[])] Append(System.Text.StringBuilder,System.Object)", " [AspectMethodReplace(\"System.Text.StringBuilder::Append(System.Char[])\",\"\",[0],[False],[None],Default,[])] Append(System.Text.StringBuilder,System.Char[])", diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Net/WebUtilityAspect.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Net/WebUtilityAspect.cs index f88d2e0025d2..b3dbe86d0619 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Net/WebUtilityAspect.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Net/WebUtilityAspect.cs @@ -26,6 +26,19 @@ public class WebUtilityAspect [AspectMethodReplace("System.Net.WebUtility::HtmlEncode(System.String)")] public static string? Review(string? parameter) { - return IastModule.OnXssEscape(parameter); + var result = WebUtility.HtmlEncode(parameter); + try + { + if (parameter is not null && result is not null) + { + return IastModule.OnXssEscape(parameter, result); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(WebUtilityAspect)}.{nameof(Review)}"); + } + + return result; } } diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Security.Cryptography/SymmetricAlgorithmAspect.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Security.Cryptography/SymmetricAlgorithmAspect.cs index 0971bda04518..a6296465fa6a 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Security.Cryptography/SymmetricAlgorithmAspect.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Security.Cryptography/SymmetricAlgorithmAspect.cs @@ -44,7 +44,15 @@ private static void ProcessCipherClassCreation(SymmetricAlgorithm target) public static DESCryptoServiceProvider InitDES() { var target = new DESCryptoServiceProvider(); - ProcessCipherClassCreation(target); + try + { + ProcessCipherClassCreation(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(SymmetricAlgorithmAspect)}.{nameof(InitDES)}"); + } + return target; } @@ -56,7 +64,15 @@ public static DESCryptoServiceProvider InitDES() public static RC2CryptoServiceProvider InitRC2() { var target = new RC2CryptoServiceProvider(); - ProcessCipherClassCreation(target); + try + { + ProcessCipherClassCreation(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(SymmetricAlgorithmAspect)}.{nameof(InitRC2)}"); + } + return target; } @@ -68,7 +84,15 @@ public static RC2CryptoServiceProvider InitRC2() public static TripleDESCryptoServiceProvider InitTripleDES() { var target = new TripleDESCryptoServiceProvider(); - ProcessCipherClassCreation(target); + try + { + ProcessCipherClassCreation(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(SymmetricAlgorithmAspect)}.{nameof(InitTripleDES)}"); + } + return target; } @@ -80,7 +104,15 @@ public static TripleDESCryptoServiceProvider InitTripleDES() public static RijndaelManaged InitRijndaelManaged() { var target = new RijndaelManaged(); - ProcessCipherClassCreation(target); + try + { + ProcessCipherClassCreation(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(SymmetricAlgorithmAspect)}.{nameof(InitRijndaelManaged)}"); + } + return target; } @@ -92,7 +124,15 @@ public static RijndaelManaged InitRijndaelManaged() public static AesCryptoServiceProvider InitAesCryptoServiceProvider() { var target = new AesCryptoServiceProvider(); - ProcessCipherClassCreation(target); + try + { + ProcessCipherClassCreation(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(SymmetricAlgorithmAspect)}.{nameof(InitAesCryptoServiceProvider)}"); + } + return target; } diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Text.Json/JsonDocumentAspects.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Text.Json/JsonDocumentAspects.cs index 1d78e90ec24a..74f390f0b1e3 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Text.Json/JsonDocumentAspects.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Text.Json/JsonDocumentAspects.cs @@ -54,6 +54,7 @@ public static object Parse(string json, JsonDocumentOptions options) /// the string result [AspectMethodReplace("System.Text.Json.JsonElement::GetString()", [0], [true])] public static string? GetString(object target) +#pragma warning disable DD0005 // Function is already safe where needed { IJsonElement? element; try @@ -84,6 +85,7 @@ public static object Parse(string json, JsonDocumentOptions options) return str; } +#pragma warning restore DD0005 /// /// GetRawText method aspect @@ -93,6 +95,7 @@ public static object Parse(string json, JsonDocumentOptions options) /// the raw string result [AspectMethodReplace("System.Text.Json.JsonElement::GetRawText()", [0], [true])] public static string? GetRawText(object target) +#pragma warning disable DD0005 // Function is already safe where needed { IJsonElement? element; try @@ -123,6 +126,7 @@ public static object Parse(string json, JsonDocumentOptions options) return str; } +#pragma warning restore DD0005 private static void TaintJsonElements(string json, JsonDocument doc) { diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Text/StringBuilderAspects.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Text/StringBuilderAspects.cs index 1068f3535e7c..55c43d151d72 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Text/StringBuilderAspects.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Text/StringBuilderAspects.cs @@ -30,7 +30,15 @@ public class StringBuilderAspects public static StringBuilder Init(string? value) { var result = new StringBuilder(value); - PropagationModuleImpl.PropagateTaint(value, result); + try + { + PropagationModuleImpl.PropagateTaint(value, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Init)}"); + } + return result; } @@ -42,7 +50,15 @@ public static StringBuilder Init(string? value) public static StringBuilder Init(string? value, int capacity) { var result = new StringBuilder(value, capacity); - PropagationModuleImpl.PropagateTaint(value, result); + try + { + PropagationModuleImpl.PropagateTaint(value, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Init)}"); + } + return result; } @@ -56,7 +72,15 @@ public static StringBuilder Init(string? value, int capacity) public static StringBuilder Init(string? value, int startIndex, int length, int capacity) { var result = new StringBuilder(value, startIndex, length, capacity); - StringBuilderModuleImpl.OnStringBuilderSubSequence(value, startIndex, length, result); + try + { + StringBuilderModuleImpl.OnStringBuilderSubSequence(value, startIndex, length, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Init)}"); + } + return result; } @@ -66,13 +90,18 @@ public static StringBuilder Init(string? value, int startIndex, int length, int [AspectMethodReplace("System.Object::ToString()", "System.Text.StringBuilder")] public static string? ToString(object? target) { - // We want the null reference exception to be launched here if target is null var result = target!.ToString(); - - if (target is StringBuilder) + try { - PropagationModuleImpl.PropagateTaint(target, result); - PropagationModuleImpl.FixRangesIfNeeded(result); + if (target is StringBuilder) + { + PropagationModuleImpl.PropagateTaint(target, result); + PropagationModuleImpl.FixRangesIfNeeded(result); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(ToString)}"); } return result; @@ -86,10 +115,17 @@ public static StringBuilder Init(string? value, int startIndex, int length, int [AspectMethodReplace("System.Text.StringBuilder::ToString(System.Int32,System.Int32)")] public static string ToString(StringBuilder? target, int startIndex, int length) { - // We want the null reference exception to be launched here if target is null var result = target!.ToString(startIndex, length); - PropagationModuleImpl.OnStringSubSequence(target, startIndex, result, result.Length); - PropagationModuleImpl.FixRangesIfNeeded(result); + try + { + PropagationModuleImpl.OnStringSubSequence(target, startIndex, result, result.Length); + PropagationModuleImpl.FixRangesIfNeeded(result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(ToString)}"); + } + return result; } @@ -100,11 +136,22 @@ public static string ToString(StringBuilder? target, int startIndex, int length) [AspectMethodReplace("System.Text.StringBuilder::Append(System.String)", AspectFilter.StringLiteral_1)] public static StringBuilder Append(StringBuilder? target, string? value) { - var initialLength = target?.Length ?? 0; - var length = value?.Length ?? 0; - // We want the null reference exception to be launched here if target is null var result = target!.Append(value); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + try + { + if (target is not null && value is not null) + { + var length = value.Length; + var initialLength = target.Length - length; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); + } + + return result; } #if !NETFRAMEWORK @@ -115,11 +162,22 @@ public static StringBuilder Append(StringBuilder? target, string? value) [AspectMethodReplace("System.Text.StringBuilder::Append(System.Text.StringBuilder)")] public static StringBuilder Append(StringBuilder? target, StringBuilder? value) { - var initialLength = target?.Length ?? 0; - var length = value?.Length ?? 0; - // We want the null reference exception to be launched here if target is null var result = target!.Append(value); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + try + { + if (target is not null && value is not null) + { + var length = value.Length; + var initialLength = target.Length - length; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); + } + + return result; } #endif @@ -132,13 +190,24 @@ public static StringBuilder Append(StringBuilder? target, StringBuilder? value) [AspectMethodReplace("System.Text.StringBuilder::Append(System.String,System.Int32,System.Int32)", AspectFilter.StringLiteral_1)] public static StringBuilder Append(StringBuilder? target, string? value, int startIndex, int count) { - var initialLength = target?.Length ?? 0; - // We want the null reference exception to be launched here if target is null var result = target!.Append(value, startIndex, count); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value?.Length ?? 0, startIndex, count); + try + { + if (target is not null && value is not null) + { + var initialLength = target.Length - count; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value.Length, startIndex, count); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); + } + + return result; } -#if !NETFRAMEWORK +#if NETCOREAPP /// StringBuilder.Append aspect /// StringBuilder instance /// string parameter @@ -148,32 +217,48 @@ public static StringBuilder Append(StringBuilder? target, string? value, int sta [AspectMethodReplace("System.Text.StringBuilder::Append(System.Text.StringBuilder,System.Int32,System.Int32)", AspectFilter.StringLiteral_1)] public static StringBuilder Append(StringBuilder? target, StringBuilder? value, int startIndex, int count) { - var initialLength = target?.Length ?? 0; - // We want the null reference exception to be launched here if target is null - // netcore2.1 defines this overload, but not netstandard, so we have to call ToString() -#if NETSTANDARD - var result = target!.Append(value?.ToString(), startIndex, count); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value?.Length ?? 0, startIndex, count); -#else var result = target!.Append(value, startIndex, count); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value?.Length ?? 0, startIndex, count); -#endif + try + { + if (target is not null && value is not null) + { + var initialLength = target.Length - count; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value.Length, startIndex, count); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); + } + + return result; } #endif - /// StringBuilder.Append aspect - /// StringBuilder instance - /// string parameter - /// startIndex parameter - /// charCount parameter - /// instance.Append() + /// StringBuilder.Append aspect + /// StringBuilder instance + /// string parameter + /// startIndex parameter + /// charCount parameter + /// instance.Append() [AspectMethodReplace("System.Text.StringBuilder::Append(System.Char[],System.Int32,System.Int32)")] public static StringBuilder Append(StringBuilder? target, char[]? value, int startIndex, int charCount) { - var initialLength = target?.Length ?? 0; - // We want the null reference exception to be launched here if target is null var result = target!.Append(value, startIndex, charCount); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value?.Length ?? 0, startIndex, charCount); + try + { + if (target is not null && value is not null) + { + var initialLength = target.Length - charCount; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, value.Length, startIndex, charCount); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); + } + + return result; } /// StringBuilder.Append aspect @@ -183,24 +268,34 @@ public static StringBuilder Append(StringBuilder? target, char[]? value, int sta [AspectMethodReplace("System.Text.StringBuilder::Append(System.Object)")] public static StringBuilder Append(StringBuilder? target, object? value) { - var initialLength = target?.Length ?? 0; - - object? valueObject; - int length; - if (value is StringBuilder valueStringBuilder) + var result = target!.Append(value); + try { - valueObject = valueStringBuilder; - length = valueStringBuilder!.Length; + if (target is not null && value is not null) + { + object? valueObject; + int length; + if (value is StringBuilder valueStringBuilder) + { + valueObject = valueStringBuilder; + length = valueStringBuilder!.Length; + } + else + { + valueObject = value?.ToString(); + length = (valueObject as string)?.Length ?? 0; + } + + var initialLength = target.Length - length; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, valueObject, length, 0, length); + } } - else + catch (Exception ex) { - valueObject = value?.ToString(); - length = (valueObject as string)?.Length ?? 0; + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); } - // We want the null reference exception to be launched here if target is null - var result = target!.Append(value); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, valueObject, length, 0, length); + return result; } /// StringBuilder.Append aspect @@ -210,12 +305,22 @@ public static StringBuilder Append(StringBuilder? target, object? value) [AspectMethodReplace("System.Text.StringBuilder::Append(System.Char[])")] public static StringBuilder Append(StringBuilder? target, char[]? value) { - var initialLength = target?.Length ?? 0; - var length = value?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Append(value); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + try + { + if (target is not null && value is not null) + { + var length = value.Length; + var initialLength = target.Length - length; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Append)}"); + } + + return result; } /// StringBuilder.AppendLine aspect @@ -225,12 +330,23 @@ public static StringBuilder Append(StringBuilder? target, char[]? value) [AspectMethodReplace("System.Text.StringBuilder::AppendLine(System.String)", AspectFilter.StringLiteral_1)] public static StringBuilder AppendLine(StringBuilder? target, string? value) { - var initialLength = target?.Length ?? 0; - var length = value?.Length ?? 0; - // We do not take into account the endline char because it is not tainted - // We want the null reference exception to be launched here if target is null var result = target!.AppendLine(value); - return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + try + { + // We do not take into account the endline char because it is not tainted + if (target is not null && value is not null) + { + var length = value.Length; + var initialLength = target.Length - length - Environment.NewLine.Length; + return StringBuilderModuleImpl.OnStringBuilderAppend(result, initialLength, value, length, 0, length); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendLine)}"); + } + + return result; } /// StringBuilder.AppendFormat aspect @@ -241,9 +357,16 @@ public static StringBuilder AppendLine(StringBuilder? target, string? value) [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.String,System.Object)")] public static StringBuilder AppendFormat(StringBuilder? target, string? format, object? arg0) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(format!, arg0); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -256,9 +379,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, string? format, [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.String,System.Object,System.Object)")] public static StringBuilder AppendFormat(StringBuilder? target, string? format, object? arg0, object? arg1) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(format!, arg0, arg1); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -272,9 +402,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, string? format, [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.String,System.Object,System.Object,System.Object)")] public static StringBuilder AppendFormat(StringBuilder? target, string? format, object? arg0, object? arg1, object? arg2) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(format!, arg0, arg1, arg2); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1, arg2); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1, arg2); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -286,9 +423,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, string? format, [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.String,System.Object[])")] public static StringBuilder AppendFormat(StringBuilder? target, string? format, object[]? args) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(format!, args!); - StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, format, args); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, format, args); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -301,9 +445,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, string? format, [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.IFormatProvider,System.String,System.Object)")] public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? provider, string? format, object? arg0) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(provider, format!, arg0); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -317,9 +468,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.IFormatProvider,System.String,System.Object,System.Object)")] public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? provider, string? format, object? arg0, object? arg1) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(provider, format!, arg0, arg1); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -334,9 +492,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.IFormatProvider,System.String,System.Object,System.Object,System.Object)")] public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? provider, string? format, object? arg0, object? arg1, object? arg2) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(provider, format!, arg0, arg1, arg2); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1, arg2); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, format, arg0, arg1, arg2); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -349,9 +514,16 @@ public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? [AspectMethodReplace("System.Text.StringBuilder::AppendFormat(System.IFormatProvider,System.String,System.Object[])")] public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? provider, string? format, object[]? args) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendFormat(provider, format!, args!); - StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, format, args); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, format, args); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendFormat)}"); + } + return result; } @@ -364,9 +536,15 @@ public static StringBuilder AppendFormat(StringBuilder? target, IFormatProvider? [AspectMethodReplace("System.Text.StringBuilder::CopyTo(System.Int32,System.Char[],System.Int32,System.Int32)")] public static void CopyTo(StringBuilder? target, int sourceIndex, char[]? destination, int destinationIndex, int count) { - // We want the null reference exception to be launched here if target is null target!.CopyTo(sourceIndex, destination!, destinationIndex, count); - StringBuilderModuleImpl.FullTaintIfAnyTainted(destination, target); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(destination, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(CopyTo)}"); + } } /// StringBuilder.Insert aspect @@ -377,11 +555,20 @@ public static void CopyTo(StringBuilder? target, int sourceIndex, char[]? destin [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.String)")] public static StringBuilder Insert(StringBuilder? target, int index, string? value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null && value is not null) + { + var previousLength = target.Length - value.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -394,11 +581,20 @@ public static StringBuilder Insert(StringBuilder? target, int index, string? val [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.String,System.Int32)")] public static StringBuilder Insert(StringBuilder? target, int index, string? value, int count) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value, count); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value, count); + try + { + if (target is not null && value is not null && count > 0) + { + var previousLength = target.Length - (value.Length * count); + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value, count); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -410,11 +606,20 @@ public static StringBuilder Insert(StringBuilder? target, int index, string? val [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Char)")] public static StringBuilder Insert(StringBuilder? target, int index, char value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var previousLength = target.Length - 1; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -426,11 +631,20 @@ public static StringBuilder Insert(StringBuilder? target, int index, char value) [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Char[])")] public static StringBuilder Insert(StringBuilder? target, int index, char[]? value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null && value is not null) + { + var previousLength = target.Length - value.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -444,11 +658,20 @@ public static StringBuilder Insert(StringBuilder? target, int index, char[]? val [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Char[],System.Int32,System.Int32)")] public static StringBuilder Insert(StringBuilder? target, int index, char[]? value, int startIndex, int charCount) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value, startIndex, charCount); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value, 1, startIndex, charCount); + try + { + if (target is not null && value is not null) + { + var previousLength = target.Length - charCount; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value, 1, startIndex, charCount); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -460,11 +683,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, char[]? val [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Int32)")] public static StringBuilder Insert(StringBuilder? target, int index, int value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -476,11 +709,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, int value) [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Int64)")] public static StringBuilder Insert(StringBuilder? target, int index, long value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -492,11 +735,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, long value) [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Single)")] public static StringBuilder Insert(StringBuilder? target, int index, float value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -508,11 +761,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, float value [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Double)")] public static StringBuilder Insert(StringBuilder? target, int index, double value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -524,11 +787,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, double valu [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Decimal)")] public static StringBuilder Insert(StringBuilder? target, int index, decimal value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -540,11 +813,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, decimal val [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.UInt16)")] public static StringBuilder Insert(StringBuilder? target, int index, ushort value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -556,11 +839,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, ushort valu [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.UInt32)")] public static StringBuilder Insert(StringBuilder? target, int index, uint value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -572,11 +865,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, uint value) [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.UInt64)")] public static StringBuilder Insert(StringBuilder? target, int index, ulong value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -588,11 +891,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, ulong value [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Boolean)")] public static StringBuilder Insert(StringBuilder? target, int index, bool value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -604,11 +917,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, bool value) [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.SByte)")] public static StringBuilder Insert(StringBuilder? target, int index, sbyte value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -620,11 +943,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, sbyte value [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Byte)")] public static StringBuilder Insert(StringBuilder? target, int index, byte value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -636,11 +969,21 @@ public static StringBuilder Insert(StringBuilder? target, int index, byte value) [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Int16)")] public static StringBuilder Insert(StringBuilder? target, int index, short value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -650,13 +993,23 @@ public static StringBuilder Insert(StringBuilder? target, int index, short value /// The object to insert. /// The modified StringBuilder instance. [AspectMethodReplace("System.Text.StringBuilder::Insert(System.Int32,System.Object)")] - public static StringBuilder Insert(StringBuilder? target, int index, object value) + public static StringBuilder Insert(StringBuilder? target, int index, object? value) { - var previousLength = target?.Length ?? 0; - - // We want the null reference exception to be launched here if target is null var result = target!.Insert(index, value); - StringBuilderModuleImpl.OnStringBuilderInsert(target, previousLength, index, value); + try + { + if (target is not null && value is not null) + { + var val = value.ToString(); + var previousLength = target.Length - val!.Length; + StringBuilderModuleImpl.OnStringBuilderInsert(target!, previousLength, index, value); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Insert)}"); + } + return result; } @@ -668,9 +1021,16 @@ public static StringBuilder Insert(StringBuilder? target, int index, object valu [AspectMethodReplace("System.Text.StringBuilder::Remove(System.Int32,System.Int32)")] public static StringBuilder Remove(StringBuilder? target, int startIndex, int length) { - // We want the null reference exception to be launched here if target is null var result = target!.Remove(startIndex, length); - PropagationModuleImpl.OnStringRemove(target, result, startIndex, startIndex + length); + try + { + PropagationModuleImpl.OnStringRemove(target, result, startIndex, startIndex + length); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Remove)}"); + } + return result; } @@ -682,9 +1042,16 @@ public static StringBuilder Remove(StringBuilder? target, int startIndex, int le [AspectMethodReplace("System.Text.StringBuilder::Replace(System.String,System.String)")] public static StringBuilder Replace(StringBuilder? target, string? oldValue, string? newValue) { - // We want the null reference exception to be launched here if target is null var result = target!.Replace(oldValue!, newValue); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, oldValue, newValue); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, oldValue, newValue); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Replace)}"); + } + return result; } @@ -698,9 +1065,16 @@ public static StringBuilder Replace(StringBuilder? target, string? oldValue, str [AspectMethodReplace("System.Text.StringBuilder::Replace(System.String,System.String,System.Int32,System.Int32)")] public static StringBuilder Replace(StringBuilder? target, string? oldValue, string? newValue, int startIndex, int count) { - // We want the null reference exception to be launched here if target is null var result = target!.Replace(oldValue!, newValue, startIndex, count); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target, oldValue, newValue); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target, oldValue, newValue); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Replace)}"); + } + return result; } @@ -712,9 +1086,16 @@ public static StringBuilder Replace(StringBuilder? target, string? oldValue, str [AspectMethodReplace("System.Text.StringBuilder::Replace(System.Char,System.Char)")] public static StringBuilder Replace(StringBuilder? target, char oldChar, char newChar) { - // We want the null reference exception to be launched here if target is null var result = target!.Replace(oldChar, newChar); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Replace)}"); + } + return result; } @@ -728,9 +1109,16 @@ public static StringBuilder Replace(StringBuilder? target, char oldChar, char ne [AspectMethodReplace("System.Text.StringBuilder::Replace(System.Char,System.Char,System.Int32,System.Int32)")] public static StringBuilder Replace(StringBuilder? target, char oldChar, char newChar, int startIndex, int count) { - // We want the null reference exception to be launched here if target is null var result = target!.Replace(oldChar, newChar, startIndex, count); - StringBuilderModuleImpl.FullTaintIfAnyTainted(target); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(Replace)}"); + } + return result; } @@ -740,9 +1128,15 @@ public static StringBuilder Replace(StringBuilder? target, char oldChar, char ne [AspectMethodReplace("System.Text.StringBuilder::set_Length(System.Int32)")] public static void SetLength(StringBuilder? target, int length) { - // We want the null reference exception to be launched here if target is null target!.Length = length; - StringBuilderModuleImpl.FullTaintIfAnyTainted(target); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTainted(target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(SetLength)}"); + } } #if NETCOREAPP3_1_OR_GREATER @@ -754,9 +1148,16 @@ public static void SetLength(StringBuilder? target, int length) [AspectMethodReplace("System.Text.StringBuilder::AppendJoin(System.String,System.String[])")] public static StringBuilder AppendJoin(StringBuilder? target, string? separator, string[]? values) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendJoin(separator, values!); - StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, separator, values); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, separator, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendJoin)}"); + } + return result; } @@ -768,9 +1169,16 @@ public static StringBuilder AppendJoin(StringBuilder? target, string? separator, [AspectMethodReplace("System.Text.StringBuilder::AppendJoin(System.String,System.Object[])")] public static StringBuilder AppendJoin(StringBuilder? target, string? separator, object[]? values) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendJoin(separator, values!); - StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, separator, values); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, separator, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendJoin)}"); + } + return result; } @@ -782,9 +1190,16 @@ public static StringBuilder AppendJoin(StringBuilder? target, string? separator, [AspectMethodReplace("System.Text.StringBuilder::AppendJoin(System.Char,System.String[])")] public static StringBuilder AppendJoin(StringBuilder? target, char separator, string[]? values) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendJoin(separator, values!); - StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, null, values); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, null, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendJoin)}"); + } + return result; } @@ -796,12 +1211,22 @@ public static StringBuilder AppendJoin(StringBuilder? target, char separator, st [AspectMethodReplace("System.Text.StringBuilder::AppendJoin(System.Char,System.Object[])")] public static StringBuilder AppendJoin(StringBuilder? target, char separator, object[]? values) { - // We want the null reference exception to be launched here if target is null var result = target!.AppendJoin(separator, values!); - StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, null, values); + try + { + StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, null, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringBuilderAspects)}.{nameof(AppendJoin)}"); + } + return result; } + // TODO : Add support for callsites with undefined generic params +/* + /// StringBuilder.AppendJoin aspect /// The StringBuilder instance. /// The character to use as a separator. @@ -889,5 +1314,6 @@ public static StringBuilder AppendJoin(StringBuilder? target, string? separator, StringBuilderModuleImpl.FullTaintIfAnyTaintedEnumerable(target, separator, valuesConverted); return result; } +*/ #endif } diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Web.Extensions/JavaScriptSerializerAspects.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Web.Extensions/JavaScriptSerializerAspects.cs index 91eea86c2e4f..423e3d100d7a 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Web.Extensions/JavaScriptSerializerAspects.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Web.Extensions/JavaScriptSerializerAspects.cs @@ -31,6 +31,7 @@ public class JavaScriptSerializerAspects /// The target url [AspectMethodReplace("System.Web.Script.Serialization.JavaScriptSerializer::DeserializeObject(System.String)")] public static object? DeserializeObject(object instance, string input) +#pragma warning disable DD0005 { IJavaScriptSerializer? serializer; try @@ -63,6 +64,7 @@ public class JavaScriptSerializerAspects return result; } +#pragma warning restore DD0005 private static void TaintObject(object obj, TaintedObjects taintedObjects) { diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpCookieAspect.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpCookieAspect.cs index f2392f38b251..f0c94566a455 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpCookieAspect.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpCookieAspect.cs @@ -6,6 +6,7 @@ #nullable enable +using System; using System.Web; using Datadog.Trace.Iast.Dataflow; using Datadog.Trace.Iast.Propagation; @@ -29,10 +30,16 @@ public class HttpCookieAspect public static string GetValue(HttpCookie cookie) { var value = cookie.Value; - - if (!string.IsNullOrEmpty(value)) + try + { + if (!string.IsNullOrEmpty(value)) + { + PropagationModuleImpl.AddTaintedSource(value, new Source(SourceType.CookieValue, cookie?.Name, value)); + } + } + catch (Exception ex) { - PropagationModuleImpl.AddTaintedSource(value, new Source(SourceType.CookieValue, cookie?.Name, value)); + IastModule.Log.Error(ex, $"Error invoking {nameof(HttpCookieAspect)}.{nameof(GetValue)}"); } return value; diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpUtilityAspect.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpUtilityAspect.cs index 9cd473e1c506..50ea2aa96f57 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpUtilityAspect.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System.Web/HttpUtilityAspect.cs @@ -26,6 +26,19 @@ public class HttpUtilityAspect [AspectMethodReplace("System.Web.HttpUtility::HtmlEncode(System.String)")] public static string? Review(string? parameter) { - return IastModule.OnXssEscape(parameter); + var result = WebUtility.HtmlEncode(parameter); + try + { + if (parameter is not null && result is not null) + { + return IastModule.OnXssEscape(parameter, result); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(HttpUtilityAspect)}.{nameof(Review)}"); + } + + return result; } } diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System/StringAspects.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System/StringAspects.cs index 2825c7e122e1..f1a6d17c0b50 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System/StringAspects.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System/StringAspects.cs @@ -31,7 +31,17 @@ public class StringAspects [AspectMethodReplace("System.String::Trim()", AspectFilter.StringLiteral_0)] public static string Trim(string target) { - return StringModuleImpl.OnStringTrim(target, target.Trim(), null, true, true); + var result = target.Trim(); + try + { + return StringModuleImpl.OnStringTrim(target, result, null, true, true); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Trim)}"); + } + + return result; } /// @@ -43,14 +53,24 @@ public static string Trim(string target) [AspectMethodReplace("System.String::Trim(System.Char[])", AspectFilter.StringLiteral_0)] public static string Trim(string target, char[] trimChars) { - if (trimChars != null && trimChars.Length > 0) + var result = target.Trim(trimChars); + try { - return StringModuleImpl.OnStringTrimArray(target, target.Trim(trimChars), trimChars, true, true); + if (trimChars != null && trimChars.Length > 0) + { + return StringModuleImpl.OnStringTrimArray(target, result, trimChars, true, true); + } + else + { + return StringModuleImpl.OnStringTrim(target, result, null, true, true); + } } - else + catch (Exception ex) { - return StringModuleImpl.OnStringTrim(target, target.Trim(trimChars), null, true, true); + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Trim)}"); } + + return result; } #if !NETFRAMEWORK @@ -63,7 +83,17 @@ public static string Trim(string target, char[] trimChars) [AspectMethodReplace("System.String::Trim(System.Char)", AspectFilter.StringLiteral_0)] public static string Trim(string target, char trimChar) { - return StringModuleImpl.OnStringTrim(target, target.Trim(trimChar), trimChar, true, true); + var result = target.Trim(trimChar); + try + { + return StringModuleImpl.OnStringTrim(target, result, trimChar, true, true); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Trim)}"); + } + + return result; } #endif @@ -76,14 +106,24 @@ public static string Trim(string target, char trimChar) [AspectMethodReplace("System.String::TrimStart(System.Char[])", AspectFilter.StringLiteral_0)] public static string TrimStart(string target, char[] trimChars) { - if (trimChars != null && trimChars.Length > 0) + var result = target.TrimStart(trimChars); + try { - return StringModuleImpl.OnStringTrimArray(target, target.TrimStart(trimChars), trimChars, true, false); + if (trimChars != null && trimChars.Length > 0) + { + return StringModuleImpl.OnStringTrimArray(target, result, trimChars, true, false); + } + else + { + return StringModuleImpl.OnStringTrim(target, result, null, true, false); + } } - else + catch (Exception ex) { - return StringModuleImpl.OnStringTrim(target, target.TrimStart(trimChars), null, true, false); + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(TrimStart)}"); } + + return result; } #if !NETFRAMEWORK @@ -96,7 +136,17 @@ public static string TrimStart(string target, char[] trimChars) [AspectMethodReplace("System.String::TrimStart(System.Char)", AspectFilter.StringLiteral_0)] public static string TrimStart(string target, char trimChar) { - return StringModuleImpl.OnStringTrim(target, target.TrimStart(trimChar), trimChar, true, false); + var result = target.TrimStart(trimChar); + try + { + return StringModuleImpl.OnStringTrim(target, result, trimChar, true, false); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(TrimStart)}"); + } + + return result; } /// @@ -107,7 +157,17 @@ public static string TrimStart(string target, char trimChar) [AspectMethodReplace("System.String::TrimStart()", AspectFilter.StringLiteral_0)] public static string TrimStart(string target) { - return StringModuleImpl.OnStringTrim(target, target.TrimStart(), null, true, false); + var result = target.TrimStart(); + try + { + return StringModuleImpl.OnStringTrim(target, result, null, true, false); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(TrimStart)}"); + } + + return result; } #endif @@ -120,14 +180,24 @@ public static string TrimStart(string target) [AspectMethodReplace("System.String::TrimEnd(System.Char[])", AspectFilter.StringLiteral_0)] public static string TrimEnd(string target, char[] trimChars) { - if (trimChars != null && trimChars.Length > 0) + var result = target.TrimEnd(trimChars); + try { - return StringModuleImpl.OnStringTrimArray(target, target.TrimEnd(trimChars), trimChars, false, true); + if (trimChars != null && trimChars.Length > 0) + { + return StringModuleImpl.OnStringTrimArray(target, result, trimChars, false, true); + } + else + { + return StringModuleImpl.OnStringTrim(target, result, null, false, true); + } } - else + catch (Exception ex) { - return StringModuleImpl.OnStringTrim(target, target.TrimEnd(trimChars), null, false, true); + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(TrimEnd)}"); } + + return result; } #if !NETFRAMEWORK @@ -140,7 +210,17 @@ public static string TrimEnd(string target, char[] trimChars) [AspectMethodReplace("System.String::TrimEnd(System.Char)", AspectFilter.StringLiteral_0)] public static string TrimEnd(string target, char trimChar) { - return StringModuleImpl.OnStringTrim(target, target.TrimEnd(trimChar), trimChar, false, true); + var result = target.TrimEnd(trimChar); + try + { + return StringModuleImpl.OnStringTrim(target, result, trimChar, false, true); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(TrimEnd)}"); + } + + return result; } /// @@ -151,7 +231,17 @@ public static string TrimEnd(string target, char trimChar) [AspectMethodReplace("System.String::TrimEnd()", AspectFilter.StringLiteral_0)] public static string TrimEnd(string target) { - return StringModuleImpl.OnStringTrim(target, target.TrimEnd(), null, false, true); + var result = target.TrimEnd(); + try + { + return StringModuleImpl.OnStringTrim(target, result, null, false, true); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(TrimEnd)}"); + } + + return result; } #endif @@ -164,7 +254,17 @@ public static string TrimEnd(string target) [AspectMethodReplace("System.String::Concat(System.String,System.String)", AspectFilter.StringLiterals_Any)] public static string Concat(string param1, string param2) { - return StringModuleImpl.OnStringConcat(param1, param2, string.Concat(param1, param2)); + var result = string.Concat(param1, param2); + try + { + return StringModuleImpl.OnStringConcat(param1, param2, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } /// @@ -176,7 +276,17 @@ public static string Concat(string param1, string param2) [AspectMethodReplace("System.String::Concat(System.String,System.String)", AspectFilter.StringLiteral_0)] public static string Concat_0(string param1, string param2) { - return StringModuleImpl.OnStringConcat(param1, param2, string.Concat(param1, param2), AspectFilter.StringLiteral_0); + var result = string.Concat(param1, param2); + try + { + return StringModuleImpl.OnStringConcat(param1, param2, result, AspectFilter.StringLiteral_0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat_0)}"); + } + + return result; } /// @@ -188,7 +298,17 @@ public static string Concat_0(string param1, string param2) [AspectMethodReplace("System.String::Concat(System.String,System.String)", AspectFilter.StringLiteral_1)] public static string Concat_1(string param1, string param2) { - return StringModuleImpl.OnStringConcat(param1, param2, string.Concat(param1, param2), AspectFilter.StringLiteral_1); + var result = string.Concat(param1, param2); + try + { + return StringModuleImpl.OnStringConcat(param1, param2, result, AspectFilter.StringLiteral_1); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat_1)}"); + } + + return result; } /// @@ -200,7 +320,17 @@ public static string Concat_1(string param1, string param2) [AspectMethodReplace("System.String::Concat(System.Object,System.Object)")] public static string Concat(object param1, object param2) { - return StringModuleImpl.OnStringConcat(param1?.ToString(), param2?.ToString(), string.Concat(param1, param2)); + var result = string.Concat(param1, param2); + try + { + return StringModuleImpl.OnStringConcat(param1?.ToString(), param2?.ToString(), result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } /// @@ -213,7 +343,17 @@ public static string Concat(object param1, object param2) [AspectMethodReplace("System.String::Concat(System.String,System.String,System.String)", AspectFilter.StringLiterals)] public static string Concat(string param1, string param2, string param3) { - return StringModuleImpl.OnStringConcat(new StringConcatParams(param1, param2, param3), string.Concat(param1, param2, param3)); + var result = string.Concat(param1, param2, param3); + try + { + return StringModuleImpl.OnStringConcat(new StringConcatParams(param1, param2, param3), result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } /// @@ -226,7 +366,17 @@ public static string Concat(string param1, string param2, string param3) [AspectMethodReplace("System.String::Concat(System.Object,System.Object,System.Object)")] public static string Concat(object param1, object param2, object param3) { - return StringModuleImpl.OnStringConcat(new StringConcatParams(param1?.ToString(), param2?.ToString(), param3?.ToString()), string.Concat(param1, param2, param3)); + var result = string.Concat(param1, param2, param3); + try + { + return StringModuleImpl.OnStringConcat(new StringConcatParams(param1?.ToString(), param2?.ToString(), param3?.ToString()), result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } /// @@ -240,7 +390,17 @@ public static string Concat(object param1, object param2, object param3) [AspectMethodReplace("System.String::Concat(System.String,System.String,System.String,System.String)", AspectFilter.StringLiterals)] public static string Concat(string param1, string param2, string param3, string param4) { - return StringModuleImpl.OnStringConcat(new StringConcatParams(param1, param2, param3, param4), string.Concat(param1, param2, param3, param4)); + var result = string.Concat(param1, param2, param3, param4); + try + { + return StringModuleImpl.OnStringConcat(new StringConcatParams(param1, param2, param3, param4), result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } #if NETFRAMEWORK @@ -255,7 +415,17 @@ public static string Concat(string param1, string param2, string param3, string [AspectMethodReplace("System.String::Concat(System.Object,System.Object,System.Object,System.Object)")] public static string Concat(object param1, object param2, object param3, object param4) { - return StringModuleImpl.OnStringConcat(new StringConcatParams(param1?.ToString(), param2?.ToString(), param3?.ToString(), param4?.ToString()), string.Concat(param1, param2, param3, param4)); + var result = string.Concat(param1, param2, param3, param4); + try + { + return StringModuleImpl.OnStringConcat(new StringConcatParams(param1?.ToString(), param2?.ToString(), param3?.ToString(), param4?.ToString()), result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } #endif @@ -267,7 +437,17 @@ public static string Concat(object param1, object param2, object param3, object [AspectMethodReplace("System.String::Concat(System.String[])")] public static string Concat(string[] values) { - return StringModuleImpl.OnStringConcat(values, string.Concat(values)); + var result = string.Concat(values); + try + { + return StringModuleImpl.OnStringConcat(values, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } + + return result; } /// @@ -278,19 +458,17 @@ public static string Concat(string[] values) [AspectMethodReplace("System.String::Concat(System.Object[])")] public static string Concat(object[] values) { - return StringModuleImpl.OnStringConcat(values, string.Concat(values)); - } + var result = string.Concat(values); + try + { + return StringModuleImpl.OnStringConcat(values, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); + } - /// - /// String.Concat aspect - /// - /// Parameters - /// String.Concat(values) - [AspectMethodReplace("System.String::Concat(System.Collections.Generic.IEnumerable`1)")] - public static string Concat(IEnumerable values) - { - var valuesConverted = values as IEnumerable; - return StringModuleImpl.OnStringConcat(valuesConverted, string.Concat(valuesConverted)); + return result; } /// @@ -298,36 +476,24 @@ public static string Concat(IEnumerable values) /// /// Parameters /// String.Concat(values) - [AspectMethodReplace("System.String::Concat(System.Collections.Generic.IEnumerable`1)")] - public static string Concat2(IEnumerable values) + [AspectMethodReplace("System.String::Concat(System.Collections.Generic.IEnumerable`1)")] + public static string Concat(IEnumerable values) { - if (values is null) - { - return string.Concat(values); - } - - var valuesConverted = values as IEnumerable; - if (valuesConverted != null) - { - return StringModuleImpl.OnStringConcat(valuesConverted, string.Concat(valuesConverted)); - } - - // We have a IEnumerable of structs or basic types. This is a corner case. - + var result = string.Concat(values); try { - valuesConverted = values.Cast(); + return StringModuleImpl.OnStringConcat(values, result); } - catch + catch (Exception ex) { - // This sould never happen. - Log.Warning("Cannot process values in System.String::Concat(System.Collections.Generic.IEnumerable`1)"); - return string.Concat(values); + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Concat)}"); } - return StringModuleImpl.OnStringConcat(values, string.Concat(valuesConverted)); + return result; } + // [AspectMethodReplace("System.String::Concat(System.Collections.Generic.IEnumerable`1)")] + /// /// String.Substring aspect /// @@ -337,7 +503,17 @@ public static string Concat2(IEnumerable values) [AspectMethodReplace("System.String::Substring(System.Int32)", AspectFilter.StringLiteral_0)] public static string Substring(string target, int startIndex) { - return StringModuleImpl.OnStringSubSequence(target, startIndex, target.Substring(startIndex)); + var result = target.Substring(startIndex); + try + { + return StringModuleImpl.OnStringSubSequence(target, startIndex, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Substring)}"); + } + + return result; } /// @@ -350,7 +526,17 @@ public static string Substring(string target, int startIndex) [AspectMethodReplace("System.String::Substring(System.Int32,System.Int32)", AspectFilter.StringLiteral_0)] public static string Substring(string target, int startIndex, int length) { - return StringModuleImpl.OnStringSubSequence(target, startIndex, target.Substring(startIndex, length)); + var result = target.Substring(startIndex, length); + try + { + return StringModuleImpl.OnStringSubSequence(target, startIndex, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Substring)}"); + } + + return result; } /// @@ -362,7 +548,15 @@ public static string Substring(string target, int startIndex, int length) public static char[] ToCharArray(string target) { var result = target.ToCharArray(); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToCharArray)}"); + } + return result; } @@ -376,7 +570,17 @@ public static char[] ToCharArray(string target) [AspectMethodReplace("System.String::ToCharArray(System.Int32,System.Int32)", AspectFilter.StringLiteral_0)] public static char[] ToCharArray(string target, int startIndex, int length) { - return StringModuleImpl.OnStringSubSequence(target, startIndex, target.ToCharArray(startIndex, length)); + var result = target.ToCharArray(startIndex, length); + try + { + return StringModuleImpl.OnStringSubSequence(target, startIndex, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToCharArray)}"); + } + + return result; } /// @@ -390,10 +594,20 @@ public static char[] ToCharArray(string target, int startIndex, int length) [AspectMethodReplace("System.String::Join(System.String,System.String[],System.Int32,System.Int32)")] public static string Join(string separator, string[] values, int startIndex, int count) { - return OnStringJoin(string.Join(separator, values, startIndex, count), separator, values, startIndex, count); + var result = string.Join(separator, values, startIndex, count); + try + { + return OnStringJoin(result, separator, values, startIndex, count); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); + } + + return result; } -#if NETSTANDARD || NETCOREAPP +#if NETCOREAPP /// /// String.Join aspect /// @@ -403,7 +617,17 @@ public static string Join(string separator, string[] values, int startIndex, int [AspectMethodReplace("System.String::Join(System.Char,System.String[])")] public static string Join(char separator, string[] values) { - return OnStringJoin(string.Join(separator.ToString(), values), values); + var result = string.Join(separator, values); + try + { + return OnStringJoin(result, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); + } + + return result; } /// @@ -415,7 +639,17 @@ public static string Join(char separator, string[] values) [AspectMethodReplace("System.String::Join(System.Char,System.Object[])")] public static string Join(char separator, object[] values) { - return Join(separator.ToString(), values); + var result = string.Join(separator, values); + try + { + return OnStringJoin(result, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); + } + + return result; } /// @@ -429,21 +663,24 @@ public static string Join(char separator, object[] values) [AspectMethodReplace("System.String::Join(System.Char,System.String[],System.Int32,System.Int32)")] public static string Join(char separator, string[] values, int startIndex, int count) { - return OnStringJoin(string.Join(separator.ToString(), values, startIndex, count), values, startIndex, count); - } + var result = string.Join(separator, values, startIndex, count); + try + { + return OnStringJoin(result, values, startIndex, count); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); + } - /// - /// String.Join aspect - /// - /// sparator - /// values to join - /// Join result - [AspectMethodReplace("System.String::Join(System.Char,System.Collections.Generic.IEnumerable`1)")] - public static string Join(char separator, IEnumerable values) - { - return Join(separator.ToString(), values); + return result; } + + // TODO : Add support for callsites with undefined generic params + // [AspectMethodReplace("System.String::Join(System.Char,System.Collections.Generic.IEnumerable`1)")] #endif + // TODO : Add support for callsites with undefined generic params + // [AspectMethodReplace("System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)")] /// /// String.Join aspect @@ -454,7 +691,17 @@ public static string Join(char separator, IEnumerable values) [AspectMethodReplace("System.String::Join(System.String,System.Object[])")] public static string Join(string separator, object[] values) { - return OnStringJoin(string.Join(separator, values), separator, values); + var result = string.Join(separator, values); + try + { + return OnStringJoin(result, separator, values); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); + } + + return result; } /// @@ -466,34 +713,17 @@ public static string Join(string separator, object[] values) [AspectMethodReplace("System.String::Join(System.String,System.String[])")] public static string Join(string separator, string[] values) { - return OnStringJoin(string.Join(separator, values), separator, values); - } - - /// - /// String.Join aspect - /// - /// sparator - /// values to join - /// Join result - [AspectMethodReplace("System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)")] - public static string JoinString(string separator, IEnumerable values) - { - if (values is null) - { - return OnStringJoin(string.Join(separator, values), separator, null); - } - - var valuesConverted = values as IEnumerable; - if (valuesConverted != null) + var result = string.Join(separator, values); + try { - return OnStringJoin(string.Join(separator, valuesConverted), separator, valuesConverted); + return OnStringJoin(result, separator, values); } - else + catch (Exception ex) { - // This should never happen - Log.Warning("Could not taint the string.join call in System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)"); - return string.Join(separator, values); + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); } + + return result; } /// @@ -502,33 +732,20 @@ public static string JoinString(string separator, IEnumerable values) /// sparator /// values to join /// Join result - [AspectMethodReplace("System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)")] - public static string Join(string separator, IEnumerable values) + [AspectMethodReplace("System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)")] + public static string JoinString(string separator, IEnumerable values) { - if (values is null) - { - return OnStringJoin(string.Join(separator, values), separator, null); - } - - var valuesConverted = values as IEnumerable; - if (valuesConverted != null) - { - return OnStringJoin(string.Join(separator, valuesConverted), separator, valuesConverted); - } - - // We have a IEnumerable of structs or basic types. This is a corner case. + var result = string.Join(separator, values); try { - valuesConverted = values.Cast(); + return OnStringJoin(result, separator, values); } - catch + catch (Exception ex) { - // This sould never happen, but just in case, we return the join... - Log.Warning("Could not taint the string.join call in System.String::Join(System.String,System.Collections.Generic.IEnumerable`1)"); - return string.Join(separator, values); + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Join)}"); } - return OnStringJoin(string.Join(separator, valuesConverted), separator, valuesConverted); + return result; } /// @@ -540,7 +757,15 @@ public static string Join(string separator, IEnumerable values) public static string ToUpper(string target) { var result = target.ToUpper(); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToUpper)}"); + } + return result; } @@ -554,7 +779,15 @@ public static string ToUpper(string target) public static string ToUpper(string target, global::System.Globalization.CultureInfo culture) { var result = target.ToUpper(culture); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToUpper)}"); + } + return result; } @@ -567,7 +800,15 @@ public static string ToUpper(string target, global::System.Globalization.Culture public static string ToUpperInvariant(string target) { var result = target.ToUpperInvariant(); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToUpperInvariant)}"); + } + return result; } @@ -580,7 +821,15 @@ public static string ToUpperInvariant(string target) public static string ToLower(string target) { var result = target.ToLower(); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToLower)}"); + } + return result; } @@ -594,7 +843,15 @@ public static string ToLower(string target) public static string ToLower(string target, global::System.Globalization.CultureInfo culture) { var result = target.ToLower(culture); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToLower)}"); + } + return result; } @@ -607,7 +864,15 @@ public static string ToLower(string target, global::System.Globalization.Culture public static string ToLowerInvariant(string target) { var result = target.ToLowerInvariant(); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(ToLowerInvariant)}"); + } + return result; } @@ -621,7 +886,15 @@ public static string ToLowerInvariant(string target) public static string Remove(string target, int startIndex) { string result = target.Remove(startIndex); - PropagationModuleImpl.OnStringRemove(target, result, startIndex, target.Length); + try + { + PropagationModuleImpl.OnStringRemove(target, result, startIndex, target.Length); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Remove)}"); + } + return result; } @@ -636,7 +909,15 @@ public static string Remove(string target, int startIndex) public static string Remove(string target, int startIndex, int count) { string result = target.Remove(startIndex, count); - PropagationModuleImpl.OnStringRemove(target, result, startIndex, startIndex + count); + try + { + PropagationModuleImpl.OnStringRemove(target, result, startIndex, startIndex + count); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Remove)}"); + } + return result; } @@ -651,7 +932,15 @@ public static string Remove(string target, int startIndex, int count) public static string Insert(string target, int startIndex, string value) { var result = target.Insert(startIndex, value); - OnStringInsert(target, startIndex, value, result); + try + { + OnStringInsert(target, startIndex, value, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Insert)}"); + } + return result; } @@ -665,7 +954,15 @@ public static string Insert(string target, int startIndex, string value) public static string PadLeft(string target, int totalWidth) { var result = target.PadLeft(totalWidth); - PropagationModuleImpl.PropagateTaint(target, result, (result?.Length - target?.Length) ?? 0); + try + { + PropagationModuleImpl.PropagateTaint(target, result, (result?.Length - target?.Length) ?? 0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(PadLeft)}"); + } + return result; } @@ -680,7 +977,15 @@ public static string PadLeft(string target, int totalWidth) public static string PadLeft(string target, int totalWidth, char paddingChar) { var result = target.PadLeft(totalWidth, paddingChar); - PropagationModuleImpl.PropagateTaint(target, result, (result?.Length - target?.Length) ?? 0); + try + { + PropagationModuleImpl.PropagateTaint(target, result, (result?.Length - target?.Length) ?? 0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(PadLeft)}"); + } + return result; } @@ -694,7 +999,15 @@ public static string PadLeft(string target, int totalWidth, char paddingChar) public static string PadRight(string target, int totalWidth) { var result = target.PadRight(totalWidth); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(PadRight)}"); + } + return result; } @@ -709,7 +1022,15 @@ public static string PadRight(string target, int totalWidth) public static string PadRight(string target, int totalWidth, char paddingChar) { var result = target.PadRight(totalWidth, paddingChar); - PropagationModuleImpl.PropagateTaint(target, result); + try + { + PropagationModuleImpl.PropagateTaint(target, result); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(PadRight)}"); + } + return result; } @@ -723,7 +1044,15 @@ public static string PadRight(string target, int totalWidth, char paddingChar) public static string Format(string format, object arg0) { var result = string.Format(format, arg0); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -738,7 +1067,15 @@ public static string Format(string format, object arg0) public static string Format(string format, object arg0, object arg1) { var result = string.Format(format, arg0, arg1); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -754,7 +1091,15 @@ public static string Format(string format, object arg0, object arg1) public static string Format(string format, object arg0, object arg1, object arg2) { var result = string.Format(format, arg0, arg1, arg2); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1, arg2); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1, arg2); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -768,7 +1113,15 @@ public static string Format(string format, object arg0, object arg1, object arg2 public static string Format(string format, object[] args) { var result = string.Format(format, args); - PropagationModuleImpl.PropagateResultWhenInputArrayTainted(result, format, args); + try + { + PropagationModuleImpl.PropagateResultWhenInputArrayTainted(result, format, args); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -783,7 +1136,15 @@ public static string Format(string format, object[] args) public static string Format(IFormatProvider provider, string format, object arg0) { var result = string.Format(provider, format, arg0); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -799,7 +1160,15 @@ public static string Format(IFormatProvider provider, string format, object arg0 public static string Format(IFormatProvider provider, string format, object arg0, object arg1) { var result = string.Format(provider, format, arg0, arg1); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -816,7 +1185,15 @@ public static string Format(IFormatProvider provider, string format, object arg0 public static string Format(IFormatProvider provider, string format, object arg0, object arg1, object arg2) { var result = string.Format(provider, format, arg0, arg1, arg2); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1, arg2); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, format, arg0, arg1, arg2); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -831,7 +1208,15 @@ public static string Format(IFormatProvider provider, string format, object arg0 public static string Format(IFormatProvider provider, string format, object[] args) { var result = string.Format(provider, format, args); - PropagationModuleImpl.PropagateResultWhenInputArrayTainted(result, format, args); + try + { + PropagationModuleImpl.PropagateResultWhenInputArrayTainted(result, format, args); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Format)}"); + } + return result; } @@ -849,7 +1234,15 @@ public static string Format(IFormatProvider provider, string format, object[] ar public static string Replace(string target, string oldValue, string newValue, bool ignore, CultureInfo culture) { var result = target.Replace(oldValue, newValue, ignore, culture); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target, oldValue, newValue); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target, oldValue, newValue); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Replace)}"); + } + return result; } @@ -865,7 +1258,15 @@ public static string Replace(string target, string oldValue, string newValue, bo public static string Replace(string target, string oldValue, string newValue, StringComparison comparison) { var result = target.Replace(oldValue, newValue, comparison); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target, oldValue, newValue); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target, oldValue, newValue); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Replace)}"); + } + return result; } #endif @@ -881,7 +1282,15 @@ public static string Replace(string target, string oldValue, string newValue, St public static string Replace(string target, char oldChar, char newChar) { var result = target.Replace(oldChar, newChar); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Replace)}"); + } + return result; } @@ -896,7 +1305,15 @@ public static string Replace(string target, char oldChar, char newChar) public static string Replace(string target, string oldValue, string newValue) { var result = target.Replace(oldValue, newValue); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target, oldValue, newValue); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target, oldValue, newValue); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Replace)}"); + } + return result; } @@ -910,7 +1327,15 @@ public static string Replace(string target, string oldValue, string newValue) public static string[] Split(string target, char[] separator) { var result = target.Split(separator); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -925,7 +1350,15 @@ public static string[] Split(string target, char[] separator) public static string[] Split(string target, char[] separator, int count) { var result = target.Split(separator, count); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -940,7 +1373,15 @@ public static string[] Split(string target, char[] separator, int count) public static string[] Split(string target, char[] separator, StringSplitOptions options) { var result = target.Split(separator, options); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -956,7 +1397,15 @@ public static string[] Split(string target, char[] separator, StringSplitOptions public static string[] Split(string target, char[] separator, int count, StringSplitOptions options) { var result = target.Split(separator, count, options); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -971,7 +1420,15 @@ public static string[] Split(string target, char[] separator, int count, StringS public static string[] Split(string target, string[] separator, StringSplitOptions options) { var result = target.Split(separator, options); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -987,11 +1444,20 @@ public static string[] Split(string target, string[] separator, StringSplitOptio public static string[] Split(string target, string[] separator, int count, StringSplitOptions options) { var result = target.Split(separator, count, options); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } -#if !NETFRAMEWORK +#if NETCOREAPP2_1_OR_GREATER + /// /// String.Split aspect /// @@ -1003,12 +1469,16 @@ public static string[] Split(string target, string[] separator, int count, Strin [AspectMethodReplace("System.String::Split(System.String,System.Int32,System.StringSplitOptions)", AspectFilter.StringLiteral_0)] public static string[] Split(string target, string separator, int count, StringSplitOptions options) { -#if NETSTANDARD - var result = target.Split(new string[] { separator }, count, options); -#else var result = target.Split(separator, count, options); -#endif - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -1022,12 +1492,16 @@ public static string[] Split(string target, string separator, int count, StringS [AspectMethodReplace("System.String::Split(System.String,System.StringSplitOptions)", AspectFilter.StringLiteral_0)] public static string[] Split(string target, string separator, StringSplitOptions options) { -#if NETSTANDARD - var result = target.Split(new string[] { separator }, options); -#else var result = target.Split(separator, options); -#endif - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -1041,12 +1515,16 @@ public static string[] Split(string target, string separator, StringSplitOptions [AspectMethodReplace("System.String::Split(System.Char,System.StringSplitOptions)", AspectFilter.StringLiteral_0)] public static string[] Split(string target, char separator, StringSplitOptions options) { -#if NETSTANDARD - var result = target.Split(new char[] { separator }, options); -#else var result = target.Split(separator, options); -#endif - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } @@ -1061,12 +1539,16 @@ public static string[] Split(string target, char separator, StringSplitOptions o [AspectMethodReplace("System.String::Split(System.Char,System.Int32,System.StringSplitOptions)", AspectFilter.StringLiteral_0)] public static string[] Split(string target, char separator, int count, StringSplitOptions options) { -#if NETSTANDARD - var result = target.Split(new char[] { separator }, count, options); -#else var result = target.Split(separator, count, options); -#endif - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Split)}"); + } + return result; } #endif @@ -1081,7 +1563,15 @@ public static string[] Split(string target, char separator, int count, StringSpl public static string Copy(string target) { var result = string.Copy(target); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, target); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(StringAspects)}.{nameof(Copy)}"); + } + return result; } #pragma warning restore CS0618 // Obsolete diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System/UriAspect.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System/UriAspect.cs index 364e55a9a986..eb3e43ba6ca1 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System/UriAspect.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System/UriAspect.cs @@ -26,7 +26,15 @@ public class UriAspect public static Uri Init(string uriBase) { var result = new Uri(uriBase); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } @@ -43,7 +51,15 @@ public static Uri Init(Uri uriBase, string uriText, bool escape) #pragma warning disable CS0618 // Type or member is obsolete var result = new Uri(uriBase, uriText, escape); #pragma warning restore CS0618 // Type or member is obsolete - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase.OriginalString, uriText); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase.OriginalString, uriText); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } @@ -57,7 +73,15 @@ public static Uri Init(Uri uriBase, string uriText, bool escape) public static Uri Init(Uri uriBase, string relativeUri) { var result = new Uri(uriBase, relativeUri); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase.OriginalString, relativeUri); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase.OriginalString, relativeUri); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } @@ -71,7 +95,15 @@ public static Uri Init(Uri uriBase, string relativeUri) public static Uri Init(Uri uriBase, Uri relativeUri) { var result = new Uri(uriBase, relativeUri); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase.OriginalString, relativeUri.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase.OriginalString, relativeUri.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } @@ -87,7 +119,15 @@ public static Uri Init(string uriBase, bool dontEscape) #pragma warning disable CS0618 // Type or member is obsolete var result = new Uri(uriBase, dontEscape); #pragma warning restore CS0618 // Type or member is obsolete - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } @@ -101,7 +141,15 @@ public static Uri Init(string uriBase, bool dontEscape) public static Uri Init(string uriBase, UriKind uriKind) { var result = new Uri(uriBase, uriKind); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } @@ -116,7 +164,15 @@ public static Uri Init(string uriBase, UriKind uriKind) public static Uri Init(string uriBase, in UriCreationOptions options) { var result = new Uri(uriBase, in options); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.OriginalString, uriBase); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(Init)}"); + } + return result; } #endif @@ -132,9 +188,16 @@ public static Uri Init(string uriBase, in UriCreationOptions options) public static bool TryCreate(string uri, UriKind kind, out Uri? uriCreated) { var result = Uri.TryCreate(uri, kind, out uriCreated); - if (uriCreated is not null) + try + { + if (uriCreated is not null) + { + PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, uri); + } + } + catch (Exception ex) { - PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, uri); + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(TryCreate)}"); } return result; @@ -152,9 +215,16 @@ public static bool TryCreate(string uri, UriKind kind, out Uri? uriCreated) public static bool TryCreate(string uri, in UriCreationOptions options, out Uri? uriCreated) { var result = Uri.TryCreate(uri, options, out uriCreated); - if (uriCreated is not null) + try + { + if (uriCreated is not null) + { + PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, uri); + } + } + catch (Exception ex) { - PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, uri); + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(TryCreate)}"); } return result; @@ -172,9 +242,16 @@ public static bool TryCreate(string uri, in UriCreationOptions options, out Uri? public static bool TryCreate(Uri? baseUri, string? relativeUri, out Uri? uriCreated) { var result = Uri.TryCreate(baseUri, relativeUri, out uriCreated); - if (uriCreated is not null) + try { - PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, baseUri?.OriginalString, relativeUri); + if (uriCreated is not null) + { + PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, baseUri?.OriginalString, relativeUri); + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(TryCreate)}"); } return result; @@ -191,9 +268,16 @@ public static bool TryCreate(Uri? baseUri, string? relativeUri, out Uri? uriCrea public static bool TryCreate(Uri? baseUri, Uri? relativeUri, out Uri? uriCreated) { var result = Uri.TryCreate(baseUri, relativeUri, out uriCreated); - if (uriCreated is not null) + try + { + if (uriCreated is not null) + { + PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, baseUri?.OriginalString, relativeUri?.OriginalString); + } + } + catch (Exception ex) { - PropagationModuleImpl.PropagateResultWhenInputTainted(uriCreated.OriginalString, baseUri?.OriginalString, relativeUri?.OriginalString); + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(TryCreate)}"); } return result; @@ -208,7 +292,15 @@ public static bool TryCreate(Uri? baseUri, Uri? relativeUri, out Uri? uriCreated public static string UnescapeDataString(string uri) { var result = Uri.UnescapeDataString(uri); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(UnescapeDataString)}"); + } + return result; } @@ -223,7 +315,15 @@ public static string EscapeUriString(string uri) #pragma warning disable SYSLIB0013 // obsolete var result = Uri.EscapeUriString(uri); #pragma warning restore SYSLIB0013 - PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(EscapeUriString)}"); + } + return result; } @@ -236,7 +336,15 @@ public static string EscapeUriString(string uri) public static string EscapeDataString(string uri) { var result = Uri.EscapeDataString(uri); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(EscapeDataString)}"); + } + return result; } @@ -249,7 +357,15 @@ public static string EscapeDataString(string uri) public static string GetAbsoluteUri(Uri instance) { var result = instance.AbsoluteUri; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetAbsoluteUri)}"); + } + return result; } @@ -262,7 +378,15 @@ public static string GetAbsoluteUri(Uri instance) public static string GetAbsolutePath(Uri instance) { var result = instance.AbsolutePath; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetAbsolutePath)}"); + } + return result; } @@ -275,7 +399,15 @@ public static string GetAbsolutePath(Uri instance) public static string GetLocalPath(Uri instance) { var result = instance.LocalPath; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetLocalPath)}"); + } + return result; } @@ -291,9 +423,16 @@ public static string GetLocalPath(Uri instance) #pragma warning disable CS0618 // Type or member is obsolete var result = instance.MakeRelative(uri); #pragma warning restore CS0618 // Type or member is obsolete - if (!string.IsNullOrWhiteSpace(result)) + try + { + if (!string.IsNullOrWhiteSpace(result)) + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri.OriginalString); + } + } + catch (Exception ex) { - PropagationModuleImpl.PropagateResultWhenInputTainted(result, uri.OriginalString); + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(MakeRelative)}"); } return result; @@ -309,9 +448,16 @@ public static string GetLocalPath(Uri instance) public static Uri? MakeRelativeUri(Uri instance, Uri uri) { var result = instance.MakeRelativeUri(uri); - if (!string.IsNullOrWhiteSpace(result?.OriginalString)) + try + { + if (!string.IsNullOrWhiteSpace(result?.OriginalString)) + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result!.OriginalString, uri.OriginalString); + } + } + catch (Exception ex) { - PropagationModuleImpl.PropagateResultWhenInputTainted(result!.OriginalString, uri.OriginalString); + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(MakeRelativeUri)}"); } return result; @@ -326,7 +472,15 @@ public static string GetLocalPath(Uri instance) public static string GetHost(Uri instance) { var result = instance.Host; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetHost)}"); + } + return result; } @@ -339,7 +493,15 @@ public static string GetHost(Uri instance) public static string GetPathAndQuery(Uri instance) { var result = instance.PathAndQuery; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetPathAndQuery)}"); + } + return result; } @@ -352,7 +514,15 @@ public static string GetPathAndQuery(Uri instance) public static string GetAuthority(Uri instance) { var result = instance.Authority; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetAuthority)}"); + } + return result; } @@ -365,7 +535,15 @@ public static string GetAuthority(Uri instance) public static string GetQuery(Uri instance) { var result = instance.Query; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(GetQuery)}"); + } + return result; } @@ -379,7 +557,15 @@ public static string GetQuery(Uri instance) { // We want the null reference exception to be launched here if target is null var result = instance!.ToString(); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, (instance as Uri)?.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, (instance as Uri)?.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriAspect)}.{nameof(ToString)}"); + } + return result; } } diff --git a/tracer/src/Datadog.Trace/Iast/Aspects/System/UriBuilderAspect.cs b/tracer/src/Datadog.Trace/Iast/Aspects/System/UriBuilderAspect.cs index a15ba8e4360e..f5934b731660 100644 --- a/tracer/src/Datadog.Trace/Iast/Aspects/System/UriBuilderAspect.cs +++ b/tracer/src/Datadog.Trace/Iast/Aspects/System/UriBuilderAspect.cs @@ -26,7 +26,15 @@ public class UriBuilderAspect public static UriBuilder Init(string uriText) { var result = new UriBuilder(uriText); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, uriText); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, uriText); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } + return result; } @@ -39,7 +47,15 @@ public static UriBuilder Init(string uriText) public static UriBuilder Init(Uri uri) { var result = new UriBuilder(uri); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, uri.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, uri.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } + return result; } @@ -53,7 +69,15 @@ public static UriBuilder Init(Uri uri) public static UriBuilder Init(string scheme, string host) { var result = new UriBuilder(scheme, host); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } + return result; } @@ -68,7 +92,15 @@ public static UriBuilder Init(string scheme, string host) public static UriBuilder Init(string scheme, string host, int port) { var result = new UriBuilder(scheme, host, port); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } + return result; } @@ -84,7 +116,15 @@ public static UriBuilder Init(string scheme, string host, int port) public static UriBuilder Init(string scheme, string host, int port, string path) { var result = new UriBuilder(scheme, host, port, path); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host, path); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host, path); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } + return result; } @@ -101,7 +141,15 @@ public static UriBuilder Init(string scheme, string host, int port, string path) public static UriBuilder Init(string scheme, string host, int port, string path, string extra) { var result = new UriBuilder(scheme, host, port, path, extra); - PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host, path, extra); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result.Uri.OriginalString, host, path, extra); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } + return result; } @@ -114,7 +162,14 @@ public static UriBuilder Init(string scheme, string host, int port, string path, public static void SetHost(UriBuilder instance, string parameter) { instance.Host = parameter; - PropagationModuleImpl.PropagateResultWhenInputTainted(instance.Uri.OriginalString, parameter); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(instance.Uri.OriginalString, parameter); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(Init)}"); + } } /// @@ -126,7 +181,14 @@ public static void SetHost(UriBuilder instance, string parameter) public static void SetQuery(UriBuilder instance, string parameter) { instance.Query = parameter; - PropagationModuleImpl.PropagateResultWhenInputTainted(instance.Uri.OriginalString, parameter); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(instance.Uri.OriginalString, parameter); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(SetQuery)}"); + } } /// @@ -138,7 +200,14 @@ public static void SetQuery(UriBuilder instance, string parameter) public static void SetPath(UriBuilder instance, string parameter) { instance.Path = parameter; - PropagationModuleImpl.PropagateResultWhenInputTainted(instance.Uri.OriginalString, parameter); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(instance.Uri.OriginalString, parameter); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(SetPath)}"); + } } /// @@ -150,7 +219,15 @@ public static void SetPath(UriBuilder instance, string parameter) public static string GetHost(UriBuilder instance) { var result = instance.Host; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.Uri.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.Uri.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(GetHost)}"); + } + return result; } @@ -163,7 +240,15 @@ public static string GetHost(UriBuilder instance) public static string GetQuery(UriBuilder instance) { var result = instance.Query; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.Uri.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.Uri.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(GetQuery)}"); + } + return result; } @@ -176,7 +261,15 @@ public static string GetQuery(UriBuilder instance) public static string GetPath(UriBuilder instance) { var result = instance.Path; - PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.Uri.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, instance.Uri.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(GetPath)}"); + } + return result; } @@ -190,7 +283,15 @@ public static string GetPath(UriBuilder instance) { // We want the null reference exception to be launched here if target is null var result = instance!.ToString(); - PropagationModuleImpl.PropagateResultWhenInputTainted(result, (instance as UriBuilder)?.Uri?.OriginalString); + try + { + PropagationModuleImpl.PropagateResultWhenInputTainted(result, (instance as UriBuilder)?.Uri?.OriginalString); + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(UriBuilderAspect)}.{nameof(ToString)}"); + } + return result; } } diff --git a/tracer/src/Datadog.Trace/Iast/IastModule.Escape.cs b/tracer/src/Datadog.Trace/Iast/IastModule.Escape.cs index ff5ff2e13cdf..d00d43065853 100644 --- a/tracer/src/Datadog.Trace/Iast/IastModule.Escape.cs +++ b/tracer/src/Datadog.Trace/Iast/IastModule.Escape.cs @@ -14,20 +14,19 @@ namespace Datadog.Trace.Iast; internal static partial class IastModule { - public static string? OnXssEscape(string? text) + public static string? OnXssEscape(string? text, string? encoded) { - var res = WebUtility.HtmlEncode(text); try { if (!iastSettings.Enabled || string.IsNullOrEmpty(text)) { - return res; + return encoded; } var tracer = Tracer.Instance; if (!tracer.Settings.IsIntegrationEnabled(IntegrationId.Xss)) { - return res; + return encoded; } var scope = tracer.ActiveScope as Scope; @@ -35,13 +34,13 @@ internal static partial class IastModule if (traceContext?.IastRequestContext?.AddVulnerabilitiesAllowed() != true) { - return res; + return encoded; } var tainted = traceContext?.IastRequestContext?.GetTainted(text!); if (tainted is null) { - return res; + return encoded; } // Add the mark (exclusion) to the tainted ranges @@ -52,6 +51,6 @@ internal static partial class IastModule Log.Error(ex, "Error while escaping string for XSS."); } - return res; + return encoded; } } diff --git a/tracer/src/Datadog.Trace/Iast/Propagation/StringModuleImpl.cs b/tracer/src/Datadog.Trace/Iast/Propagation/StringModuleImpl.cs index d00826b0d6b1..98ef46634806 100644 --- a/tracer/src/Datadog.Trace/Iast/Propagation/StringModuleImpl.cs +++ b/tracer/src/Datadog.Trace/Iast/Propagation/StringModuleImpl.cs @@ -140,7 +140,7 @@ public static string OnStringSubSequence(string self, int beginIndex, string res return result; } - public static string OnStringJoin(string result, IEnumerable values, int startIndex = 0, int count = -1) + public static string OnStringJoin(string result, IEnumerable values, int startIndex = 0, int count = -1) { try { @@ -184,7 +184,12 @@ public static string OnStringJoin(string result, IEnumerable values, int return result; } - public static string OnStringJoin(string result, string delimiter, IEnumerable values, int startIndex = 0, int count = -1) + public static string OnStringJoin(string result, char delimiter, IEnumerable values, int startIndex = 0, int count = -1) + { + return OnStringJoin(result, delimiter.ToString(), values, startIndex, count); + } + + public static string OnStringJoin(string result, string delimiter, IEnumerable values, int startIndex = 0, int count = -1) { try { @@ -496,7 +501,7 @@ public static string OnStringConcat(in StringConcatParams parameters, string res /// StringConcat params struct /// Result /// result - public static string OnStringConcat(IEnumerable parameters, string result) + public static string OnStringConcat(IEnumerable parameters, string result) { try { diff --git a/tracer/test/Datadog.Trace.Security.IntegrationTests/IAST/IastInstrumentationUnitTests.cs b/tracer/test/Datadog.Trace.Security.IntegrationTests/IAST/IastInstrumentationUnitTests.cs index d4f049b3b8ae..d3511ca2be11 100644 --- a/tracer/test/Datadog.Trace.Security.IntegrationTests/IAST/IastInstrumentationUnitTests.cs +++ b/tracer/test/Datadog.Trace.Security.IntegrationTests/IAST/IastInstrumentationUnitTests.cs @@ -44,18 +44,26 @@ public IastInstrumentationUnitTests(ITestOutputHelper output) } [SkippableTheory] +#if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(StringBuilder), "Append")] +#else + [InlineData(typeof(StringBuilder), "Append", new string[] { "System.Text.StringBuilder Append(System.Text.StringBuilder, Int32, Int32)" })] +#endif [InlineData(typeof(StringBuilder), "AppendLine", null, true)] [InlineData(typeof(StringBuilder), ".ctor", null, true)] [InlineData(typeof(StringBuilder), "Insert", null, true)] #if NETCOREAPP3_1_OR_GREATER - [InlineData(typeof(StringBuilder), "AppendJoin", null, true)] + [InlineData(typeof(StringBuilder), "AppendJoin", new string[] { "System.Text.StringBuilder AppendJoin[T](System.String, System.Collections.Generic.IEnumerable`1[T])" }, true)] #endif [InlineData(typeof(StringBuilder), "Replace", null, true)] [InlineData(typeof(StringBuilder), "Remove", null, true)] [InlineData(typeof(StringBuilder), "CopyTo", null, true)] - [InlineData(typeof(StringBuilder), "AppendFormat", new string[] { "System.StringBuilder::AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,System.Object[])" }, true)] - [InlineData(typeof(string), "Join")] + [InlineData(typeof(StringBuilder), "AppendFormat", new string[] { "System.StringBuilder AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,System.Object[])" }, true)] +#if NETCOREAPP3_1_OR_GREATER + [InlineData(typeof(string), "Join", new string[] { "System.String Join[T](System.String, System.Collections.Generic.IEnumerable`1[T])" })] +#else + [InlineData(typeof(string), "Join", new string[] { "System.String Join[T](System.String, System.Collections.Generic.IEnumerable`1[T])", "System.String Join(Char, System.String[])", "System.String Join(Char, System.Object[])", "System.String Join(Char, System.String[], Int32, Int32)" })] +#endif [InlineData(typeof(string), "Copy")] [InlineData(typeof(string), "ToUpper")] [InlineData(typeof(string), "ToUpperInvariant")] @@ -69,7 +77,13 @@ public IastInstrumentationUnitTests(ITestOutputHelper output) [InlineData(typeof(string), "Substring")] [InlineData(typeof(string), "TrimEnd")] [InlineData(typeof(string), "Format", new string[] { "System.String Format(System.IFormatProvider, System.Text.CompositeFormat, System.Object[])" })] - [InlineData(typeof(string), "Split")] +#if NETCOREAPP2_1 + [InlineData(typeof(string), "Split", new string[] { "System.String[] Split(System.String, System.StringSplitOptions)", "System.String[] Split(System.String, Int32, System.StringSplitOptions)", "System.String Join(Char, System.String[], Int32, Int32)", "System.String Join(Char, System.String[], Int32, Int32)", "System.String Join(Char, System.String[], Int32, Int32)" })] +#elif NETCOREAPP3_0 + [InlineData(typeof(string), "Split", new string[] { "System.String[] Split(System.String, System.StringSplitOptions)", "System.String[] Split(System.String, Int32, System.StringSplitOptions)" })] +#else + [InlineData(typeof(string), "Split", new string[] { "System.String[] Split(System.String, System.StringSplitOptions)" })] +#endif [InlineData(typeof(string), "Replace", new string[] { "System.String::Replace(System.String,System.String,System.StringComparison)", "System.String::Replace(System.String,System.String,System.Boolean,System.Globalization.CultureInfo)" })] [InlineData(typeof(string), "Concat", new string[] { "System.String Concat(System.Object)" })] [InlineData(typeof(StreamReader), ".ctor")] @@ -226,11 +240,11 @@ public void TestFileClassMethodsAspectCover() [InlineData(typeof(XPathExpression))] [InlineData(typeof(Activator), new string[] { "System.Activator::CreateInstance(System.AppDomain,System.String,System.String)" })] #if !NETFRAMEWORK - #if NET6_0_OR_GREATER +#if NET6_0_OR_GREATER [InlineData(typeof(Type))] - #else +#else [InlineData(typeof(Type), new string[] { "System.Type::GetMethod(System.String,System.Reflection.BindingFlags,System.Type[])" })] - #endif +#endif #else [InlineData(typeof(Type), new string[] { "System.Type::GetMethod(System.String,System.Int32,System.Reflection.BindingFlags,System.Reflection.Binder,System.Reflection.CallingConventions,System.Type[],System.Reflection.ParameterModifier[])", "System.Type::GetMethod(System.String,System.Int32,System.Reflection.BindingFlags,System.Reflection.Binder,System.Type[],System.Reflection.ParameterModifier[])", "System.Type::GetMethod(System.String,System.Int32,System.Type[],System.Reflection.ParameterModifier[])", "System.Type::GetMethod(System.String,System.Reflection.BindingFlags,System.Type[])", "System.Type::GetMethod(System.String,System.Int32,System.Type[])" })] #endif diff --git a/tracer/test/Datadog.Trace.Tools.Analyzers.Tests/AspectAnalyzers/ReplaceAspectAnalyzerTests.cs b/tracer/test/Datadog.Trace.Tools.Analyzers.Tests/AspectAnalyzers/ReplaceAspectAnalyzerTests.cs new file mode 100644 index 000000000000..1aaadb4e94b0 --- /dev/null +++ b/tracer/test/Datadog.Trace.Tools.Analyzers.Tests/AspectAnalyzers/ReplaceAspectAnalyzerTests.cs @@ -0,0 +1,642 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Threading.Tasks; +using Datadog.Trace.Tools.Analyzers.AspectAnalyzers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; +using Verifier = Microsoft.CodeAnalysis.CSharp.Testing.XUnit.CodeFixVerifier< + Datadog.Trace.Tools.Analyzers.AspectAnalyzers.ReplaceAspectAnalyzer, + Datadog.Trace.Tools.Analyzers.AspectAnalyzers.ReplaceAspectCodeFixProvider>; + +namespace Datadog.Trace.Tools.Analyzers.Tests.AspectAnalyzers; + +public class ReplaceAspectAnalyzerTests +{ + private const string DiagnosticId = ReplaceAspectAnalyzer.DiagnosticId; + private const DiagnosticSeverity Severity = ReplaceAspectAnalyzer.Severity; + + // No diagnostics expected to show up + [Fact] + public async Task EmptySourceShouldNotHaveDiagnostics() + { + var test = string.Empty; + + await Verifier.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task ShouldNotFlagMethodWithoutAttributes() + { + var method = + """ + string TestMethod(string myParam) + { + // does something + return myParam; + } + """; + + await Verifier.VerifyAnalyzerAsync(GetTestCode(method)); + } + + [Fact] + public async Task ShouldNotFlagCtorMethodWithoutAttributes() + { + var method = + """ + TestClass TestMethod(string myParam) + { + // does something + return new TestClass(); + } + """; + + await Verifier.VerifyAnalyzerAsync(GetTestCode(method)); + } + + [Fact] + public async Task ShouldNotFlagMethodWithCorrectFormat() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + { + var result = myParam + "/"; + try + { + // does something + return myParam; + } + catch (Exception ex) + { + // the contents don't actually matter here + return myParam; + } + return result; + } + """; + + await Verifier.VerifyAnalyzerAsync(GetTestCode(method)); + } + + [Fact] + public async Task ShouldNotFlagVoidMethodWithCorrectFormat() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + void TestMethod(string myParam) + { + string.Concat(myParam, "/"); + try + { + // does something + } + catch (Exception ex) + { + // the contents don't actually matter here + } + } + """; + + await Verifier.VerifyAnalyzerAsync(GetTestCode(method)); + } + + [Fact] + public async Task ShouldNotFlagCtorWithCorrectFormat() + { + var method = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + { + var result = new TestClass(); + + try + { + // does something + } + catch (Exception ex) + { + // the contents don't actually matter here + } + + return result; + } + """; + + await Verifier.VerifyAnalyzerAsync(GetTestCode(method)); + } + + [Fact] + public async Task ShouldFlagExpressionBodiedMember() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:=> myParam|}; + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_Nothing() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:{ + // does something + return myParam; + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + // can't fix as no good options + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_NoTryCatch() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:{ + var result = myParam + "/"; + + _ = myParam; + + return result; + }|} + """; + + var fixedMethod = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + { + var result = myParam + "/"; + try + { + _ = myParam; + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(TestClass)}.{nameof(TestMethod)}"); + } + + return result; + } + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + var fix = GetTestCode(fixedMethod); + await Verifier.VerifyCodeFixAsync(code, expected, fix); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_NoTryCatchMultiBlock() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:{ + var result = myParam + "/"; + + _ = myParam; + var x = myParam + myParam; + + return result; + }|} + """; + + var fixedMethod = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + { + var result = myParam + "/"; + try + { + _ = myParam; + var x = myParam + myParam; + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(TestClass)}.{nameof(TestMethod)}"); + } + + return result; + } + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + var fix = GetTestCode(fixedMethod); + await Verifier.VerifyCodeFixAsync(code, expected, fix); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_MultiBlockTryCatch() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:{ + var result = myParam + "/"; + + _ = myParam; + try + { + var x = myParam + myParam; + } + catch (Exception e) + { + // the contents don't actually matter here + } + + return result; + }|} + """; + + var fixedMethod = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + { + var result = myParam + "/"; + try + { + _ = myParam; + try + { + var x = myParam + myParam; + } + catch (Exception e) + { + // the contents don't actually matter here + } + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(TestClass)}.{nameof(TestMethod)}"); + } + + return result; + } + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + var fix = GetTestCode(fixedMethod); + await Verifier.VerifyCodeFixAsync(code, expected, fix); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_ReturnsWrongValue() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:{ + var result = myParam + "/"; + + try + { + // does something + } + catch (Exception ex) + { + // the contents don't actually matter here + } + + return myParam; + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + // can't fix as no good options + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_NotALocalDeclaration() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + {|#0:{ + string.Concat(myParam, "/"); + + try + { + // does something + } + catch (Exception ex) + { + // the contents don't actually matter here + } + + return myParam; + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + // can't fix as no good options + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagMethodThatDoesntFitSpec_InsufficientCatch() + { + var method = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + { + var result = myParam + "/"; + + try + { + // does something + } + {|#0:catch (SystemException ex) + { + // using too narrow an exception here + }|} + + return result; + } + """; + + var fixedMethod = + """ + [AspectMethodReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + string TestMethod(string myParam) + { + var result = myParam + "/"; + + try + { + // does something + } + catch (SystemException ex) + { + // using too narrow an exception here + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(TestClass)}.{nameof(TestMethod)}"); + } + + return result; + } + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + var fix = GetTestCode(fixedMethod); + await Verifier.VerifyCodeFixAsync(code, expected, fix); + } + + [Fact] + public async Task ShouldFlagCtorThatDoesntFitSpec_Nothing() + { + var method = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + {|#0:{ + // does something + return new(); + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + // can't fix as no good options + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagCtorThatDoesntFitSpec_NoTryCatch() + { + var method = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + {|#0:{ + var result = new TestClass(); + + _ = myParam; + + return result; + }|} + """; + + var fixedMethod = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + {|#0:{ + var result = new TestClass(); + try + { + _ = myParam; + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(TestClass)}.{nameof(TestMethod)}"); + } + + return result; + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + var fix = GetTestCode(fixedMethod); + await Verifier.VerifyCodeFixAsync(code, expected, fix); + } + + [Fact] + public async Task ShouldFlagCtorThatDoesntFitSpec_ReturnsWrongValue() + { + var method = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + {|#0:{ + var result = new TestClass(); + + try + { + // does something + } + catch (Exception ex) + { + // the contents don't actually matter here + } + + return new TestClass(); + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + // can't fix as no good options + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagCtorThatDoesntFitSpec_NotALocalDeclaration() + { + var method = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + {|#0:{ + new TestClass(); + + try + { + // does something + } + catch (Exception ex) + { + // the contents don't actually matter here + } + + return new TestClass(); + }|} + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + // can't fix as no good options + await Verifier.VerifyAnalyzerAsync(code, expected); + } + + [Fact] + public async Task ShouldFlagCtorThatDoesntFitSpec_InsufficientCatch() + { + var method = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + { + var result = new TestClass(); + + try + { + // does something + } + {|#0:catch (SystemException ex) + { + // using too narrow an exception here + }|} + + return result; + } + """; + + var fixedMethod = + """ + [AspectCtorReplace("Microsoft.AspNetCore.Http.HttpResponse::Redirect(System.String)")] + TestClass TestMethod(string myParam) + { + var result = new TestClass(); + + try + { + // does something + } + catch (SystemException ex) + { + // using too narrow an exception here + } + catch (Exception ex) + { + IastModule.Log.Error(ex, $"Error invoking {nameof(TestClass)}.{nameof(TestMethod)}"); + } + + return result; + } + """; + + var expected = new DiagnosticResult(DiagnosticId, Severity).WithLocation(0); + var code = GetTestCode(method); + var fix = GetTestCode(fixedMethod); + await Verifier.VerifyCodeFixAsync(code, expected, fix); + } + + private static string GetTestCode(string testFragment) + => + $$""" + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Diagnostics; + + namespace ConsoleApplication1 + { + class TestClass + { + private static readonly IDatadogLogger Log = new DatadogLogging(); + + {{testFragment}} + } + + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] + internal abstract class AspectAttribute : Attribute { } + + internal sealed class AspectCtorReplaceAttribute : AspectAttribute + { + public AspectCtorReplaceAttribute(string targetMethod) { } + } + + internal sealed class AspectMethodReplaceAttribute : AspectAttribute + { + public AspectMethodReplaceAttribute(string targetMethod) { } + } + + interface IDatadogLogger + { + void Error(Exception? exception, string messageTemplate); + } + + class DatadogLogging : IDatadogLogger + { + public void Error(Exception? exception, string messageTemplate) { } + } + + static class IastModule + { + public static readonly IDatadogLogger Log = new DatadogLogging(); + } + } + """; +} diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/InstrumentationTestsBase.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/InstrumentationTestsBase.cs index 5c8f674f428d..fc54421327b3 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/InstrumentationTestsBase.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/InstrumentationTestsBase.cs @@ -337,7 +337,8 @@ protected string FormatTainted(object value) foreach (var range in rangesList) { var start = (int)_StartProperty.Invoke(range, Array.Empty()); - result = result.Insert(start + (int)_lengthProperty.Invoke(range, Array.Empty()), "-+:"); + var length = (int)_LengthProperty.Invoke(range, Array.Empty()); + result = result.Insert(start + length, "-+:"); result = result.Insert(start, ":+-"); } diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringConcatTests.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringConcatTests.cs index a5f91069a517..41bd108331cf 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringConcatTests.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringConcatTests.cs @@ -31,7 +31,7 @@ public StringConcatTests() //Basic cases [Fact] - public void GivenStringConcatBasicOperations_WhenPerformed_ResultIsOK() + public void GivenStringConcatOperations_WhenPerformed_ResultIsOK() { var testString1 = AddTaintedString("01"); var testString2 = AddTaintedString("abc"); @@ -58,7 +58,6 @@ public void GivenStringConcatBasicOperations_WhenPerformed_ResultIsOK() FormatTainted(String.Concat(new string[] { testString1, testString2, testString3, testString4, testString5 })).Should().Be(":+-01-+::+-abc-+::+-ABCD-+::+-.,;:?-+::+-+-*/{}-+:"); FormatTainted(String.Concat(new object[] { testString1, testString2, testString3, testString4, testString5 })).Should().Be(":+-01-+::+-abc-+::+-ABCD-+::+-.,;:?-+::+-+-*/{}-+:"); - FormatTainted(String.Concat(new List { testString1, testString2, testString3, testString4, testString5 })).Should().Be(":+-01-+::+-abc-+::+-ABCD-+::+-.,;:?-+::+-+-*/{}-+:"); FormatTainted(String.Concat(testString1, " dummy ")).Should().Be(":+-01-+: dummy "); FormatTainted(String.Concat(" dummy ", testString2, " dummy ")).Should().Be(" dummy :+-abc-+: dummy "); FormatTainted(String.Concat(" dummy ", testString3)).Should().Be(" dummy :+-ABCD-+:"); @@ -69,6 +68,18 @@ public void GivenStringConcatBasicOperations_WhenPerformed_ResultIsOK() FormatTainted(String.Concat((object)" dummy ", null, testString2, (object)" dummy ")).Should().Be(" dummy :+-abc-+: dummy "); } + [Fact(Skip = "Aspect disabled until undefined generics are supported")] + public void GivenStringConcatOperations_WhenPerformedWithGenerics_ResultIsOK() + { + var testString1 = AddTaintedString("01"); + var testString2 = AddTaintedString("abc"); + var testString3 = AddTaintedString("ABCD"); + var testString4 = AddTaintedString(".,;:?"); + var testString5 = AddTaintedString("+-*/{}"); + + FormatTainted(String.Concat(new List { testString1, testString2, testString3, testString4, testString5 })).Should().Be(":+-01-+::+-abc-+::+-ABCD-+::+-.,;:?-+::+-+-*/{}-+:"); + } + [Fact] public void GivenAStringConcatOneString_WhenPerformed_ResultIsOK() { @@ -485,7 +496,7 @@ public void GivenATaintedObject_WhenCallingConcatWith4ObjectParams_ResultIsTaint AssertTaintedFormatWithOriginalCallCheck(":+-TAINTED2-+:concat:+-tainted-+:concat2", String.Concat(taintedValue2, (object)"concat", taintedValue, (object)"concat2"), () => String.Concat(taintedValue2, (object)"concat", taintedValue, (object)"concat2")); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAnObjectList_WhenConcat_ResultIsOk() { AssertTaintedFormatWithOriginalCallCheck("123:+-TaintedObject-+:", String.Concat(new List { 1, 2, 3, TaintedObject }), () => String.Concat(new List { 1, 2, 3, TaintedObject })); @@ -493,14 +504,14 @@ public void GivenAnObjectList_WhenConcat_ResultIsOk() // structs and built-in types - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void Given_StringConcatGenericStruct_WhenConcat_ResultIsTainted() { string str = String.Concat(new List { new StructForStringTest(UntaintedString), new StructForStringTest(TaintedString) }); FormatTainted(str).Should().Be("UntaintedString:+-TaintedString-+:"); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInStruct_WhenCallingConcat_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString:+-tainted-+:", String.Concat(new List { new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue) }), () => String.Concat(new List { new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue) })); @@ -535,7 +546,7 @@ public void GivenAnCharList_WhenConcat_ResultIsOk2() // Classes - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInClassList_WhenCallingConcat_ResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString:+-TaintedString-+:", @@ -543,7 +554,7 @@ public void GivenATaintedStringInClassList_WhenCallingConcat_ResultIsTainted2() () => String.Concat(new List { new ClassForStringTest(UntaintedString), new ClassForStringTest(TaintedString) })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInClassArray_WhenCallingConcat_ResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString:+-tainted-+:", @@ -551,7 +562,7 @@ public void GivenATaintedStringInClassArray_WhenCallingConcat_ResultIsTainted2() () => String.Concat(new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInStruct_WhenCallingConcat_ResultIsTainted3() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString:+-tainted-+:", String.Concat(new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) }), () => String.Concat(new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) })); @@ -571,19 +582,19 @@ public void GivenATaintedObject_WhenCallingConcatWithStringArrayParam_ResultIsTa AssertTaintedFormatWithOriginalCallCheck("concatCONCAT2:+-tainted-+::+-TAINTED2-+:", String.Concat(new string[] { "concat", "CONCAT2", taintedValue, taintedValue2 }), () => String.Concat(new string[] { "concat", "CONCAT2", taintedValue, taintedValue2 })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingConcatWithStringIEnumerableStringParam_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("concatCONCAT2:+-tainted-+::+-TAINTED2-+:", String.Concat(new List { "concat", "CONCAT2", taintedValue, taintedValue2 }), () => String.Concat(new List { "concat", "CONCAT2", taintedValue, taintedValue2 })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingConcatWithStringIEnumerableNullParam_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("concatCONCAT2:+-TAINTED2-+:", String.Concat(new List { "concat", "CONCAT2", null, taintedValue2 }), () => String.Concat(new List { "concat", "CONCAT2", null, taintedValue2 })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingConcatWithStringIEnumerableStringParam_ResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck("concatCONCAT2:+-tainted-+::+-TAINTED2-+:", String.Concat(new List { "concat", "CONCAT2", taintedValue, taintedValue2 }), () => String.Concat(new List { "concat", "CONCAT2", taintedValue, taintedValue2 })); @@ -603,21 +614,21 @@ public void GivenATaintedString_WhenCallingConcatWithObjectArrayParam_ResultIsTa AssertTaintedFormatWithOriginalCallCheck("concatconcat2:+-tainted-+::+-TAINTED2-+:", String.Concat(new object[] { "concat", "concat2", taintedValue, taintedValue2 }), () => String.Concat(new object[] { "concat", "concat2", taintedValue, taintedValue2 })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedObject_WhenCallingConcatWithObjectListParam_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("concatconcat2:+-tainted-+::+-TAINTED2-+:", String.Concat(new List { "concat", "concat2", taintedValue, taintedValue2 }), () => String.Concat(new List { "concat", "concat2", taintedValue, taintedValue2 })); } - [Fact] - + [Fact(Skip = "Aspect disabled until undefined generics are supported")] + public void GivenATaintedObject_WhenCallingConcatWithGenericObjectArrayParam_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("concatconcat2:+-tainted-+::+-TAINTED2-+:", String.Concat(new object[] { "concat", "concat2", taintedValue, taintedValue2 }), () => String.Concat(new object[] { "concat", "concat2", taintedValue, taintedValue2 })); } - [Fact] - + [Fact(Skip = "Aspect disabled until undefined generics are supported")] + public void GivenATaintedObject_WhenCallingConcatWithGenericObjectListParam_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("concatconcat2:+-tainted-+::+-TAINTED2-+:", String.Concat(new List { "concat", "concat2", taintedValue, taintedValue2 }), () => String.Concat(new List { "concat", "concat2", taintedValue, taintedValue2 })); diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringJoinTests.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringJoinTests.cs index 64fbfc293e02..a197044062b1 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringJoinTests.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringJoinTests.cs @@ -177,31 +177,31 @@ public void GivenATaintedObject_WhenCallingJoinWithStringArrayAndIndexAndNullSep AssertTaintedFormatWithOriginalCallCheck(":+-TAINTED2-+:eee", String.Join(null, new string[] { taintedValue2, "eee" }, 0, 2), () => String.Join(null, new string[] { taintedValue2, "eee" }, 0, 2)); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedObject_WhenCallingJoinWithGenericListNullSeparator_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck(":+-TAINTED2-+:eee", String.Join(null, new List { taintedValue2, "eee" }), () => String.Join(null, new List { taintedValue2, "eee" })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedObject_WhenCallingJoinWithGenericListOneNullParams_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck(":+-TAINTED2-+::+-tainted-+:", String.Join(taintedValue, new List { taintedValue2, null }), () => String.Join(taintedValue, new List { taintedValue2, null })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedObject_WhenCallingJoinWithGenericList_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck(":+-TAINTED2-+::+-tainted-+:eee", String.Join(taintedValue, new List { taintedValue2, "eee" }), () => String.Join(taintedValue, new List { taintedValue2, "eee" })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInStruct_WhenCallingJoin_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString,:+-tainted-+:", String.Join(",", new List { new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue) }), () => String.Join(",", new List { new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue) })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInStruct_WhenCallingJoin_ResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString,:+-tainted-+:", String.Join(",", new List { new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue) }), () => String.Join(",", new List { new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue) })); @@ -219,13 +219,13 @@ public void GivenATaintedStringInStruct_WhenCallingJoin_ResultIsTainted3() AssertTaintedFormatWithOriginalCallCheck("UntaintedString,:+-tainted-+:", String.Join(",", new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue)), () => String.Join(",", new StructForStringTest("UntaintedString"), new StructForStringTest(taintedValue))); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInClass_WhenCallingJoin_ResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString,:+-tainted-+:", String.Join(",", new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) }), () => String.Join(",", new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInClass_WhenCallingJoin_ResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck("UntaintedString,:+-tainted-+:", String.Join(",", new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) }), () => String.Join(",", new List { new ClassForStringTest("UntaintedString"), new ClassForStringTest(taintedValue) })); @@ -249,9 +249,9 @@ public void GivenATaintedStringInClass_WhenCallingJoin_ResultIsTainted5() AssertTaintedFormatWithOriginalCallCheck(":+-tainted-+:", String.Join(",", new ClassForStringTest(taintedValue)), () => String.Join(",", new ClassForStringTest(taintedValue))); } -#if !NET462 +#if NETCOREAPP3_1_OR_GREATER - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInList_WhenCallingJoinWithChar_ResultIsTainted10() { var objectList = new List { TaintedObject, UntaintedObject, OtherTaintedObject }; @@ -272,7 +272,7 @@ void NestedMethod(List parameters) NestedMethod(new List { taintedValue }); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInNestedMethodObject_WhenCallingJoinWithChar_ResultIsTainted7() { void NestedMethod(List parameters) @@ -283,7 +283,7 @@ void NestedMethod(List parameters) NestedMethod(new List { taintedValue, "NonTainted" }); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedStringInList_WhenCallingJoinWithChar_ResultIsTainted8() { var parameters = new List { taintedValue, "NonTainted" }; @@ -323,7 +323,7 @@ public void GivenATaintedString_WhenCallingJoin_ResultIsTainted10() () => String.Join('a', new string[] { taintedValue, taintedValue }, 0, 2)); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingJoin_ResultIsTainted12() { AssertTaintedFormatWithOriginalCallCheck(":+-tainted-+:a:+-tainted-+:", @@ -331,7 +331,7 @@ public void GivenATaintedString_WhenCallingJoin_ResultIsTainted12() () => String.Join('a', new List { taintedValue, taintedValue })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingJoin_ResultIsTainted13() { AssertTaintedFormatWithOriginalCallCheck(":+-tainted-+:aa:+-tainted-+:", @@ -339,7 +339,7 @@ public void GivenATaintedString_WhenCallingJoin_ResultIsTainted13() () => String.Join('a', new List { taintedValue, null, taintedValue })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingJoin_ResultIsTainted14() { AssertTaintedFormatWithOriginalCallCheck(":+-tainted-+:a:+-tainted-+:", @@ -347,7 +347,7 @@ public void GivenATaintedString_WhenCallingJoin_ResultIsTainted14() () => String.Join('a', new List { taintedValue, taintedValue })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenATaintedString_WhenCallingJoin_ResultIsTainted15() { AssertTaintedFormatWithOriginalCallCheck(":+-tainted-+:aa:+-tainted-+:", @@ -509,7 +509,7 @@ public void GivenStringJoinListWithTwoTaintedAndTwoUntainted_WhenJoin_ResultIsOk () => String.Join("|", list)); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenStringJoinTGenericStruct_WhenJoin_ResultIsOk() { var list = new List { new StructForStringTest(UntaintedString), new StructForStringTest(TaintedString) }; @@ -518,7 +518,7 @@ public void GivenStringJoinTGenericStruct_WhenJoin_ResultIsOk() () => string.Join("|", list)); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenStringJoinTGenericClass_WhenJoin_ResultIsOk() { var list = new List { new ClassForStringTest(UntaintedString), new ClassForStringTest(TaintedString) }; diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringSplitTests.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringSplitTests.cs index 02bcfa6272c4..0667c8c2ebf5 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringSplitTests.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/String/StringSplitTests.cs @@ -370,7 +370,7 @@ public void GivenATaintedObject_WhenCallingSplitWithStringArrayCountOptions_Resu // Test System.String::Split(System.String,System.Int32,System.StringSplitOptions) -#if !NETFRAMEWORK +#if NETCOREAPP3_1_OR_GREATER [Fact] public void GivenATaintedObject_WhenCallingSplitWithStringAndOptions_ResultIsTainted2() { @@ -389,12 +389,7 @@ public void GivenATaintedObject_WhenCallingSplitWithString_ResultIsNotTainted2() { AssertNoneTainted(_untaintedString.Split("i", StringSplitOptions.None)); } -#endif - - // Test System.String::Split(System.String,System.StringSplitOptions) - -#if !NETFRAMEWORK [Fact] public void GivenATaintedObject_WhenCallingSplitWithStringAndOptions_ResultIsTainted1() { @@ -413,9 +408,6 @@ public void GivenATaintedObject_WhenCallingSplitWithStringCountOptions_ResultIsN { AssertNoneTainted(_untaintedString.Split("i", 1, StringSplitOptions.None)); } -#endif - - // Test System.String::Split(System.Char,System.StringSplitOptions) [Fact] @@ -446,6 +438,7 @@ public void GivenATaintedObject_WhenCallingSplitWithCharAndOptions_ResultIsTaint AssertEqual(expected, str.Split('|')); } + [Fact] public void GivenATaintedObject_WhenCallingSplitWithCharAndOptions_ResultIsTainted4() { @@ -456,7 +449,6 @@ public void GivenATaintedObject_WhenCallingSplitWithCharAndOptions_ResultIsTaint AssertAllTainted(results); } -#if !NETFRAMEWORK [Fact] public void GivenATaintedObject_WhenCallingSplitWithCharAndOptions_ResultIsTainted5() { @@ -476,11 +468,6 @@ public void GivenATaintedObject_WhenCallingSplitWithCharAndOptions_ResultIsNotTa { AssertNoneTainted(_untaintedString.Split('i', StringSplitOptions.None)); } -#endif - - // Test System.String::Split(System.Char,System.Int32,System.StringSplitOptions) - -#if NETCOREAPP [Fact] public void GivenATaintedObject_WhenCallingSplitWithCharIndexAndOptions_ResultIsTainted2() diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendJoin.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendJoin.cs index 8c76f94508d0..3181566c4764 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendJoin.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendJoin.cs @@ -150,7 +150,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinStringObject_ThenResultIsTa // System.Text.StringBuilder::AppendJoin(System.String,System.Collections.Generic.IEnumerable`1) - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck(":+-tainted.untainted-+:", @@ -158,7 +158,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResul () => new StringBuilder().AppendJoin(".", new List { _taintedValue, _untaintedString })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck(":+-untainted.tainted-+:", @@ -174,7 +174,7 @@ public void GivenAStringBuilderNotTainted_WhenAppendJoinStringIEnumerable_ThenRe () => new StringBuilder().AppendJoin(".", new List { _untaintedString, _untaintedString })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResultIsTainted3() { AssertTaintedFormatWithOriginalCallCheck(":+-testuntainted.untainted-+:", @@ -182,7 +182,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResul () => GetTaintedStringBuilder("test").AppendJoin(".", new List { _untaintedString, _untaintedString })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResultIsTainted4() { AssertTaintedFormatWithOriginalCallCheck(":+-testuntainteduntainted-+:", @@ -206,7 +206,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResul () => GetTaintedStringBuilder("test").AppendJoin(".", (object[])null)); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinStringIEnumerable_ThenResultIsTainted7() { AssertTaintedFormatWithOriginalCallCheck(":+-untaintedtainteduntainted-+:", @@ -314,9 +314,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinCharObject_ThenResultIsNotT () => GetTaintedStringBuilder("test").AppendJoin('.', (object[])null)); } - // System.Text.StringBuilder::AppendJoin(System.Char,System.Collections.Generic.IEnumerable`1) - - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinCharIEnumerable_ThenResultIsTainted() { AssertTaintedFormatWithOriginalCallCheck(":+-tainted.untainted-+:", @@ -324,7 +322,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinCharIEnumerable_ThenResultI () => new StringBuilder().AppendJoin('.', new List { _taintedValue, _untaintedString })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinCharIEnumerable_ThenResultIsTainted2() { AssertTaintedFormatWithOriginalCallCheck(":+-untainted.tainted-+:", @@ -340,7 +338,7 @@ public void GivenAStringBuilderNotTainted_WhenAppendJoinCharIEnumerable_ThenResu () => new StringBuilder().AppendJoin('.', new List { _untaintedString, _untaintedString })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinCharIEnumerable_ThenResultIsTainted3() { var st = new StringBuilder("test").AppendJoin('.', new List { _untaintedString, _untaintedString }); @@ -350,7 +348,7 @@ public void GivenAStringBuilderTainted_WhenAppendJoinCharIEnumerable_ThenResultI () => GetTaintedStringBuilder("test").AppendJoin('.', new List { _untaintedString, _untaintedString })); } - [Fact] + [Fact(Skip = "Aspect disabled until undefined generics are supported")] public void GivenAStringBuilderTainted_WhenAppendJoinCharIEnumerable_ThenResultIsTainted4() { AssertTaintedFormatWithOriginalCallCheck(":+-test3.4-+:", diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendTests.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendTests.cs index 7288eaf8b473..8a953835a383 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendTests.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderAppendTests.cs @@ -219,7 +219,8 @@ public void GivenATaintedString_WhenCallingStringBuilderAppendStringIndexes_Resu // System.Text.StringBuilder::Append(System.Text.StringBuilder,System.Int32,System.Int32) -#if !NETFRAMEWORK +#if NETCOREAPP3_1_OR_GREATER + [Fact] public void GivenATaintedString_WhenCallingStringBuilderAppendStringBuilderIndexes_ResultIsTainted() { diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderInsertTests.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderInsertTests.cs index 05b1599c5c87..0bc220a69134 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderInsertTests.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderInsertTests.cs @@ -220,9 +220,13 @@ public void GivenATaintedString_WhenCallingStringBuilderInsertCharArrayTaintedAn [Fact] public void StringBuilder_Insert_Int_With_Untainted() { + var check = new StringBuilder("TaintedStringBuilder"); + var tainted = new StringBuilder("TaintedStringBuilder"); + AddTainted(tainted); + AssertTaintedFormatWithOriginalCallCheck("10:+-TaintedStringBuilder-+:", - _taintedStringBuilder.Insert(0, 10), - () => _taintedStringBuilder.Insert(0, 10)); + tainted.Insert(0, 10), + () => check.Insert(0, 10)); } [Fact] diff --git a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderRemoveTests.cs b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderRemoveTests.cs index d6b58c884f2a..a5241cd99184 100644 --- a/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderRemoveTests.cs +++ b/tracer/test/test-applications/integrations/Samples.InstrumentedTests/Vulnerabilities/StringBuilder/StringBuilderRemoveTests.cs @@ -5,7 +5,7 @@ namespace Samples.InstrumentedTests.Iast.Vulnerabilities.StringBuilderPropagatio public class StringBuilderRemoveTests : InstrumentationTestsBase { private string _taintedValue = "tainted"; - private StringBuilder _taintedStringBuilder = new StringBuilder("TaintedStringBuilder"); + //private StringBuilder _taintedStringBuilder = new StringBuilder("TaintedStringBuilder"); private string _taintedString = "TaintedString"; private string _untaintedString = "UntaintedString"; @@ -13,55 +13,79 @@ public StringBuilderRemoveTests() { AddTainted(_taintedValue); AddTainted(_taintedString); - AddTainted(_taintedStringBuilder); + //AddTainted(_taintedStringBuilder); } [Fact] public void GivenATaintedString_WhenCallingStringBuilderRemoveTainted_ResultIsTainted() { + var check = new StringBuilder("TaintedStringBuilder"); + var tainted = new StringBuilder("TaintedStringBuilder"); + AddTainted(tainted); + AssertTaintedFormatWithOriginalCallCheck(":+-TaintedBuilder-+:", - _taintedStringBuilder.Remove(7, 6), - () => _taintedStringBuilder.Remove(7, 6)); + tainted.Remove(7, 6), + () => check.Remove(7, 6)); } [Fact] public void GivenATaintedString_WhenCallingStringBuilderRemoveTainted_ResultIsTainted2() { - StringBuilder strb = _taintedStringBuilder.Append(_untaintedString); + var check = new StringBuilder("TaintedStringBuilder"); + var tainted = new StringBuilder("TaintedStringBuilder"); + AddTainted(tainted); + + tainted.Append(_untaintedString); + check.Append(_untaintedString); + AssertTaintedFormatWithOriginalCallCheck(":+-TaintedBuilder-+:UntaintedString", - strb.Remove(7, 6), - () => strb.Remove(7, 6)); + tainted.Remove(7, 6), + () => check.Remove(7, 6)); } [Fact] public void GivenATaintedString_WhenCallingStringBuilderRemoveTainted_ResultIsTainted3() { - StringBuilder strb = _taintedStringBuilder.Append(_taintedString); + var check = new StringBuilder("TaintedStringBuilder"); + var tainted = new StringBuilder("TaintedStringBuilder"); + AddTainted(tainted); + + tainted.Append(_taintedString); + check.Append(_taintedString); + AssertTaintedFormatWithOriginalCallCheck(":+-TaintedBuilder-+::+-TaintedString-+:", - strb.Remove(7, 6), - () => strb.Remove(7, 6)); + tainted.Remove(7, 6), + () => check.Remove(7, 6)); } [Fact] public void GivenATaintedString_WhenCallingStringBuilderRemoveTainted_ResultIsTainted4() { - StringBuilder strb = _taintedStringBuilder.Append(_untaintedString); - strb = strb.Append(_taintedString); + var check = new StringBuilder("TaintedStringBuilder"); + var tainted = new StringBuilder("TaintedStringBuilder"); + AddTainted(tainted); + + tainted.Append(_untaintedString).Append(_taintedString); + check.Append(_untaintedString).Append(_taintedString); AssertTaintedFormatWithOriginalCallCheck(":+-TaintedStringBuilder-+:Untainted:+-TaintedString-+:", - strb.Remove(29, 6), - () => strb.Remove(29, 6)); + tainted.Remove(29, 6), + () => check.Remove(29, 6)); } [Fact] public void GivenATaintedString_WhenCallingStringBuilderRemoveTainted_ResultIsTainted5() { - StringBuilder strb = _taintedStringBuilder.Append(_untaintedString); - strb = strb.Append(_taintedString); + var check = new StringBuilder("TaintedStringBuilder"); + var tainted = new StringBuilder("TaintedStringBuilder"); + AddTainted(tainted); + + tainted.Append(_untaintedString).Append(_taintedString); + check.Append(_untaintedString).Append(_taintedString); AssertTaintedFormatWithOriginalCallCheck(":+-TaintedBuilder-+:UntaintedString:+-TaintedString-+:", - strb.Remove(7, 6), - () => strb.Remove(7, 6)); + tainted.Remove(7, 6), + () => check.Remove(7, 6)); } [Fact]