public Publisher CreatePublisher(string cls, SerializableDictionary <string, Variant> args) { logger.Trace("CreatePublisher: {0}", cls); OnCreatePublisherEvent(cls, args); var type = ClassLoader.FindTypeByAttribute <PublisherAttribute>((x, y) => y.Name == cls); if (type == null) { throw new PeachException("Error, unable to locate Pubilsher '" + cls + "'"); } try { Dictionary <string, Variant> copy = new Dictionary <string, Variant>(); foreach (var kv in args) { copy.Add(kv.Key, kv.Value); } var pub = Activator.CreateInstance(type, copy) as Publisher; return(pub); } catch (TargetInvocationException ex) { throw new PeachException("Could not start publisher \"" + cls + "\". " + ex.InnerException.Message, ex); } }
private void AddAgent(Dom.Agent agentDef) { Uri uri = new Uri(agentDef.location); var type = ClassLoader.FindTypeByAttribute <AgentAttribute>((x, y) => y.protocol == uri.Scheme); if (type == null) { throw new PeachException("Error, unable to locate agent that supports the '" + uri.Scheme + "' protocol."); } var agent = Activator.CreateInstance(type, agentDef.name, agentDef.location, agentDef.password) as AgentClient; _agents[agentDef.name] = agent; _agentDefinitions[agentDef.name] = agentDef; }
public void StartMonitor(string name, string cls, SerializableDictionary <string, Variant> args) { logger.Trace("StartMonitor: {0} {1}", name, cls); OnStartMonitorEvent(name, cls, args); var type = ClassLoader.FindTypeByAttribute <MonitorAttribute>((x, y) => y.Name == cls); if (type == null) { throw new PeachException("Error, unable to locate Monitor '" + cls + "'"); } try { var monitor = Activator.CreateInstance(type, (IAgent)this, name, args) as Monitor; this.monitors.Add(name, monitor); } catch (TargetInvocationException ex) { throw new PeachException("Could not start monitor \"" + cls + "\". " + ex.InnerException.Message, ex); } }
public FormMain() { InitializeComponent(); foreach (var strategy in ClassLoader.GetAllByAttribute <MutationStrategyAttribute>(null)) { comboBoxFuzzingStrategy.Items.Add(strategy.Key.Name); } //tabControl.TabPages.Remove(tabPageGUI); tabControl.TabPages.Remove(tabPageFuzzing); //tabControl.TabPages.Remove(tabPageOutput); LoadPlatformAssembly(); // Check OS and load side assembly Platform.OS os = Platform.GetOS(); switch (os) { case Platform.OS.OSX: tabControl.TabPages.Remove(tabPageDebuggerLinux); tabControl.TabPages.Remove(tabPageDebuggerWin); tabControl.TabPages.Remove(tabPageGUI); richTextBoxOSX.LoadFile(Assembly.GetExecutingAssembly().GetManifestResourceStream("PeachFuzzBang.OSXDebugging.rtf"), RichTextBoxStreamType.RichText); break; case Platform.OS.Linux: tabControl.TabPages.Remove(tabPageDebuggerOSX); tabControl.TabPages.Remove(tabPageDebuggerWin); tabControl.TabPages.Remove(tabPageGUI); richTextBoxLinux.LoadFile(Assembly.GetExecutingAssembly().GetManifestResourceStream("PeachFuzzBang.LinuxDebugging.rtf"), RichTextBoxStreamType.RichText); break; case Platform.OS.Windows: { comboBoxAttachToServiceServices.Items.Clear(); foreach (ServiceController srv in ServiceController.GetServices()) { comboBoxAttachToServiceServices.Items.Add(srv.ServiceName); } textBoxAttachToProcessProcessName.Items.Clear(); foreach (Process proc in Process.GetProcesses()) { textBoxAttachToProcessProcessName.Items.Add(proc.ProcessName); proc.Close(); } tabControl.TabPages.Remove(tabPageDebuggerOSX); tabControl.TabPages.Remove(tabPageDebuggerLinux); if (!Environment.Is64BitProcess && Environment.Is64BitOperatingSystem) { MessageBox.Show("Warning: The 64bit version of Peach 3 must be used on 64 bit Operating Systems.", "Warning"); } string windbg = null; Type t = ClassLoader.FindTypeByAttribute <MonitorAttribute>((x, y) => y.Name == "WindowsDebugger"); if (t != null) { windbg = t.InvokeMember("FindWinDbg", BindingFlags.InvokeMethod, null, null, null) as string; } if (windbg != null) { textBoxDebuggerPath.Text = windbg; } else { textBoxDebuggerPath.Text = "Error, could not locate windbg!"; } } break; } if (os != Platform.OS.Windows) { // Update default settings to include full path to PeachFuzzBang // When double clicking the app to run it, the current working // directory is $HOME string cwd = Environment.CurrentDirectory + Path.DirectorySeparatorChar; string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; if (path.StartsWith(cwd)) { path = path.Substring(cwd.Length); } if (!string.IsNullOrEmpty(path)) { textBoxFuzzedFile.Text = Path.Combine(path, textBoxFuzzedFile.Text); textBoxTemplateFiles.Text = Path.Combine(path, textBoxTemplateFiles.Text); textBoxLinuxArguments.Text = Path.Combine(path, textBoxLinuxArguments.Text); textBoxOSXArguments.Text = Path.Combine(path, textBoxOSXArguments.Text); } } buttonStartFuzzing.Enabled = true; buttonSaveConfiguration.Enabled = false; buttonStopFuzzing.Enabled = false; comboBoxPitDataModel.SelectedIndexChanged += new EventHandler(comboBoxPitDataModel_SelectedIndexChanged); richTextBoxIntroduction.LoadFile(Assembly.GetExecutingAssembly().GetManifestResourceStream("PeachFuzzBang.Introduction.rtf"), RichTextBoxStreamType.RichText); }
public Program(string[] args) { AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload); Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); config = new RunConfiguration(); config.debug = 0; try { string analyzer = null; bool test = false; string agent = null; var definedValues = new List <string>(); bool parseOnly = false; var color = Console.ForegroundColor; Console.Write("\n"); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("[[ "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(ProductName); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("[[ "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(Copyright); Console.ForegroundColor = color; if (args.Length == 0) { Syntax(); } var p = new OptionSet() { { "h|?|help", v => Syntax() }, { "analyzer=", v => analyzer = v }, { "debug", v => config.debug = 1 }, { "trace", v => config.debug = 2 }, { "1", v => config.singleIteration = true }, { "range=", v => ParseRange(config, v) }, { "t|test", v => test = true }, { "c|count", v => config.countOnly = true }, { "skipto=", v => config.skipToIteration = Convert.ToUInt32(v) }, { "seed=", v => config.randomSeed = Convert.ToUInt32(v) }, { "p|parallel=", v => ParseParallel(config, v) }, { "a|agent=", v => agent = v }, { "D|define=", v => AddNewDefine(v) }, { "definedvalues=", v => definedValues.Add(v) }, { "config=", v => definedValues.Add(v) }, { "parseonly", v => parseOnly = true }, { "bob", var => bob() }, //输出他的头像,醉了 { "charlie", var => Charlie() }, //醉了 { "showdevices", var => ShowDevices() }, //列出网卡设备信息 { "showenv", var => ShowEnvironment() }, //输出使用信息?基本属性的使用? { "makexsd", var => MakeSchema() }, //生成Peach.xsd文件 }; List <string> extra = p.Parse(args);//extra[0]存放文件名即 pit文件.xml if (extra.Count == 0 && agent == null && analyzer == null) { Syntax(); } Platform.LoadAssembly(); AddNewDefine("Peach.Cwd=" + Environment.CurrentDirectory); AddNewDefine("Peach.Pwd=" + Path.GetDirectoryName(Assembly.GetCallingAssembly().Location)); // 判断是否有 pit文件.xml.config 文件,如果有我们就加载改文件 // 注意:pit文件.xml.config 应该和 pit文件.xml文件放在同一目录下 if (extra.Count > 0 && File.Exists(extra[0]) && extra[0].ToLower().EndsWith(".xml") && File.Exists(extra[0] + ".config")) { definedValues.Insert(0, extra[0] + ".config"); } foreach (var definedValuesFile in definedValues) { var defs = PitParser.parseDefines(definedValuesFile); foreach (var kv in defs) { // Allow command line to override values in XML file. if (!DefinedValues.ContainsKey(kv.Key)) { DefinedValues.Add(kv.Key, kv.Value); } } } // 如果需要则启动调试 // 如果已经由.congig文件进行配置,则不会做任何更改 ConfigureLogging(config.debug); if (agent != null) { var agentType = ClassLoader.FindTypeByAttribute <AgentServerAttribute>((x, y) => y.name == agent); if (agentType == null) { Console.WriteLine("错误, unable to locate agent server for protocol '" + agent + "'.\n"); return; } var agentServer = Activator.CreateInstance(agentType) as IAgentServer; ConsoleWatcher.WriteInfoMark(); Console.WriteLine("启动代理服务..."); agentServer.Run(new Dictionary <string, string>()); return; } if (analyzer != null) { var analyzerType = ClassLoader.FindTypeByAttribute <AnalyzerAttribute>((x, y) => y.Name == analyzer); if (analyzerType == null) { Console.WriteLine("错误,无法定位名为'" + analyzer + "'的analyzer.\n"); return; } var field = analyzerType.GetField("supportCommandLine", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if ((bool)field.GetValue(null) == false) { Console.WriteLine("错误, 从命令行启动的analyzer还没有进行配置."); return; } var analyzerInstance = Activator.CreateInstance(analyzerType) as Analyzer; ConsoleWatcher.WriteInfoMark(); Console.WriteLine("启动Analyzer..."); analyzerInstance.asCommandLine(new Dictionary <string, string>()); return; } Dictionary <string, object> parserArgs = new Dictionary <string, object>(); parserArgs[PitParser.DEFINED_VALUES] = this.DefinedValues; if (test) { ConsoleWatcher.WriteInfoMark(); Console.Write("Validating file [" + extra[0] + "]... "); Analyzer.defaultParser.asParserValidation(parserArgs, extra[0]); if (Type.GetType("Mono.Runtime") != null) { Console.WriteLine("File parsed successfully, but XSD validation is not supported on the Mono runtime."); } else { Console.WriteLine("No Errors Found."); } return; } Engine e = new Engine(GetUIWatcher()); dom = GetParser(e).asParser(parserArgs, extra[0]); config.pitFile = extra[0]; // 用于单元测试 if (parseOnly) { return; } foreach (string arg in args) { config.commandLine += arg + " "; } if (extra.Count > 1) { config.runName = extra[1]; } e.startFuzzing(dom, config); exitCode = 0; } catch (SyntaxException) { // 由syntax()抛出,可忽略 } catch (OptionException oe) { Console.WriteLine(oe.Message + "\n"); } catch (PeachException ee) { if (config.debug > 0) { Console.WriteLine(ee); } else { Console.WriteLine(ee.Message + "\n"); } } finally { // HACK - 需使用NLog 2.0的Mono ConfigureLogging(-1); // 重置控制台输出文字的颜色 Console.ForegroundColor = DefaultForground; } }
void AddDataElement(string name, Type type) { var schemaElem = MakeItem <XmlSchemaElement>(name, type, objElemCache); var complexType = new XmlSchemaComplexType(); var schemaParticle = new XmlSchemaChoice(); schemaParticle.MinOccursString = "0"; schemaParticle.MaxOccursString = "unbounded"; foreach (var prop in type.GetAttributes <ParameterAttribute>()) { var attr = MakeAttribute(prop.name, prop); complexType.Attributes.Add(attr); } var deAttr = type.GetAttributes <Peach.Core.Dom.DataElementAttribute>().First(); if (deAttr.elementTypes.HasFlag(Peach.Core.Dom.DataElementTypes.DataElements)) { foreach (var kv in ClassLoader.GetAllByAttribute <Peach.Core.Dom.DataElementAttribute>(null)) { var parents = kv.Value.GetAttributes <Peach.Core.Dom.DataElementParentSupportedAttribute>(); if (parents.Any() && !parents.Any(a => a.elementName == name)) { continue; } var elem = MakeDataElement(kv.Key.elementName, kv.Value); schemaParticle.Items.Add(elem); } } foreach (var child in type.GetAttributes <Peach.Core.Dom.DataElementChildSupportedAttribute>()) { var childType = ClassLoader.FindTypeByAttribute <Peach.Core.Dom.DataElementAttribute>((t, a) => a.elementName == child.elementName); var elem = MakeDataElement(child.elementName, childType); schemaParticle.Items.Add(elem); } if (deAttr.elementTypes.HasFlag(Peach.Core.Dom.DataElementTypes.Fixup)) { PopulateDataElement(schemaParticle, "Fixup"); } if (deAttr.elementTypes.HasFlag(Peach.Core.Dom.DataElementTypes.Hint)) { var elems = MakeElement("Hint", null, typeof(DataModel).GetProperty("Hint"), null); foreach (var elem in elems) { elem.MinOccursString = null; elem.MaxOccursString = null; schemaParticle.Items.Add(elem); } } if (deAttr.elementTypes.HasFlag(Peach.Core.Dom.DataElementTypes.Transformer)) { PopulateDataElement(schemaParticle, "Transformer"); } if (deAttr.elementTypes.HasFlag(Peach.Core.Dom.DataElementTypes.Relation)) { PopulateDataElement(schemaParticle, "Relation"); } if (deAttr.elementTypes.HasFlag(Peach.Core.Dom.DataElementTypes.Analyzer)) { PopulateDataElement(schemaParticle, "Analyzer"); } if (schemaParticle.Items.Count > 0) { complexType.Particle = schemaParticle; } schemaElem.SchemaType = complexType; }
public Program(string[] args) { AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload); Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); RunConfiguration config = new RunConfiguration(); config.debug = false; try { string analyzer = null; bool test = false; string agent = null; var definedValues = new List <string>(); bool parseOnly = false; var color = Console.ForegroundColor; Console.Write("\n"); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("[[ "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(ProductName); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("[[ "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(Copyright); Console.WriteLine(); Console.ForegroundColor = color; if (args.Length == 0) { Syntax(); } var p = new OptionSet() { { "h|?|help", v => Syntax() }, { "analyzer=", v => analyzer = v }, { "debug", v => config.debug = true }, { "1", v => config.singleIteration = true }, { "range=", v => ParseRange(config, v) }, { "t|test", v => test = true }, { "c|count", v => config.countOnly = true }, { "skipto=", v => config.skipToIteration = Convert.ToUInt32(v) }, { "seed=", v => config.randomSeed = Convert.ToUInt32(v) }, { "p|parallel=", v => ParseParallel(config, v) }, { "a|agent=", v => agent = v }, { "D|define=", v => AddNewDefine(v) }, { "definedvalues=", v => definedValues.Add(v) }, { "parseonly", v => parseOnly = true }, { "bob", var => bob() }, { "charlie", var => Charlie() }, { "showdevices", var => ShowDevices() }, { "showenv", var => ShowEnvironment() }, { "inputFilePath=", v => config.inputFilePath = v }, { "outputFilePath=", v => config.outputFilePath = v }, }; List <string> extra = p.Parse(args); if (extra.Count == 0 && agent == null && analyzer == null) { Syntax(); } Platform.LoadAssembly(); AddNewDefine("Peach.Cwd=" + Environment.CurrentDirectory); foreach (var definedValuesFile in definedValues) { var defs = PitParser.parseDefines(definedValuesFile); foreach (var kv in defs) { // Allow command line to override values in XML file. if (!DefinedValues.ContainsKey(kv.Key)) { DefinedValues.Add(kv.Key, kv.Value); } } } // Enable debugging if asked for if (config.debug) { var nconfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); nconfig.AddTarget("console", consoleTarget); consoleTarget.Layout = "${logger} ${message}"; var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); nconfig.LoggingRules.Add(rule); LogManager.Configuration = nconfig; } if (agent != null) { var agentType = ClassLoader.FindTypeByAttribute <AgentServerAttribute>((x, y) => y.name == agent); if (agentType == null) { Console.WriteLine("Error, unable to locate agent server for protocol '" + agent + "'.\n"); return; } var agentServer = Activator.CreateInstance(agentType) as IAgentServer; ConsoleWatcher.WriteInfoMark(); Console.WriteLine("Starting agent server"); agentServer.Run(new Dictionary <string, string>()); return; } if (analyzer != null) { var analyzerType = ClassLoader.FindTypeByAttribute <AnalyzerAttribute>((x, y) => y.Name == analyzer); if (analyzerType == null) { Console.WriteLine("Error, unable to locate analyzer called '" + analyzer + "'.\n"); return; } var field = analyzerType.GetField("supportCommandLine", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if ((bool)field.GetValue(null) == false) { Console.WriteLine("Error, analyzer not configured to run from command line."); return; } var analyzerInstance = Activator.CreateInstance(analyzerType) as Analyzer; ConsoleWatcher.WriteInfoMark(); Console.WriteLine("Starting Analyzer"); analyzerInstance.asCommandLine(new Dictionary <string, string>()); return; } Dictionary <string, object> parserArgs = new Dictionary <string, object>(); parserArgs[PitParser.DEFINED_VALUES] = this.DefinedValues; if (test) { ConsoleWatcher.WriteInfoMark(); Console.Write("Validating file [" + extra[0] + "]... "); Analyzer.defaultParser.asParserValidation(parserArgs, extra[0]); if (Type.GetType("Mono.Runtime") != null) { Console.WriteLine("File parsed successfully, but XSD validation is not supported on the Mono runtime."); } else { Console.WriteLine("No Errors Found."); } return; } Engine e = new Engine(GetUIWatcher()); dom = GetParser(e).asParser(parserArgs, extra[0]); config.pitFile = extra[0]; // Used for unittests if (parseOnly) { return; } foreach (string arg in args) { config.commandLine += arg + " "; } if (extra.Count > 1) { if (!dom.tests.ContainsKey(extra[1])) { throw new PeachException("Error, unable to locate test named \"" + extra[1] + "\"."); } e.startFuzzing(dom, dom.tests[extra[1]], config); } else { e.startFuzzing(dom, config); } exitCode = 0; } catch (SyntaxException) { // Ignore, thrown by syntax() } catch (OptionException oe) { Console.WriteLine(oe.Message + "\n"); } catch (PeachException ee) { if (config.debug) { Console.WriteLine(ee); } else { Console.WriteLine(ee.Message + "\n"); } } finally { // HACK - Required on Mono with NLog 2.0 LogManager.Configuration = null; // Reset console colors Console.ForegroundColor = DefaultForground; } }