/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using SharpFuzz;
namespace Opc.Ua.Fuzzing
{
public static class FuzzMethods
{
///
/// signatures supported by fuzzers
///
public delegate void AflFuzzStream(Stream stream);
public delegate void AflFuzzString(string text);
public delegate void LibFuzzSpan(ReadOnlySpan bytes);
public static readonly Type[] Delegates
= [typeof(AflFuzzStream), typeof(AflFuzzString), typeof(LibFuzzSpan)];
public static readonly Dictionary FuzzMethodsToParameterType = new()
{
{ typeof(AflFuzzStream), typeof(Stream) },
{ typeof(AflFuzzString), typeof(string) },
{ typeof(LibFuzzSpan), typeof(ReadOnlySpan) }
};
///
/// Finds all fuzzing methods for specified delegate.
///
public static List FindFuzzMethods(Type delegateType)
{
var fuzzMethods = new List();
Type type = typeof(FuzzableCode);
if (FuzzMethodsToParameterType.TryGetValue(
delegateType,
out Type? delegateParameterType))
{
foreach (
MethodInfo method in type.GetMethods(
BindingFlags.Public | BindingFlags.Static))
{
// Determine the target signature
ParameterInfo[] parameters = method.GetParameters();
if (method.ReturnType == typeof(void) &&
!method.ContainsGenericParameters &&
parameters.Length == 1 &&
parameters[0].ParameterType == delegateParameterType)
{
fuzzMethods.Add(method.CreateDelegate(delegateType));
}
}
}
return fuzzMethods;
}
///
/// Finds a fuzzing method by name and returns a delegate to call it.
///
public static Delegate? FindFuzzMethod(TextWriter errorOutput, string fuzzingFunction)
{
// find the function to fuzz based on the first argument using reflection
Type type = typeof(FuzzableCode);
MethodInfo method = type.GetMethod(
fuzzingFunction,
BindingFlags.Public | BindingFlags.Static)!;
if (method != null)
{
// Determine the target signature
ParameterInfo[] parameters = method.GetParameters();
if (method.ReturnType == typeof(void) &&
!method.ContainsGenericParameters &&
parameters.Length == 1)
{
// afl-fuzz targets
#if NET8_0_OR_GREATER
if (parameters[0].ParameterType == typeof(Stream))
{
return method.CreateDelegate();
}
else if (parameters[0].ParameterType == typeof(string))
{
return method.CreateDelegate();
}
// libfuzzer span target
else if (parameters[0].ParameterType == typeof(ReadOnlySpan))
{
return method.CreateDelegate();
}
#else
if (parameters[0].ParameterType == typeof(Stream))
{
return method.CreateDelegate(typeof(AflFuzzStream));
}
else if (parameters[0].ParameterType == typeof(string))
{
return method.CreateDelegate(typeof(AflFuzzString));
}
// libfuzzer span target
else if (parameters[0].ParameterType == typeof(ReadOnlySpan))
{
return method.CreateDelegate(typeof(LibFuzzSpan));
}
#endif
}
errorOutput.WriteLine(
"The fuzzing function {0} must be static void with one " +
"Stream, string or ReadOnlySpan parameter.",
fuzzingFunction);
}
else
{
errorOutput.WriteLine("The fuzzing function {0} was not found.", fuzzingFunction);
}
return null;
}
///
/// Replays one input without starting an instrumentation engine.
///
public static void Replay(Delegate fuzzingMethod, ReadOnlySpan input)
{
byte[] data = input.ToArray();
if (fuzzingMethod is LibFuzzSpan spanMethod)
{
RunWithOracles(spanMethod.Method.Name, data, () => spanMethod(data));
}
else if (fuzzingMethod is AflFuzzStream streamMethod)
{
RunWithOracles(streamMethod.Method.Name, data, () =>
{
using var stream = new MemoryStream(data, writable: false);
streamMethod(stream);
});
}
else if (fuzzingMethod is AflFuzzString stringMethod)
{
string text = Encoding.UTF8.GetString(data);
RunWithOracles(stringMethod.Method.Name, data, () => stringMethod(text));
}
else
{
throw new ArgumentException("Unsupported fuzzing delegate.", nameof(fuzzingMethod));
}
}
///
/// Runs one input under the stack and time oracles of .
///
private static void RunWithOracles(string target, byte[] input, Action run)
{
FuzzOracles.RunTarget(target, input.Length, run);
}
///
/// Runs the fuzzing method with the given delegate.
///
public static void RunFuzzMethod(Delegate fuzzingMethod, bool outOfProcess = false)
{
// find the function to fuzz method based on the type
if (fuzzingMethod is AflFuzzStream aflFuzzStreamMethod)
{
// Buffered so the oracles can re-run the input and measure its size.
void RunStream(Stream stream)
{
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
byte[] data = buffer.ToArray();
RunWithOracles(aflFuzzStreamMethod.Method.Name, data, () =>
{
using var input = new MemoryStream(data, writable: false);
aflFuzzStreamMethod(input);
});
}
if (outOfProcess)
{
Fuzzer.OutOfProcess.Run(RunStream);
}
else
{
Fuzzer.Run(RunStream);
}
}
else if (fuzzingMethod is AflFuzzString aflFuzzStringMethod)
{
void RunString(string text)
{
RunWithOracles(
aflFuzzStringMethod.Method.Name,
Encoding.UTF8.GetBytes(text),
() => aflFuzzStringMethod(text));
}
if (outOfProcess)
{
Fuzzer.OutOfProcess.Run(RunString);
}
else
{
Fuzzer.Run(RunString);
}
return;
}
// libfuzzer span target
else if (fuzzingMethod is LibFuzzSpan libFuzzSpanMethod)
{
Fuzzer.LibFuzzer.Run(bytes =>
{
byte[] data = bytes.ToArray();
RunWithOracles(libFuzzSpanMethod.Method.Name, data, () => libFuzzSpanMethod(data));
});
return;
}
else
{
throw new ArgumentException("Unsupported fuzzing delegate.", nameof(fuzzingMethod));
}
}
}
}