Example #1
0
        private static void _doFaultSimTrace(MyConfig simConfig, IBinInfo binInfo, IEnumerable <TraceRange> glitchRange,
                                             out Trace correctSignTraceDataOut, out Trace wrongSignTraceDataOut)
        {
            Trace correctSignTraceData = null;
            Trace wrongSignTraceData   = null;

            try {
                var normalFipSim = new Simulator(simConfig);

                simConfig.UseAltData = true;
                var altFipSim = new Simulator(simConfig);

                var task1 = Task.Run(() => {
                    Console.WriteLine("Start correct sign trace");

                    Result correctSignResult;
                    (correctSignResult, correctSignTraceData) = normalFipSim.TraceSimulation();

                    if (correctSignResult != Result.Completed)
                    {
                        Console.Out.WriteLine("Simulation did not complete; result: " + correctSignResult);
                        Environment.Exit(-1);
                    }

                    Console.WriteLine("Finished correct sign trace");
                });

                var task2 = Task.Run(() => {
                    Console.WriteLine("Start wrong sign trace");

                    Result wrongSignResult;
                    (wrongSignResult, wrongSignTraceData) = altFipSim.TraceSimulation(glitchRange);

                    if (wrongSignResult != Result.Failed && wrongSignResult != Result.Timeout)
                    {
                        Console.Out.WriteLine("Simulation did not fail; result: " + wrongSignResult);
                        Environment.Exit(-1);
                    }

                    Console.WriteLine("Finished wrong sign trace");
                });

                task1.Wait();
                task2.Wait();
            }
            catch (SimulationException ex) {
                Console.Out.WriteLine(ex.Message);
                Console.Out.WriteLine();

                if (ex is PlatformEngineException exception)
                {
                    exception.Engine.DumpState(Console.Out, binInfo);
                }

                Environment.Exit(-1);
            }

            correctSignTraceDataOut = correctSignTraceData;
            wrongSignTraceDataOut   = wrongSignTraceData;
        }
Example #2
0
        private static void _doGUIFaultSim(MyConfig simConfig, IBinInfo binInfo, IFaultModel[] faultModels, IEnumerable <TraceRange> glitchRange)
        {
            Console.WriteLine("Starting simulation... This will take several minutes.");

            // Good / Bad simulation
            _doFaultSimTrace(simConfig, binInfo, glitchRange, out var correctSignTraceData, out var wrongSignTraceData);

            Console.Out.Write($"{correctSignTraceData.AmountInstuctionsExecuted}/{correctSignTraceData.AmountUniqueInstuctionsExecuted} " +
                              $"{wrongSignTraceData.AmountInstuctionsExecuted}/{wrongSignTraceData.AmountUniqueInstuctionsExecuted}");

            var totalRuns = 0ul;

            foreach (var faultModel in faultModels)
            {
                totalRuns += faultModel.CountUniqueFaults(wrongSignTraceData);
            }

            Console.Out.WriteLine(" " + faultModels.Length + "/" + totalRuns);
            Console.Error.WriteLine(totalRuns);

            simConfig.UseAltData = true;

            var faultSim = new FaultSimulator(simConfig);

            faultSim.OnGlitchSimulationCompleted += (runs, eng, result) => {
                Console.Error.WriteLine($"{result.Fault.FaultModel.Name}::{result.Result}::{result.Fault.FaultAddress:x8}::" +
                                        $"{result.Fault.ToString()}::{(result.Result == Result.Exception?result.Exception.Message:"")}");

                return(false);
            };

            faultSim.RunSimulation(faultModels, wrongSignTraceData);

            Environment.Exit(0);
        }
Example #3
0
        private static void _doABVerificationTestSim(MyConfig simConfig, IBinInfo binInfo)
        {
            try {
                Console.Out.WriteLine("Verify functional behavior...");

                // *** GOOD SIGN *** //
                var sim = new Simulator(simConfig);

                sim.Config.BreakPoints.Add(binInfo.Symbols["serial_putc"].Address, eng => {
                    Console.Out.Write((char)eng.RegRead(Arm.UC_ARM_REG_R0));
                });

                var simResult = sim.RunSimulation();

                if (simResult != Result.Completed)
                {
                    Console.Out.WriteLine("Incorrect behavior (" + simResult + ") with signed payload!");
                    Environment.Exit(-1);
                }

                // *** Incorrect SIGN *** //
                simConfig.UseAltData = true;

                ((OtpPeripheral)simConfig.AddressSpace[0x12000000]).PersistentChanges = false;

                sim = new Simulator(simConfig);

                sim.Config.BreakPoints.Add(binInfo.Symbols["serial_putc"].Address, eng => {
                    Console.Out.Write((char)eng.RegRead(Arm.UC_ARM_REG_R0));
                });

                simResult = sim.RunSimulation();

                if (simResult != Result.Failed && simResult != Result.Timeout)
                {
                    Console.Out.WriteLine($"Incorrect behavior ({simResult.ToString()}) with incorrectly signed payload!");
                    Environment.Exit(-1);
                }

                Console.Out.WriteLine("Verification finished. Bootloader is verified to work as intended.");
                Environment.Exit(0);
            }
            catch (SimulationException ex) {
                Console.Out.WriteLine(ex.Message);
                Console.Out.WriteLine();

                if (ex is PlatformEngineException exception)
                {
                    exception.Engine.DumpState(Console.Out, binInfo);
                }

                Environment.Exit(-1);
            }
        }
Example #4
0
        private static void _doNormalExecutionSim(MyConfig simConfig, IBinInfo binInfo)
        {
            // enable serial
            simConfig.BreakPoints.Add(binInfo.Symbols["serial_putc"].Address, eng => {
                Console.Write((char)eng.RegRead(Arm.UC_ARM_REG_R0));
            });

            var sim = new Simulator(simConfig);

            var simResult = sim.RunSimulation();

            Console.WriteLine("Result: " + simResult);
        }
Example #5
0
        private bool _loadAssemblyToSourceInfo(TextWriter outputWriter, string binaryPath, ulong loadingVa, ulong binaryVa)
        {
            try {
                _binInfo = BinInfoFactory.GetBinInfo(binaryPath);
            }
            catch (Exception e) {
                outputWriter.WriteLine(e);

                return(false);
            }

            return(true);
        }
Example #6
0
        protected override void DumpBackTrace(TextWriter outputWriter, IBinInfo binInfo)
        {
            var frameNr = 0;

            var currentPc = Engine.RegRead(ArchInfo.PC);
            var currentFramePointerAddress = Engine.RegRead(ArchInfo.FP);
            var currentLrAddress           = Engine.RegRead(Simulation.Engine.ArchInfo.AArch64.LR);

            var lastFrame    = false;
            var didLastFrame = false;

            while (Config.AddressSpace.IsMapped(currentLrAddress - 4) && !didLastFrame)
            {
                if (!lastFrame)
                {
                    outputWriter.WriteLine($"#{frameNr++} {currentPc:X16} {binInfo.Symbolize(currentPc)} (LR: {currentLrAddress:X16} FP: {currentFramePointerAddress:X16})");

                    if (Config.AddressSpace.IsInRegion(Config.AddressSpace.GetRegion(Config.StackBase), currentFramePointerAddress, 8))
                    {
                        var storedFpData = new byte[8];
                        var storedLrData = new byte[8];

                        Engine.MemRead(currentFramePointerAddress + 0, storedFpData);
                        Engine.MemRead(currentFramePointerAddress + 8, storedLrData);

                        var storedFp = BitConverter.ToUInt64(storedFpData, 0);
                        var storedLr = BitConverter.ToUInt64(storedLrData, 0);

                        currentPc = currentLrAddress - 4;
                        currentFramePointerAddress = storedFp;
                        currentLrAddress           = storedLr;
                    }
                    else
                    {
                        currentPc = currentLrAddress - 4;

                        lastFrame = true;
                    }
                }
                else
                {
                    outputWriter.WriteLine($"#{frameNr++} {currentPc:X16} {binInfo.Symbolize(currentPc)}");

                    didLastFrame = true;
                }
            }
        }
Example #7
0
        private static void _doTUIFaultSim(MyConfig simConfig, IBinInfo binInfo, IFaultModel[] faultModels, IEnumerable <TraceRange> glitchRange)
        {
            Console.WriteLine("Starting simulation... This will take several minutes.");

            // Good / Bad simulation
            _doFaultSimTrace(simConfig, binInfo, glitchRange, out var correctSignTraceData, out var wrongSignTraceData);

            simConfig.UseAltData = true;

            var faultSim = new FaultSimulator(simConfig);

            faultSim.OnGlitchSimulationCompleted += (runs, eng, result) => {
                if (result.Result == Result.Completed)
                {
                    Console.WriteLine($"{result.Fault.FaultModel.Name} {result.Fault.ToString()} {binInfo.Symbolize(result.Fault.FaultAddress)}");
                }

                return(false);
            };

            faultSim.RunSimulation(faultModels, wrongSignTraceData);

            Environment.Exit(0);
        }
Example #8
0
        public static Dictionary <string, List <ISymbolInfo> > LoadSymbolInfo(IBinInfo binPath, string toolPath = "", string toolPrefix = "", string toolName = "nm")
        {
            var nmPath = Path.GetFullPath(Path.Combine(toolPath, toolPrefix + toolName));

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                nmPath = nmPath + ".exe";
            }

            Console.WriteLine(binPath.Path);

            if (!File.Exists(nmPath))
            {
                throw new Exception("nm missing: " + nmPath);
            }

            var process = new Process {
                StartInfo =
                {
                    FileName               = nmPath,
                    Arguments              = $"-S \"{CommandLineEncoder.EncodeArgText(binPath.Path)}\"",
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true
                }
            };

            process.Start();

            var symbolInfo = new Dictionary <string, List <ISymbolInfo> >();

            while (!process.StandardOutput.EndOfStream)
            {
                var line = process.StandardOutput.ReadLine()?.Trim();

                var matchWithSize    = Regex.Match(line, @"^([0-9a-fA-F]+) ([0-9a-fA-F]+) ([a-zA-Z]) ([a-zA-Z0-9_]+)$");
                var matchWithoutSize = Regex.Match(line, @"^([0-9a-fA-F]+) ([a-zA-Z]) ([a-zA-Z0-9_]+)$");

                if (matchWithSize.Success)
                {
                    var address  = ulong.Parse(matchWithSize.Groups[1].Value, NumberStyles.HexNumber);
                    var size     = ulong.Parse(matchWithSize.Groups[2].Value, NumberStyles.HexNumber);
                    var funcName = matchWithSize.Groups[4].Value;

                    if (!symbolInfo.ContainsKey(funcName))
                    {
                        symbolInfo.Add(funcName, new List <ISymbolInfo>());
                    }

                    symbolInfo[funcName].Add(new SymbolInfo {
                        Address = address, Size = size, Name = funcName
                    });
                }
                else if (matchWithoutSize.Success)
                {
                    var address  = ulong.Parse(matchWithoutSize.Groups[1].Value, NumberStyles.HexNumber);
                    var funcName = matchWithoutSize.Groups[3].Value;

                    if (!symbolInfo.ContainsKey(funcName))
                    {
                        symbolInfo.Add(funcName, new List <ISymbolInfo>());
                    }

                    symbolInfo[funcName].Add(new SymbolInfo {
                        Address = address, Size = 0, Name = funcName
                    });
                }
            }

            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                throw new InvalidOperationException();
            }

            return(symbolInfo);
        }