/// <summary> /// This creates an RPC server that has endpoints for all the HostAPIs, then creates an elevated process that can call back into this process to report progress. /// /// /// </summary> /// <param name="script"></param> /// <returns></returns> internal int InvokeElevatedViaRPC(string script) { var guid = Guid.NewGuid(); // set up the server IPC channel var serverChannel = new IpcServerChannel(guid.ToString()); ChannelServices.RegisterChannel(serverChannel, true); // RemotingConfiguration.RegisterWellKnownServiceType( typeof(ChocolateyRequest), "Request", WellKnownObjectMode.Singleton); var objRef = RemotingServices.Marshal(_request); // Create the client elevated var process = AsyncProcess.Start(new ProcessStartInfo { FileName = ChocolateyRequest.NuGetExePath, Arguments = string.Format("-rpc {0}", objRef.URI), // WorkingDirectory = workingDirectory, WindowStyle = ProcessWindowStyle.Hidden, Verb = "runas", }); process.WaitForExit(); RemotingServices.Disconnect(_request); return 0; }
private void Form1_Load(object sender, EventArgs e) { // Initialise the IPC server ScreenshotServer = RemoteHooking.IpcCreateServer <ScreenshotInterface.ScreenshotInterface>( ref ChannelName, WellKnownObjectMode.Singleton); ScreenshotManager.OnScreenshotDebugMessage += new ScreenshotDebugMessage(ScreenshotManager_OnScreenshotDebugMessage); }
private void StartIpcServer() { LogTo.Debug("Starting Plugin IPC Server"); // Generate random channel name IpcServerChannelName = RemotingServicesEx.GenerateIpcServerChannelName(); IpcServer = RemotingServicesEx.CreateIpcServer <ISMAPluginManager, PluginManager>(this, IpcServerChannelName); }
public void InitServer(string serverName) { ServerChannel = new IpcServerChannel(serverName); ChannelServices.RegisterChannel(ServerChannel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "IPCDataManager", WellKnownObjectMode.Singleton); IPCObject = new RemoteObject(); }
private void Detach() { ButtplugGameVibrationRouterInterface.Detach(); _processTab.Attached = false; _channelName = null; _xinputHookServer = null; runTimer.Enabled = false; commandTimer.Enabled = false; }
public void Start() { var distributedObject = new DistributedObject(); var channel = new IpcServerChannel("DistributedChannel"); ChannelServices.RegisterChannel(channel, true); RemotingServices.Marshal(distributedObject, "DistributedObject"); }
/// <summary> /// Creates <see cref="System.Threading.Semaphore"/> to start remoting. /// </summary> /// <param name="name">Name</param> /// <param name="args">Arguments to another instance</param> /// <returns> /// <para>success: True if no other instance exists and this instance successfully creates</para> /// <para>response: Response from another instance if that instance exists and returns an response</para> /// </returns> public (bool success, object response) Create(string name, string[] args) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } // Determine Semaphore name and IPC port name. var semaphoreName = $"semaphore-{name}"; var ipcPortName = $"port-{name}"; const string ipcUri = "space"; _semaphore = new Semaphore(1, 1, semaphoreName, out bool createdNew); if (createdNew) { try { // Instantiate a server channel and register it. _server = new IpcServerChannel(ipcPortName); ChannelServices.RegisterChannel(_server, true); // Instantiate a remoting object and publish it. _space = new RemotingSpace(); RemotingServices.Marshal(_space, ipcUri, typeof(RemotingSpace)); } catch (RemotingException ex) { Debug.WriteLine("Failed to start remoting as server." + Environment.NewLine + ex); } return(success : true, null); } else { object response = null; try { // Instantiate a client channel and register it. var client = new IpcClientChannel(); ChannelServices.RegisterChannel(client, true); // Set a proxy for a remoting object instantiated by another instance. var ipcPath = $"ipc://{ipcPortName}/{ipcUri}"; _space = Activator.GetObject(typeof(RemotingSpace), ipcPath) as RemotingSpace; // Request that instance to take an action. If it is older version, RemotingException // will be thrown because the remoting object has no such method. response = _space?.Request(args); } catch (RemotingException ex) { Debug.WriteLine("Failed to start remoting as client." + Environment.NewLine + ex); } return(success : false, response); } }
internal static void StartRemoteService(IServiceProvider serviceProvider) { Process currentProcess = Process.GetCurrentProcess(); BlendServer.remoteHelper = new BlendServer(serviceProvider); BlendServer.serverChannel = new IpcServerChannel(BlendServer.BlendServerPipe + currentProcess.Id.ToString((IFormatProvider)CultureInfo.InvariantCulture)); ChannelServices.RegisterChannel((IChannel)BlendServer.serverChannel, false); RemotingServices.Marshal((MarshalByRefObject)BlendServer.remoteHelper, typeof(IBlendServer).Name); }
public IpcServer(int pid) { var channel = new IpcServerChannel(Constants.ChannelName); ChannelServices.RegisterChannel(channel, ensureSecurity: true); Pid = new PIDInfo(pid); RemotingServices.Marshal(Pid, Constants.UriName, typeof(PIDInfo)); }
public static int Inject() { // Find the process var process = FindRemotePlayProcess(); if (process == null) { throw new InterceptorException(string.Format("{0} not found in list of processes", TARGET_PROCESS_NAME)); } // Full path to our dll file string injectionLibrary = Path.Combine(Path.GetDirectoryName(typeof(InjectionInterface).Assembly.Location), INJECT_DLL_NAME); try { bool shouldInject = false; if (InjectionMode == InjectionMode.Auto) { if (_ipcServer == null) { // Setup remote hooking _channelName = DateTime.Now.ToString(); _ipcServer = RemoteHooking.IpcCreateServer <InjectionInterface>(ref _channelName, WellKnownObjectMode.Singleton, WellKnownSidType.WorldSid); shouldInject = true; } } else if (InjectionMode == InjectionMode.Compatibility) { // Setup remote hooking _channelName = null; _ipcServer = RemoteHooking.IpcCreateServer <InjectionInterface>(ref _channelName, WellKnownObjectMode.Singleton); shouldInject = true; } // Inject dll into the process if (shouldInject) { RemoteHooking.Inject( process.Id, // ID of process to inject into (_noGAC ? InjectionOptions.DoNotRequireStrongName : InjectionOptions.Default), // if not using GAC allow assembly without strong name injectionLibrary, // 32-bit version (the same because AnyCPU) injectionLibrary, // 64-bit version (the same because AnyCPU) _channelName ); } // Success return(process.Id); } catch (Exception ex) { throw new InterceptorException(string.Format("Failed to inject to target: {0}", ex.Message), ex); } }
/// <summary> /// Prepares capturing in the target process. Note that the process must not already be hooked, and must have a /// <see cref="Process.MainWindowHandle" />. /// </summary> /// <param name="process">The process to inject into</param> /// <exception cref="ProcessHasNoWindowHandleException"> /// Thrown if the <paramref name="process" /> does not have a window /// handle. This could mean that the process does not have a UI, or that the process has not yet finished starting. /// </exception> /// <exception cref="ProcessAlreadyHookedException">Thrown if the <paramref name="process" /> is already hooked</exception> /// <exception cref="InjectionFailedException">Thrown if the injection failed - see the InnerException for more details.</exception> /// <remarks>The target process will have its main window brought to the foreground after successful injection.</remarks> public CaptureProcess(Process process, CaptureConfig config, CaptureInterface captureInterface) { // If the process doesn't have a mainwindowhandle yet, skip it (we need to be able to get the hwnd to set foreground etc) if (process.MainWindowHandle == IntPtr.Zero) { throw new ProcessHasNoWindowHandleException(); } // Skip if the process is already hooked (and we want to hook multiple applications) if (HookManager.IsHooked(process.Id)) { throw new ProcessAlreadyHookedException(); } captureInterface.ProcessId = process.Id; CaptureInterface = captureInterface; //_serverInterface = new CaptureInterface() { ProcessId = process.Id }; // Initialise the IPC server (with our instance of _serverInterface) _screenshotServer = RemoteHooking.IpcCreateServer( ref _channelName, WellKnownObjectMode.Singleton, CaptureInterface); try { // Inject DLL into target process RemoteHooking.Inject( process.Id, InjectionOptions.Default, typeof(CaptureInterface).Assembly.Location, //"Capture.dll", // 32-bit version (the same because AnyCPU) could use different assembly that links to 32-bit C++ helper dll typeof(CaptureInterface).Assembly.Location, //"Capture.dll", // 64-bit version (the same because AnyCPU) could use different assembly that links to 64-bit C++ helper dll // the optional parameter list... _channelName, // The name of the IPC channel for the injected assembly to connect to config ); } catch (Exception e) { throw new InjectionFailedException(e); } HookManager.AddHookedProcess(process.Id); Process = process; // Ensure the target process is in the foreground, // this prevents an issue where the target app appears to be in // the foreground but does not receive any user inputs. // Note: the first Alt+Tab out of the target application after injection // may still be an issue - switching between windowed and // fullscreen fixes the issue however (see ScreenshotInjection.cs for another option) BringProcessWindowToFront(); }
/// <summary> /// Cleanup unneeded resources upon disposal. /// </summary> protected override void OnCleanup() { if (channel != null) { ChannelServices.UnregisterChannel(channel); channel = null; } base.OnCleanup(); }
protected ServerInterface() { InjectionLibrary = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new NullReferenceException(), "SMHackCore.dll"); ServerChannel = RemoteHooking.IpcCreateServer( ref ChannelName, WellKnownObjectMode.Singleton, this); }
public static void StopInjection() { if (_ipcServer == null) { return; } _ipcServer.StopListening(null); _ipcServer = null; }
public ScreenCapturer(ScreenshotRequestResponseNotification notify) { // Initialise the IPC server ScreenshotServer = RemoteHooking.IpcCreateServer <ScreenshotInterface.ScreenshotInterface>( ref ChannelName, WellKnownObjectMode.Singleton); Trace.TraceInformation("IPC server started, channel ref: {0}", ChannelName); this.notify = notify; }
/// <summary> /// This is run by the first instance of the program in order /// to accept information from later instances using the /// .NET Framework's IPC mechanism. /// </summary> public void ListenForSuccessor() { IpcServerChannel serverChannel = new IpcServerChannel("DocListUploader"); ChannelServices.RegisterChannel(serverChannel, false); RemoteMessage remoteMessage = new RemoteMessage(this); RemotingServices.Marshal(remoteMessage, "FirstInstance"); }
public override void Stop() { _stopped = true; if (_screenshotServer != null) { _screenshotServer.StopListening(null); _screenshotServer = null; } _channelName = null; }
public static void Cleanup() { Utility.SafeDispose(ref _singleInstanceMutex); if (_channel != null) { ChannelServices.UnregisterChannel(_channel); _channel = null; } }
protected EyesarServer(EyesarSharedObject sharedObject) { if (ChannelServices.RegisteredChannels.Any(channel => channel.ChannelName == "Eyesar")) { throw new InvalidOperationException(); } _channel = new IpcServerChannel("Eyesar", "eyesar"); ChannelServices.RegisterChannel(_channel, false); RemotingServices.Marshal(SharedObject = sharedObject, "shared", typeof(EyesarSharedObject)); }
public static void Cleanup() { SafeDispose(ref SingleInstanceMutex); if (Channel != null) { ChannelServices.UnregisterChannel(Channel); Channel = null; } }
internal static void DisposeInteractiveHostProcess(InteractiveHost process) { IpcServerChannel serverChannel = process._ServerChannel; process.Dispose(); var listenerThread = (Thread)s_ipcServerChannelListenerThread.GetValue(serverChannel); listenerThread.Join(); }
public static void RegisterIpcChannel(EventHandler <NewInstanceDetectedEventArgs> handler) { IChannel ipcChannel = new IpcServerChannel(String.Format(CultureInfo.InvariantCulture, "hfm-{0}-{1}", Environment.UserName, _AssemblyGuid)); ChannelServices.RegisterChannel(ipcChannel, false); var obj = new IpcObject(handler); RemotingServices.Marshal(obj, ObjectName); }
public static IpcServerChannel RegisterServerChannel(string baseServerName) { var provider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full }; var channel = new IpcServerChannel(null, baseServerName + "-" + Process.GetCurrentProcess().Id, provider); ChannelServices.RegisterChannel(channel, false); return(channel); }
static void Main(string[] args) { IpcServerChannel channel = new IpcServerChannel("ServerChannel"); ChannelServices.RegisterChannel(channel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(BaseData), "RemoteData", WellKnownObjectMode.SingleCall); Console.WriteLine("press return to exit"); Console.ReadLine(); }
/// <summary> /// Cleans up single-instance code, clearing shared resources, mutexes, etc. /// </summary> public static void Cleanup() { singleInstanceMutex?.ReleaseMutex(); if (channel != null) { ChannelServices.UnregisterChannel(channel); channel = null; } }
/// <summary> /// Creates semaphore to start remoting. /// </summary> /// <returns>True if no other instance there and this instance instantiated remoting server</returns> public bool Create(string title) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentNullException(nameof(title)); } // Determine Semaphore name and IPC port name using assembly title. var semaphoreName = $"semaphore-{title}"; var ipcPortName = $"port-{title}"; const string ipcUri = "space"; _semaphore = new Semaphore(1, 1, semaphoreName, out bool createdNew); if (createdNew) { try { // Instantiate a server channel and register it. _server = new IpcServerChannel(ipcPortName); ChannelServices.RegisterChannel(_server, true); // Instantiate a remoting object and publish it. _space = new RemotingSpace(); RemotingServices.Marshal(_space, ipcUri, typeof(RemotingSpace)); } catch (RemotingException ex) { Debug.WriteLine("Failed to start remoting." + Environment.NewLine + ex); } return(true); } else { try { // Instantiate a client channel and register it. var client = new IpcClientChannel(); ChannelServices.RegisterChannel(client, true); // Set a proxy for remote object. var ipcPath = $"ipc://{ipcPortName}/{ipcUri}"; _space = Activator.GetObject(typeof(RemotingSpace), ipcPath) as RemotingSpace; // Raise event. _space?.RaiseShowRequested(); } catch (RemotingException ex) { Debug.WriteLine("Failed to start remoting." + Environment.NewLine + ex); } return(false); } }
public static IChannel PublishLocalProxy(ExecutionServiceProxy proxy) { //We want the object to be available for as long as possible so we choose one year LifetimeServices.LeaseTime = TimeSpan.FromDays(365); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = TypeFilterLevel.Full; //need full deserialization //create a server channel and make the object available remotely Hashtable channelSettings = new Hashtable(); channelSettings["portName"] = ExecutionService.LocalPortName; //Grant access to everyone (need to get the name from the well known SID to support localized builds) SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); NTAccount everyoneAccount = (NTAccount)everyoneSid.Translate(typeof(NTAccount)); channelSettings["authorizedGroup"] = everyoneAccount.Value; //Because use use ExecutionService to update itself we have to disallow exclusive access //to the port, otherwise updating ExecutionService fails. channelSettings["exclusiveAddressUse"] = false; // Workaround for Remoting breaking change. This custom security descriptor is needed // to allow Medium IL processes to use IPC to talk to elevated UAC processes. DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1); // This is the well-known sid for network security ID string networkSidSddlForm = @"S-1-5-2"; // This is the well-known sid for all users on this machine string everyoneSidSddlForm = @"S-1-1-0"; // Deny all access to NetworkSid dacl.AddAccess(AccessControlType.Deny, new SecurityIdentifier(networkSidSddlForm), -1, InheritanceFlags.None, PropagationFlags.None); // Add access to the current user creating the pipe dacl.AddAccess(AccessControlType.Allow, WindowsIdentity.GetCurrent().User, -1, InheritanceFlags.None, PropagationFlags.None); // Add access to the all users on the machine dacl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(everyoneSidSddlForm), -1, InheritanceFlags.None, PropagationFlags.None); // Initialize and return the CommonSecurityDescriptor CommonSecurityDescriptor allowMediumILSecurityDescriptor = new CommonSecurityDescriptor(false, false, ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent, null, null, null, dacl); IpcServerChannel publishedChannel = new IpcServerChannel(channelSettings, provider, allowMediumILSecurityDescriptor); ChannelServices.RegisterChannel(publishedChannel, false); RemotingServices.Marshal(proxy, ExecutionService.ProxyName, typeof(IExecutionService)); return(publishedChannel); }
public static IpcServerChannel CreateIpcServer <IService, TService>( TService service, string channelName = null, string portName = null, WellKnownSidType aclSid = WellKnownSidType.WorldSid) where IService : class where TService : MarshalByRefObject, IService { if (channelName == null) { channelName = GenerateIpcServerChannelName(); } System.Collections.IDictionary properties = new System.Collections.Hashtable { { "name", channelName }, { "portName", portName ?? channelName } }; // Setup ACL : allow access from all users. Channel is protected by a random name. DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1); dacl.AddAccess( AccessControlType.Allow, new SecurityIdentifier( aclSid, null), -1, InheritanceFlags.None, PropagationFlags.None); CommonSecurityDescriptor secDescr = new CommonSecurityDescriptor(false, false, ControlFlags.GroupDefaulted | ControlFlags.OwnerDefaulted | ControlFlags.DiscretionaryAclPresent, null, null, null, dacl); // Formatter sink // TODO: Custom sink BinaryServerFormatterSinkProvider binaryProv = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full }; // Create server var ipcServer = new IpcServerChannel(properties, binaryProv, secDescr); ChannelServices.RegisterChannel(ipcServer, false); // Initialize with SMA interface RemotingServices.Marshal(service, channelName, typeof(IService)); return(ipcServer); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main() { RemotingConfiguration.Configure("Server.exe.config", false /*ensureSecurity*/); IDictionary props = new Hashtable(); props["portName"] = "test"; // This is the wellknown sid for network sid string networkSidSddlForm = @"S-1-5-2"; // Local administrators sid SecurityIdentifier localAdminSid = new SecurityIdentifier( WellKnownSidType.BuiltinAdministratorsSid, null); // Local Power users sid SecurityIdentifier powerUsersSid = new SecurityIdentifier( WellKnownSidType.BuiltinPowerUsersSid, null); // Network sid SecurityIdentifier networkSid = new SecurityIdentifier(networkSidSddlForm); DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1); // Disallow access from off machine dacl.AddAccess(AccessControlType.Deny, networkSid, -1, InheritanceFlags.None, PropagationFlags.None); // Allow acces only from local administrators and power users dacl.AddAccess(AccessControlType.Allow, localAdminSid, -1, InheritanceFlags.None, PropagationFlags.None); dacl.AddAccess(AccessControlType.Allow, powerUsersSid, -1, InheritanceFlags.None, PropagationFlags.None); CommonSecurityDescriptor securityDescriptor = new CommonSecurityDescriptor(false, false, ControlFlags.GroupDefaulted | ControlFlags.OwnerDefaulted | ControlFlags.DiscretionaryAclPresent, null, null, null, dacl); IpcServerChannel channel = new IpcServerChannel( props, null, securityDescriptor); ChannelServices.RegisterChannel(channel, false /*ensureSecurity*/); foreach (IChannel chan in ChannelServices.RegisteredChannels) { Console.WriteLine(chan.ChannelName); } Console.WriteLine("Waiting for connections..."); Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
/// <summary> /// Инициализации библиотеки внедрения /// </summary> public void InitSlim() { ChannelName = null; // Initialise the IPC server ScreenshotServer = RemoteHooking.IpcCreateServer <ScreenshotInterface.ScreenshotInterface>( ref ChannelName, WellKnownObjectMode.Singleton ); Thread.Sleep(250); if (!inited) { inited = true; // NOTE: On some 64-bit setups this doesn't work so well. // Sometimes if using a 32-bit target, it will not find the GAC assembly // without a machine restart, so requires manual insertion into the GAC // Alternatively if the required assemblies are in the target applications // search path they will load correctly. // Must be running as Administrator to allow dynamic registration in GAC Config.Register("ScreenshotInjector", "ScreenshotInject.dll"); } Thread.Sleep(250); UInt32 processId; UInt32 tid = GetWindowThreadProcessId((int)window.HWnd, out processId); this.pid = (int)processId; // Keep track of hooked processes in case more than one need to be hooked HookManager.AddHookedProcess(this.pid); // Inject DLL into target process RemoteHooking.Inject( this.pid, InjectionOptions.Default, // 32-bit version (the same because AnyCPU) could use different assembly that links to 32-bit C++ helper dll "ScreenshotInject.dll", // 64-bit version (the same because AnyCPU) could use different assembly that links to 64-bit C++ helper dll "ScreenshotInject.dll", // the optional parameter list... ChannelName, // The name of the IPC channel for the injected assembly to connect to Direct3D.CurrentVersion // The direct3DVersion used in the target application ); // Ensure the target process is in the foreground, // this prevents an issue where the target app appears to be in // the foreground but does not receive any user inputs. // Note: the first Alt+Tab out of the target application after injection // may still be an issue - switching between windowed and // fullscreen fixes the issue however (see ScreenshotInjection.cs for another option) NativeMethods.SetForegroundWindow(window.HWnd); }
protected void StartIpcServer() { LogTo.Debug("Starting Plugin IPC Server"); // Generate random channel name IpcServerChannelName = RemotingServicesEx.GenerateIpcServerChannelName(); IpcServer = RemotingServicesEx.CreateIpcServer <IPluginManager <ICore>, TParent>( (TParent)this, IpcServerChannelName); }
private static void RegisterRemoting() { Hashtable hashtable = new Hashtable(); hashtable["name"] = "ipc"; hashtable["priority"] = "20"; hashtable["portName"] = MyConst.ChannelPortName; CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(false, false, string.Empty); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); commonSecurityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, sid, -1, InheritanceFlags.None, PropagationFlags.None); IpcServerChannel chnl = new IpcServerChannel(hashtable, null, commonSecurityDescriptor); ChannelServices.RegisterChannel(chnl, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProfilerService), MyConst.ObjectURI, WellKnownObjectMode.Singleton); }
public IpcServer() { // Create the server channel. IpcServerChannel channel = new IpcServerChannel("ipcSample"); // Register the server channel. ChannelServices.RegisterChannel(channel, true); // Create an instance of the remote object. RemoteObject = new IpcRemoteObject(); RemoteObject.URL = "URL"; RemotingServices.Marshal(RemoteObject, "test", typeof(IpcRemoteObject)); }