public override void Analyze(BinaryAnalyzerContext context) { PEHeader peHeader = context.PE.PEHeaders.PEHeader; if (context.Pdb == null) { Errors.LogExceptionLoadingPdb(context, context.PdbParseException); return; } Pdb di = context.Pdb; TruncatedCompilandRecordList warningTooLowModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList disabledWarningModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList unknownLanguageModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList allWarningLevelLowModules = new TruncatedCompilandRecordList(); string exampleTooLowWarningCommandLine = null; int overallMinimumWarningLevel = Int32.MaxValue; string exampleDisabledWarningCommandLine = null; List <int> overallDisabledWarnings = new List <int>(); foreach (DisposableEnumerableView <Symbol> omView in di.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails omDetails = om.GetObjectModuleDetails(); if (omDetails.Language == Language.Unknown) { // See if this module contributed to an executable section. If not, we can ignore the module. if (di.CompilandWithIdIsInExecutableSectionContrib(om.SymIndexId)) { unknownLanguageModules.Add(om.CreateCompilandRecord()); } continue; } if ((omDetails.Language != Language.C) && (omDetails.Language != Language.Cxx)) { continue; } if (omDetails.Compiler != "Microsoft (R) Optimizing Compiler") { continue; } if (!om.CreateChildIterator(SymTagEnum.SymTagFunction).Any()) { // uninteresting... continue; } int warningLevel = omDetails.WarningLevel; List <int> requiredDisabledWarnings = omDetails.ExplicitlyDisabledWarnings .Where(context.Policy.GetProperty(RequiredCompilerWarnings).Contains).ToList(); if (warningLevel >= 3 && requiredDisabledWarnings.Count == 0) { // We duplicate this condition to bail out early and avoid writing the // module description or newline into sbBadWarningModules if everything // in the module is OK. continue; } List <string> suffix = new List <string>(2); overallMinimumWarningLevel = Math.Min(overallMinimumWarningLevel, warningLevel); if (warningLevel < 3) { exampleTooLowWarningCommandLine = exampleTooLowWarningCommandLine ?? omDetails.CommandLine; string msg = "[warning level: " + warningLevel.ToString(CultureInfo.InvariantCulture) + "]"; warningTooLowModules.Add(om.CreateCompilandRecordWithSuffix(msg)); suffix.Add(msg); } if (requiredDisabledWarnings.Count != 0) { MergeInto(overallDisabledWarnings, requiredDisabledWarnings); exampleDisabledWarningCommandLine = exampleDisabledWarningCommandLine ?? omDetails.CommandLine; string msg = "[Explicitly disabled warnings: " + CreateTextWarningList(requiredDisabledWarnings) + "]"; disabledWarningModules.Add(om.CreateCompilandRecordWithSuffix(msg)); suffix.Add(msg); } allWarningLevelLowModules.Add(om.CreateCompilandRecordWithSuffix(String.Join(" ", suffix))); } if (unknownLanguageModules.Empty && exampleTooLowWarningCommandLine == null && exampleDisabledWarningCommandLine == null) { // '{0}' was compiled at a secure warning level ({1}) and does not // include any modules that disable specific warnings which are // required by policy. As a result, there is a greater likelihood // that memory corruption, information disclosure, double-free and // other security-related vulnerabilities do not exist in code. context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Pass, context, null, nameof(RuleResources.BA2007_Pass), overallMinimumWarningLevel.ToString())); return; } if (!unknownLanguageModules.Empty) { // '{0}' contains code from an unknown language, preventing a // comprehensive analysis of the compiler warning settings. // The language could not be identified for the following modules: {1} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2007_Error_UnknownModuleLanguage), unknownLanguageModules.CreateSortedObjectList())); } if (exampleTooLowWarningCommandLine != null) { // '{0}' was compiled at too low a warning level. Warning level 3 enables // important static analysis in the compiler to flag bugs that can lead // to memory corruption, information disclosure, or double-free // vulnerabilities.To resolve this issue, compile at warning level 3 or // higher by supplying / W3, / W4, or / Wall to the compiler, and resolve // the warnings emitted. // An example compiler command line triggering this check: {1} // Modules triggering this check: {2} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2007_Error_InsufficientWarningLevel), overallMinimumWarningLevel.ToString(), exampleTooLowWarningCommandLine, warningTooLowModules.CreateTruncatedObjectList())); } if (exampleDisabledWarningCommandLine != null) { // '{0}' disables compiler warning(s) which are required by policy. A // compiler warning is typically required if it has a high likelihood of // flagging memory corruption, information disclosure, or double-free // vulnerabilities. To resolve this issue, enable the indicated warning(s) // by removing /Wxxxx switches (where xxxx is a warning id indicated here) // from your command line, and resolve any warnings subsequently raised // during compilation. // An example compiler command line triggering this check was: {1} // Modules triggering this check were: {2} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2007_Error_WarningsDisabled), exampleDisabledWarningCommandLine, disabledWarningModules.CreateTruncatedObjectList())); } }
public override void AnalyzePortableExecutableAndPdb(BinaryAnalyzerContext context) { PEBinary target = context.PEBinary(); Pdb pdb = target.Pdb; Version minCompilerVersion; minCompilerVersion = (target.PE.IsXBox) ? context.Policy.GetProperty(MinimumToolVersions)[MIN_XBOX_COMPILER_VER] : context.Policy.GetProperty(MinimumToolVersions)[MIN_COMPILER_VER]; TruncatedCompilandRecordList badModuleList = new TruncatedCompilandRecordList(); StringToVersionMap allowedLibraries = context.Policy.GetProperty(AllowedLibraries); foreach (DisposableEnumerableView <Symbol> omView in pdb.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails omDetails = om.GetObjectModuleDetails(); if (omDetails.WellKnownCompiler != WellKnownCompilers.MicrosoftNativeCompiler) { continue; } // See if the item is in our skip list if (!string.IsNullOrEmpty(om.Lib)) { string libFileName = string.Concat(System.IO.Path.GetFileName(om.Lib), ",", omDetails.Language.ToString()).ToLowerInvariant(); Version minAllowedVersion; if (allowedLibraries.TryGetValue(libFileName, out minAllowedVersion) && omDetails.CompilerVersion >= minAllowedVersion) { continue; } } Version actualVersion; Version minimumVersion; Language omLanguage = omDetails.Language; switch (omLanguage) { case Language.C: case Language.Cxx: actualVersion = Minimum(omDetails.CompilerVersion, omDetails.CompilerFrontEndVersion); minimumVersion = minCompilerVersion; break; default: continue; } bool foundIssue = actualVersion < minimumVersion; AdvancedMitigations advancedMitigations = context.Policy.GetProperty(AdvancedMitigationsEnforced); if (!foundIssue && (advancedMitigations & AdvancedMitigations.Spectre) == AdvancedMitigations.Spectre) { ExtendedMachine machineType = (ExtendedMachine)target.PE.Machine; // Current toolchain is within the version range to validate. // Now we'll retrieve relevant compiler mitigation details to // ensure this object module's build and revision meet // expectations. CompilerMitigations newMitigationData = EnableSpectreMitigations.GetAvailableMitigations(context, machineType, actualVersion); // Current compiler version does not support Spectre mitigations. foundIssue = !newMitigationData.HasFlag(CompilerMitigations.D2GuardSpecLoadAvailable) && !newMitigationData.HasFlag(CompilerMitigations.QSpectreAvailable); if (foundIssue) { // Get the closest compiler version that has mitigations--i.e. if the user is using a 19.0 (VS2015) compiler, we should be recommending an upgrade to the // 19.0 version that has the mitigations, not an upgrade to a 19.10+ (VS2017) compiler. // Limitation--if there are multiple 'upgrade to' versions to recommend, this just going to give users the last one we see in the error. minCompilerVersion = EnableSpectreMitigations.GetClosestCompilerVersionWithSpectreMitigations(context, machineType, actualVersion); // Indicates Spectre mitigations are not supported on this platform. We won't flag this case. if (minCompilerVersion == null) { foundIssue = false; } } } if (foundIssue) { // built with {0} compiler version {1} (Front end version: {2}) badModuleList.Add( om.CreateCompilandRecordWithSuffix( String.Format(CultureInfo.InvariantCulture, RuleResources.BA2006_Error_BadModule, omLanguage, omDetails.CompilerVersion, omDetails.CompilerFrontEndVersion))); } } if (!badModuleList.Empty) { // '{0}' was compiled with one or more modules which were not built using // minimum required tool versions (compiler version {1}). More recent toolchains // contain mitigations that make it more difficult for an attacker to exploit // vulnerabilities in programs they produce. To resolve this issue, compile // and /or link your binary with more recent tools. If you are servicing a // product where the tool chain cannot be modified (e.g. producing a hotfix // for an already shipped version) ignore this warning. Modules built outside // of policy: {2} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2006_Error), context.TargetUri.GetFileName(), minCompilerVersion.ToString(), badModuleList.CreateSortedObjectList())); return; } // All linked modules of '{0}' generated by the Microsoft front-end // satisfy configured policy (compiler minimum version {1}). context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Pass, context, null, nameof(RuleResources.BA2006_Pass), context.TargetUri.GetFileName(), minCompilerVersion.ToString())); }
public override void Analyze(BinaryAnalyzerContext context) { PEHeader peHeader = context.PE.PEHeaders.PEHeader; Pdb pdb = context.Pdb; if (pdb == null) { Errors.LogExceptionLoadingPdb(context, context.PdbParseException); return; } TruncatedCompilandRecordList noGsModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList unknownLanguageModules = new TruncatedCompilandRecordList(); foreach (DisposableEnumerableView <Symbol> omView in pdb.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails details = om.GetObjectModuleDetails(); if (details.Language == Language.Unknown) { // See if this module contributed to an executable section. // If not, we can ignore the module. if (pdb.CompilandWithIdIsInExecutableSectionContrib(om.SymIndexId)) { unknownLanguageModules.Add(om.CreateCompilandRecord()); } continue; } // Detection applies to C/C++ produced by MS compiler only if ((details.Language != Language.C) && (details.Language != Language.Cxx) || details.Compiler != "Microsoft (R) Optimizing Compiler") { continue; } if (!details.HasSecurityChecks && om.CreateChildIterator(SymTagEnum.SymTagFunction).Any()) { noGsModules.Add(om.CreateCompilandRecord()); } } if (unknownLanguageModules.Empty && noGsModules.Empty) { // '{0}' is a C or C++ binary built with the stack protector buffer security // feature enabled for all modules, making it more difficult for an attacker to // exploit stack buffer overflow memory corruption vulnerabilities. context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Pass, context, null, nameof(RuleResources.BA2011_Pass))); return; } if (!unknownLanguageModules.Empty) { // '{0}' contains code from unknown language, preventing a comprehensive analysis of the // stack protector buffer security features. The language could not be identified for // the following modules: {1}. context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2011_Error_UnknownModuleLanguage), unknownLanguageModules.CreateSortedObjectList())); } if (!noGsModules.Empty) { // '{0}' is a C or C++ binary built with the stack protector buffer security feature // disabled in one or more modules. The stack protector (/GS) is a security feature // of the compiler which makes it more difficult to exploit stack buffer overflow // memory corruption vulnerabilities. To resolve this issue, ensure that your code // is compiled with the stack protector enabled by supplying /GS on the Visual C++ // compiler command line. The affected modules were: {1} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2011_Error), noGsModules.ToString())); } }
public void Analyze(BinaryAnalyzerContext context) { PEHeader peHeader = context.PE.PEHeaders.PEHeader; Pdb pdb = context.Pdb; if (pdb == null) { context.Logger.Log(MessageKind.Fail, context, RuleUtilities.BuildCouldNotLoadPdbMessage(context)); return; } TruncatedCompilandRecordList noGsModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList unknownLanguageModules = new TruncatedCompilandRecordList(); foreach (DisposableEnumerableView<Symbol> omView in pdb.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails details = om.GetObjectModuleDetails(); if (details.Language == Language.Unknown) { // See if this module contributed to an executable section. // If not, we can ignore the module. if (pdb.CompilandWithIdIsInExecutableSectionContrib(om.SymIndexId)) { unknownLanguageModules.Add(om.CreateCompilandRecord()); } continue; } // Detection applies to C/C++ produced by MS compiler only if ((details.Language != Language.C) && (details.Language != Language.Cxx) || details.Compiler != "Microsoft (R) Optimizing Compiler") { continue; } if (!details.HasSecurityChecks && om.CreateChildIterator(SymTagEnum.SymTagFunction).Any()) { noGsModules.Add(om.CreateCompilandRecord()); } } if (unknownLanguageModules.Empty && noGsModules.Empty) { // '{0}' is a C or C++ binary built with the stack protector buffer security // feature enabled for all modules, making it more difficult for an attacker to // exploit stack buffer overflow memory corruption vulnerabilities. context.Logger.Log(MessageKind.Pass, context, RuleUtilities.BuildMessage(context, RulesResources.EnableStackProtection_Pass)); return; } if (!unknownLanguageModules.Empty) { // '{0}' contains code from unknown language, preventing a comprehensive analysis of the // stack protector buffer security features. The language could not be identified for // the following modules: {1}. context.Logger.Log(MessageKind.Fail, context, RuleUtilities.BuildMessage(context, RulesResources.EnableStackProtection_UnknownModuleLanguage_Fail, unknownLanguageModules.ToString())); } if (!noGsModules.Empty) { // '{0}' is a C or C++ binary built with the stack protector buffer security feature // disabled in one or more modules. The stack protector (/GS) is a security feature // of the compiler which makes it more difficult to exploit stack buffer overflow // memory corruption vulnerabilities. To resolve this issue, ensure that your code // is compiled with the stack protector enabled by supplying /GS on the Visual C++ // compiler command line. The affected modules were: {1} context.Logger.Log(MessageKind.Fail, context, RuleUtilities.BuildMessage(context, RulesResources.EnableStackProtection_Fail, noGsModules.ToString())); } }
public override void AnalyzePortableExecutableAndPdb(BinaryAnalyzerContext context) { PEBinary target = context.PEBinary(); Machine reflectionMachineType = target.PE.Machine; // The current Machine enum does not have support for Arm64, so translate to our Machine enum ExtendedMachine machineType = (ExtendedMachine)reflectionMachineType; if (!machineType.CanBeMitigated()) { // QUESTION: // Machine HW is unsupported for mitigations... // should this be in the CanAnalyze() method or here and issue a warning? return; } Pdb pdb = target.Pdb; TruncatedCompilandRecordList masmModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList mitigationNotEnabledModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList mitigationDisabledInDebugBuild = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList mitigationExplicitlyDisabledModules = new TruncatedCompilandRecordList(); StringToVersionMap allowedLibraries = context.Policy.GetProperty(AllowedLibraries); foreach (DisposableEnumerableView <Symbol> omView in pdb.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails omDetails = om.GetObjectModuleDetails(); // See if the item is in our skip list. if (!string.IsNullOrEmpty(om.Lib)) { string libFileName = string.Concat(System.IO.Path.GetFileName(om.Lib), ",", omDetails.Language.ToString()).ToLowerInvariant(); Version minAllowedVersion; if (allowedLibraries.TryGetValue(libFileName, out minAllowedVersion) && omDetails.CompilerVersion >= minAllowedVersion) { continue; } } Version actualVersion; Language omLanguage = omDetails.Language; // We already opted-out of IL Only binaries, so only check for native languages // or those that can appear in mixed binaries. switch (omLanguage) { case Language.C: case Language.Cxx: { if (omDetails.WellKnownCompiler != WellKnownCompilers.MicrosoftNativeCompiler) { // TODO: https://github.com/Microsoft/binskim/issues/114 continue; } else { actualVersion = omDetails.CompilerVersion; } break; } case Language.MASM: { masmModules.Add(om.CreateCompilandRecord()); continue; } case Language.LINK: { // Linker is not involved in the mitigations, so no need to check version or switches at this time. continue; } case Language.CVTRES: { // Resource compiler is not involved in the mitigations, so no need to check version or switches at this time. continue; } case Language.HLSL: { // HLSL compiler is not involved in the mitigations, so no need to check version or switches at this time. continue; } // Mixed binaries (/clr) can contain non C++ compilands if they are linked in via netmodules // .NET IL should be mitigated by the runtime if any mitigations are necessary // At this point simply accept them as safe until this is disproven. case Language.CSharp: case Language.MSIL: case Language.ILASM: { continue; } case Language.Unknown: { // The linker may emit debug information for modules from static libraries that do not contribute to actual code. // do not contribute to actual code. Currently these come back as Language.Unknown :( // TODO: https://github.com/Microsoft/binskim/issues/116 continue; } default: { // TODO: https://github.com/Microsoft/binskim/issues/117 // Review unknown languages for this and all checks } continue; } // Get the appropriate compiler version against which to check this compiland. // check that we are greater than or equal to the first fully supported release: 15.6 first Version omVersion = omDetails.CompilerVersion; CompilerMitigations availableMitigations = GetAvailableMitigations(context, machineType, omVersion); if (availableMitigations == CompilerMitigations.None) { // Built with a compiler version {0} that does not support any Spectre // mitigations. We do not report here. BA2006 will fire instead. continue; } string[] mitigationSwitches = new string[] { "/Qspectre", "/guardspecload" }; SwitchState effectiveState; // Go process the command line to check for switches effectiveState = omDetails.GetSwitchState(mitigationSwitches, null, SwitchState.SwitchDisabled, OrderOfPrecedence.LastWins); if (effectiveState == SwitchState.SwitchDisabled) { SwitchState QSpectreState = SwitchState.SwitchNotFound; SwitchState d2guardspecloadState = SwitchState.SwitchNotFound; if (availableMitigations.HasFlag(CompilerMitigations.QSpectreAvailable)) { QSpectreState = omDetails.GetSwitchState(mitigationSwitches[0] /*"/Qspectre"*/, OrderOfPrecedence.LastWins); } if (availableMitigations.HasFlag(CompilerMitigations.D2GuardSpecLoadAvailable)) { // /d2xxxx options show up in the PDB without the d2 string // So search for just /guardspecload d2guardspecloadState = omDetails.GetSwitchState(mitigationSwitches[1] /*"/guardspecload"*/, OrderOfPrecedence.LastWins); } // TODO: https://github.com/Microsoft/binskim/issues/119 // We should flag cases where /d2guardspecload is enabled but the // toolset supports /qSpectre (which should be preferred). if (QSpectreState == SwitchState.SwitchNotFound && d2guardspecloadState == SwitchState.SwitchNotFound) { // Built with tools that support the Spectre mitigations but these have not been enabled. mitigationNotEnabledModules.Add(om.CreateCompilandRecord()); } else { // Built with the Spectre mitigations explicitly disabled. mitigationExplicitlyDisabledModules.Add(om.CreateCompilandRecord()); } continue; } if (!availableMitigations.HasFlag(CompilerMitigations.NonoptimizedCodeMitigated)) { string[] OdSwitches = { "/Od" }; // These switches override /Od - there is no one place to find this information on msdn at this time. string[] OptimizeSwitches = { "/O1", "/O2", "/Ox", "/Og" }; bool debugEnabled = false; if (omDetails.GetSwitchState(OdSwitches, OptimizeSwitches, SwitchState.SwitchEnabled, OrderOfPrecedence.LastWins) == SwitchState.SwitchEnabled) { debugEnabled = true; } if (debugEnabled) { // Built with /Od which disables Spectre mitigations. mitigationDisabledInDebugBuild.Add(om.CreateCompilandRecord()); continue; } } } string line; var sb = new StringBuilder(); if (!mitigationExplicitlyDisabledModules.Empty) { // The following modules were compiled with Spectre // mitigations explicitly disabled: {0} line = string.Format( RuleResources.BA2024_Error_SpectreMitigationExplicitlyDisabled, mitigationExplicitlyDisabledModules.CreateSortedObjectList()); sb.AppendLine(line); } if (!mitigationNotEnabledModules.Empty) { // The following modules were compiled with a toolset that supports // /Qspectre but the switch was not enabled on the command-line: {0} line = string.Format( RuleResources.BA2024_Error_SpectreMitigationNotEnabled, mitigationNotEnabledModules.CreateSortedObjectList()); sb.AppendLine(line); } if (!mitigationDisabledInDebugBuild.Empty) { // The following modules were compiled with optimizations disabled(/ Od), // a condition that disables Spectre mitigations: {0} line = string.Format( RuleResources.BA2024_Error_OptimizationsDisabled, mitigationDisabledInDebugBuild.CreateSortedObjectList()); sb.AppendLine(line); } if ((context.Policy.GetProperty(Reporting) & ReportingOptions.WarnIfMasmModulesPresent) == ReportingOptions.WarnIfMasmModulesPresent && !masmModules.Empty) { line = string.Format( RuleResources.BA2024_Error_MasmModulesDetected, masmModules.CreateSortedObjectList()); sb.AppendLine(line); } if (sb.Length > 0) { // '{0}' was compiled with one or more modules that do not properly enable code // generation mitigations for speculative execution side-channel attack (Spectre) // vulnerabilities. Spectre attacks can compromise hardware-based isolation, // allowing non-privileged users to retrieve potentially sensitive data from the // CPU cache. To resolve the issue, provide the /Qspectre switch on the compiler // command-line (or /d2guardspecload in cases where your compiler supports this // switch and it is not possible to update to a toolset that supports /Qspectre). // The following modules are out of policy: {1} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2024_Error), context.TargetUri.GetFileName(), sb.ToString())); return; } // All linked modules ‘{0}’ were compiled with mitigations enabled that help prevent Spectre (speculative execution side-channel attack) vulnerabilities. context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Pass, context, null, nameof(RuleResources.BA2024_Pass), context.TargetUri.GetFileName())); }
public override void Analyze(BinaryAnalyzerContext context) { PEHeader peHeader = context.PE.PEHeaders.PEHeader; if (context.Pdb == null) { Errors.LogExceptionLoadingPdb(context, context.PdbParseException.Message); return; } Pdb di = context.Pdb; TruncatedCompilandRecordList warningTooLowModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList disabledWarningModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList unknownLanguageModules = new TruncatedCompilandRecordList(); TruncatedCompilandRecordList allWarningLevelLowModules = new TruncatedCompilandRecordList(); string exampleTooLowWarningCommandLine = null; int overallMinimumWarningLevel = Int32.MaxValue; string exampleDisabledWarningCommandLine = null; List<int> overallDisabledWarnings = new List<int>(); foreach (DisposableEnumerableView<Symbol> omView in di.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails omDetails = om.GetObjectModuleDetails(); if (omDetails.Language == Language.Unknown) { // See if this module contributed to an executable section. If not, we can ignore the module. if (di.CompilandWithIdIsInExecutableSectionContrib(om.SymIndexId)) { unknownLanguageModules.Add(om.CreateCompilandRecord()); } continue; } if ((omDetails.Language != Language.C) && (omDetails.Language != Language.Cxx)) { continue; } if (omDetails.Compiler != "Microsoft (R) Optimizing Compiler") { continue; } if (!om.CreateChildIterator(SymTagEnum.SymTagFunction).Any()) { // uninteresting... continue; } int warningLevel = omDetails.WarningLevel; List<int> requiredDisabledWarnings = omDetails.ExplicitlyDisabledWarnings .Where(context.Policy.GetProperty(RequiredCompilerWarnings).Contains).ToList(); if (warningLevel >= 3 && requiredDisabledWarnings.Count == 0) { // We duplicate this condition to bail out early and avoid writing the // module description or newline into sbBadWarningModules if everything // in the module is OK. continue; } List<string> suffix = new List<string>(2); overallMinimumWarningLevel = Math.Min(overallMinimumWarningLevel, warningLevel); if (warningLevel < 3) { exampleTooLowWarningCommandLine = exampleTooLowWarningCommandLine ?? omDetails.CommandLine; string msg = "[warning level: " + warningLevel.ToString(CultureInfo.InvariantCulture) + "]"; warningTooLowModules.Add(om.CreateCompilandRecordWithSuffix(msg)); suffix.Add(msg); } if (requiredDisabledWarnings.Count != 0) { MergeInto(overallDisabledWarnings, requiredDisabledWarnings); exampleDisabledWarningCommandLine = exampleDisabledWarningCommandLine ?? omDetails.CommandLine; string msg = "[Explicitly disabled warnings: " + CreateTextWarningList(requiredDisabledWarnings) + "]"; disabledWarningModules.Add(om.CreateCompilandRecordWithSuffix(msg)); suffix.Add(msg); } allWarningLevelLowModules.Add(om.CreateCompilandRecordWithSuffix(String.Join(" ", suffix))); } if (unknownLanguageModules.Empty && exampleTooLowWarningCommandLine == null && exampleDisabledWarningCommandLine == null) { // '{0}' was compiled at a secure warning level ({1}) and does not // include any modules that disable specific warnings which are // required by policy. As a result, there is a greater likelihood // that memory corruption, information disclosure, double-free and // other security-related vulnerabilities do not exist in code. context.Logger.Log(this, RuleUtilities.BuildResult(ResultKind.Pass, context, null, nameof(RuleResources.BA2007_Pass), overallMinimumWarningLevel.ToString())); return; } if (!unknownLanguageModules.Empty) { // '{0}' contains code from an unknown language, preventing a // comprehensive analysis of the compiler warning settings. // The language could not be identified for the following modules: {1} context.Logger.Log(this, RuleUtilities.BuildResult(ResultKind.Error, context, null, nameof(RuleResources.BA2007_Fail_UnknownModuleLanguage), unknownLanguageModules.CreateSortedObjectList())); } if (exampleTooLowWarningCommandLine != null) { // '{0}' was compiled at too low a warning level. Warning level 3 enables // important static analysis in the compiler to flag bugs that can lead // to memory corruption, information disclosure, or double-free // vulnerabilities.To resolve this issue, compile at warning level 3 or // higher by supplying / W3, / W4, or / Wall to the compiler, and resolve // the warnings emitted. // An example compiler command line triggering this check: {1} // Modules triggering this check: {2} context.Logger.Log(this, RuleUtilities.BuildResult(ResultKind.Error, context, null, nameof(RuleResources.BA2007_Fail_InsufficientWarningLevel), overallMinimumWarningLevel.ToString(), exampleTooLowWarningCommandLine, warningTooLowModules.CreateTruncatedObjectList())); } if (exampleDisabledWarningCommandLine != null) { // '{0}' disables compiler warning(s) which are required by policy. A // compiler warning is typically required if it has a high likelihood of // flagging memory corruption, information disclosure, or double-free // vulnerabilities. To resolve this issue, enable the indicated warning(s) // by removing /Wxxxx switches (where xxxx is a warning id indicated here) // from your command line, and resolve any warnings subsequently raised // during compilation. // An example compiler command line triggering this check was: {1} // Modules triggering this check were: {2} context.Logger.Log(this, RuleUtilities.BuildResult(ResultKind.Error, context, null, nameof(RuleResources.BA2007_Fail_WarningsDisabled), exampleDisabledWarningCommandLine, disabledWarningModules.CreateTruncatedObjectList())); } }
public override void Analyze(BinaryAnalyzerContext context) { PEHeader peHeader = context.PE.PEHeaders.PEHeader; Pdb pdb = context.Pdb; if (pdb == null) { Errors.LogExceptionLoadingPdb(context, context.PdbParseException); return; } Version minLinkVersion; Version minCompilerVersion; if (context.PE.IsXBox) { minCompilerVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_XBOX_COMPILER_VER]; minLinkVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_XBOX_LINKER_VER]; } else { minCompilerVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_COMPILER_VER]; minLinkVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_LINKER_VER]; } TruncatedCompilandRecordList badModuleList = new TruncatedCompilandRecordList(); StringToVersionMap allowedLibraries = context.Policy.GetProperty(AllowedLibraries); foreach (DisposableEnumerableView <Symbol> omView in pdb.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails omDetails = om.GetObjectModuleDetails(); // see if the item is in our skip list if (!string.IsNullOrEmpty(om.Lib)) { string libFileName = string.Concat(System.IO.Path.GetFileName(om.Lib), ",", omDetails.Language.ToString()).ToLowerInvariant(); Version minAllowedVersion; if (allowedLibraries.TryGetValue(libFileName, out minAllowedVersion) && omDetails.CompilerVersion >= minAllowedVersion) { continue; } } Version actualVersion; Version minimumVersion; Language omLanguage = omDetails.Language; switch (omLanguage) { case Language.C: case Language.Cxx: actualVersion = Minimum(omDetails.CompilerVersion, omDetails.CompilerFrontEndVersion); minimumVersion = minCompilerVersion; break; case Language.MASM: // TODO verify this actualVersion = omDetails.CompilerVersion; minimumVersion = minLinkVersion; break; case Language.LINK: continue; default: continue; } if (actualVersion < minimumVersion) { // built with {0} compiler version {1} (Front end version: {2}) badModuleList.Add( om.CreateCompilandRecordWithSuffix( String.Format(CultureInfo.InvariantCulture, RuleResources.BA2006_Error_BadModule, omLanguage, omDetails.CompilerVersion, omDetails.CompilerFrontEndVersion))); } } if (!badModuleList.Empty) { // '{0}' was compiled with one or more modules which were not built using minimum // required tool versions (compiler version {1}, linker version {2}). More recent // tool chains contain mitigations that make it more difficult for an attacker to // exploit vulnerabilities in programs they produce. To resolve this issue, // compile and/or link your binary with more recent tools. If you are servicing a // product where the tool chain cannot be modified (e.g. producing a hotfix for // an already shipped version) ignore this warning. // Modules built outside of policy: {3} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2006_Error), context.TargetUri.GetFileName(), minCompilerVersion.ToString(), minLinkVersion.ToString(), badModuleList.CreateSortedObjectList())); return; } // '{0}' was built with a tool chain that satisfies configured policy // (compiler minimum version {1}, linker minimum version {2}). context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Pass, context, null, nameof(RuleResources.BA2006_Pass), context.TargetUri.GetFileName(), minCompilerVersion.ToString(), minLinkVersion.ToString())); }
public override void Analyze(BinaryAnalyzerContext context) { PEHeader peHeader = context.PE.PEHeaders.PEHeader; Pdb pdb = context.Pdb; if (pdb == null) { Errors.LogExceptionLoadingPdb(context, context.PdbParseException); return; } Version minLinkVersion; Version minCompilerVersion; if (context.PE.IsXBox) { minCompilerVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_XBOX_COMPILER_VER]; minLinkVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_XBOX_LINKER_VER]; } else { minCompilerVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_COMPILER_VER]; minLinkVersion = context.Policy.GetProperty(MinimumToolVersions)[MIN_LINKER_VER]; } TruncatedCompilandRecordList badModuleList = new TruncatedCompilandRecordList(); StringToVersionMap allowedLibraries = context.Policy.GetProperty(AllowedLibraries); foreach (DisposableEnumerableView<Symbol> omView in pdb.CreateObjectModuleIterator()) { Symbol om = omView.Value; ObjectModuleDetails omDetails = om.GetObjectModuleDetails(); // see if the item is in our skip list if (!string.IsNullOrEmpty(om.Lib)) { string libFileName = string.Concat(System.IO.Path.GetFileName(om.Lib), ",", omDetails.Language.ToString()).ToLowerInvariant(); Version minAllowedVersion; if (allowedLibraries.TryGetValue(libFileName, out minAllowedVersion) && omDetails.CompilerVersion >= minAllowedVersion) { continue; } } Version actualVersion; Version minimumVersion; Language omLanguage = omDetails.Language; switch (omLanguage) { case Language.C: case Language.Cxx: actualVersion = Minimum(omDetails.CompilerVersion, omDetails.CompilerFrontEndVersion); minimumVersion = minCompilerVersion; break; case Language.MASM: // TODO verify this actualVersion = omDetails.CompilerVersion; minimumVersion = minLinkVersion; break; case Language.LINK: continue; default: continue; } if (actualVersion < minimumVersion) { // built with {0} compiler version {1} (Front end version: {2}) badModuleList.Add( om.CreateCompilandRecordWithSuffix( String.Format(CultureInfo.InvariantCulture, RuleResources.BA2006_Error_BadModule, omLanguage, omDetails.CompilerVersion, omDetails.CompilerFrontEndVersion))); } } if (!badModuleList.Empty) { // '{0}' was compiled with one or more modules which were not built using minimum // required tool versions (compiler version {1}, linker version {2}). More recent // tool chains contain mitigations that make it more difficult for an attacker to // exploit vulnerabilities in programs they produce. To resolve this issue, // compile and/or link your binary with more recent tools. If you are servicing a // product where the tool chain cannot be modified (e.g. producing a hotfix for // an already shipped version) ignore this warning. // Modules built outside of policy: {3} context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Error, context, null, nameof(RuleResources.BA2006_Error), context.TargetUri.GetFileName(), minCompilerVersion.ToString(), minLinkVersion.ToString(), badModuleList.CreateSortedObjectList())); return; } // '{0}' was built with a tool chain that satisfies configured policy // (compiler minimum version {1}, linker minimum version {2}). context.Logger.Log(this, RuleUtilities.BuildResult(ResultLevel.Pass, context, null, nameof(RuleResources.BA2006_Pass), context.TargetUri.GetFileName(), minCompilerVersion.ToString(), minLinkVersion.ToString())); }