in src/BinSkim.Rules/DwarfRules/BA3003.EnableStackProtector.cs [67:166]
public override void Analyze(BinaryAnalyzerContext context)
{
IDwarfBinary binary = context.DwarfBinary();
List<DwarfCompileCommandLineInfo> failedList;
static bool analyze(IDwarfBinary binary, out List<DwarfCompileCommandLineInfo> failedList)
{
failedList = new List<DwarfCompileCommandLineInfo>();
foreach (DwarfCompileCommandLineInfo info in binary.CommandLineInfos)
{
if (ElfUtility.GetDwarfCommandLineType(info.CommandLine) != DwarfCommandLineType.Gcc)
{
continue;
}
bool failed = false;
if ((!info.CommandLine.Contains("-fstack-protector-all", StringComparison.OrdinalIgnoreCase)
&& !info.CommandLine.Contains("-fstack-protector-strong", StringComparison.OrdinalIgnoreCase))
|| info.CommandLine.Contains("-fno-stack-protector", StringComparison.OrdinalIgnoreCase))
{
failed = true;
}
else
{
string[] paramToCheck = { "--param=ssp-buffer-size=" };
string paramValue = string.Empty;
bool found = GetOptionValue(info.CommandLine, paramToCheck, OrderOfPrecedence.FirstWins, ref paramValue);
if (found && !string.IsNullOrWhiteSpace(paramValue))
{
if (int.TryParse(paramValue, out int bufferSize))
{
if (bufferSize > 4)
{
failed = true;
}
}
}
}
if (failed)
{
failedList.Add(info);
}
}
return !failedList.Any();
}
if (binary is ElfBinary elf)
{
if (!analyze(elf, out failedList))
{
// The stack protector was not found in '{0}'.
// This may be because '--stack-protector-strong' was not used,
// or because it was explicitly disabled by '-fno-stack-protectors'.
// Modules did not meet the criteria: {1}
context.Logger.Log(this,
RuleUtilities.BuildResult(FailureLevel.Error, context, null,
nameof(RuleResources.BA3003_Error),
context.TargetUri.GetFileName(),
DwarfUtility.GetDistinctNames(failedList, context.TargetUri.GetFileName())));
return;
}
// Stack protector was found on '{0}'.
context.Logger.Log(this,
RuleUtilities.BuildResult(ResultKind.Pass, context, null,
nameof(RuleResources.BA3003_Pass),
context.TargetUri.GetFileName()));
return;
}
if (binary is MachOBinary mainBinary)
{
foreach (SingleMachOBinary subBinary in mainBinary.MachOs)
{
if (!analyze(subBinary, out failedList))
{
// The stack protector was not found in '{0}'.
// This may be because '--stack-protector-strong' was not used,
// or because it was explicitly disabled by '-fno-stack-protectors'.
// Modules did not meet the criteria: {1}
context.Logger.Log(this,
RuleUtilities.BuildResult(FailureLevel.Error, context, null,
nameof(RuleResources.BA3003_Error),
context.TargetUri.GetFileName(),
DwarfUtility.GetDistinctNames(failedList, context.TargetUri.GetFileName())));
return;
}
}
// Stack protector was found on '{0}'.
context.Logger.Log(this,
RuleUtilities.BuildResult(ResultKind.Pass, context, null,
nameof(RuleResources.BA3003_Pass),
context.TargetUri.GetFileName()));
}
}