public static MachineFamily GetMachineFamily(this ExtendedMachine extendedMachine) { if (extendedMachine.IsArmFamily()) { return(MachineFamily.Arm); } if (extendedMachine.IsX86Family()) { return(MachineFamily.X86); } return(MachineFamily.Unknown); }
public static bool IsX86Family(this ExtendedMachine machine) { bool isFamily = false; switch (machine) { case ExtendedMachine.Amd64: case ExtendedMachine.I386: isFamily = true; break; default: break; } return(isFamily); }
public static bool IsArmFamily(this ExtendedMachine machine) { bool isFamily = false; switch (machine) { case ExtendedMachine.Arm: case ExtendedMachine.Arm64: case ExtendedMachine.ArmThumb2: isFamily = true; break; default: break; } return(isFamily); }
public void GetCompilerData_VersionPresent_WorksAsExpected(string versionStr, ExtendedMachine machine, CompilerMitigations expectedMitgations) { var context = new BinaryAnalyzerContext { Policy = new PropertiesDictionary() }; this.AddFakeConfigTestData(context.Policy); CompilerMitigations actualMitigations = EnableSpectreMitigations.GetAvailableMitigations(context, machine, new Version(versionStr)); Assert.Equal(expectedMitgations, actualMitigations); }
public void GetNextCompilerVersionUp_WithSpectreMitigations_WorksAsExpected(string firstVersionStr, ExtendedMachine machine, string expectedVersionStr) { var actualVersion = new Version(firstVersionStr); var context = new BinaryAnalyzerContext { Policy = new PropertiesDictionary() }; this.AddFakeConfigTestData(context.Policy); Version nextUp = EnableSpectreMitigations.GetClosestCompilerVersionWithSpectreMitigations(context, machine, actualVersion); nextUp.ShouldBeEquivalentTo(new Version(expectedVersionStr)); }
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 static bool CanBeMitigated(this ExtendedMachine machine) { return(IsArmFamily(machine) || IsX86Family(machine)); }
/// <summary> /// Get the Spectre compiler compiler mitigations available for a particular compiler version and machine type. /// </summary> internal static CompilerMitigations GetAvailableMitigations(BinaryAnalyzerContext context, ExtendedMachine machine, Version omVersion) { var compilerMitigationData = LoadCompilerDataFromConfig(context.Policy); var machineFamily = machine.GetMachineFamily(); if (!compilerMitigationData.ContainsKey(machineFamily)) { return(CompilerMitigations.None); } else { var listOfMitigatedCompilers = compilerMitigationData[machineFamily]; for (int i = 0; i < listOfMitigatedCompilers.Length; i++) { if (omVersion >= listOfMitigatedCompilers[i].MinimalSupportedVersion && omVersion < listOfMitigatedCompilers[i].MaximumSupportedVersion) { return(listOfMitigatedCompilers[i].SupportedMitigations); } } } return(CompilerMitigations.None); }
internal static Version GetClosestCompilerVersionWithSpectreMitigations(BinaryAnalyzerContext context, ExtendedMachine machine, Version omVersion) { var compilerMitigationData = LoadCompilerDataFromConfig(context.Policy); var machineFamily = machine.GetMachineFamily(); if (!compilerMitigationData.ContainsKey(machineFamily)) { // Mitigations are not supported on this platform at all. No appropriate 'closest compiler version'. return(null); } else { var listOfMitigatedCompilers = compilerMitigationData[machineFamily]; // If the compiler version is not supported, then either: // 1) it is earlier than any supported compiler version // 2) it is in-between two supported compiler versions (e.x. VS2017.1-4)--it is larger than some supported version numbers and smaller than others. // 3) it's greater than any of them. // We want to give users the 'next greatest' compiler version that supports the spectre mitigations--this should be the "smallest available upgrade." Version previousMaximum = new Version(0, 0, 0, 0); for (int i = 0; i < listOfMitigatedCompilers.Length; i++) { if (omVersion > previousMaximum && omVersion <= listOfMitigatedCompilers[i].MinimalSupportedVersion && (listOfMitigatedCompilers[i].SupportedMitigations & (CompilerMitigations.QSpectreAvailable | CompilerMitigations.D2GuardSpecLoadAvailable)) != 0) { return(listOfMitigatedCompilers[i].MinimalSupportedVersion); } else { previousMaximum = listOfMitigatedCompilers[i].MaximumSupportedVersion; } } // If we're here, we're in situation (3)--the compiler is greater than any we recognize. We'll return the largest compiler we know supports Spectre mitigations. // With appropriate configuration (i.e. a catch-all entry with a maximum of *.*.*.* is present), we should never really hit this case. return(listOfMitigatedCompilers[listOfMitigatedCompilers.Length - 1].MinimalSupportedVersion); } }
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 static MachineFamily GetMachineFamily(this ExtendedMachine extendedMachine) { return(extendedMachine.IsArmFamily() ? MachineFamily.Arm : extendedMachine.IsX86Family() ? MachineFamily.X86 : MachineFamily.Unknown); }