示例#1
0
        public void SendMessage(string message, MessageType messageType)
        {
            if (_isFinalized)
            {
                return;
            }

            var messageData = Encoding.UTF8.GetBytes(message);
            var data        = new byte[messageData.Length + 2];

            data[0] = (byte)ClientCommandsCommunication.ResponseCommandMessage;
            data[1] = (byte)messageType;
            Array.Copy(messageData, 0, data, 2, messageData.Length);
            _connectionInfo.CommandResponse(_command, data);
        }
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            var connections = new List <ActiveConnection>();

            try
            {
                connections.AddRange(Connections.GetTcpConnections());
            }
            catch (Exception)
            {
                // ignored
            }

            try
            {
                connections.AddRange(Connections.GetUdpConnections());
            }
            catch (Exception)
            {
                // ignored
            }

            var serializer = new Serializer(typeof(List <ActiveConnection>));

            connectionInfo.CommandResponse(this, serializer.Serialize(connections));
        }
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            Initialize();

            switch ((WindowsCustomizerCommunication)parameter[0])
            {
            case WindowsCustomizerCommunication.GetCurrentSettings:
                ResponseBytes((byte)WindowsCustomizerCommunication.ResponseCurrentSettings,
                              new Serializer(typeof(CurrentSettings)).Serialize(GetCurrentSettings()), connectionInfo);
                break;

            case WindowsCustomizerCommunication.ChangeBooleanValue:
                var booleanValue = parameter[1] == 1;
                var propertyName = Encoding.UTF8.GetString(parameter, 2, parameter.Length - 2);

                var propertyInfo = _windowsPropertyInfos[propertyName];

                try
                {
                    propertyInfo.Value = booleanValue;
                }
                catch (Exception ex)
                {
                    if (!(ex is UnauthorizedAccessException) && !(ex.InnerException is UnauthorizedAccessException))
                    {
                        throw;
                    }

                    var exceptionData = new byte[parameter.Length];
                    exceptionData[0] = (byte)WindowsCustomizerCommunication.UnauthorizedAccessException;
                    Array.Copy(parameter, 1, exceptionData, 1, parameter.Length - 1);
                    connectionInfo.CommandResponse(this, exceptionData);
                    return;
                }

                var data = new byte[parameter.Length];
                data[0] = (byte)WindowsCustomizerCommunication.BooleanValueChanged;
                Array.Copy(parameter, 1, data, 1, parameter.Length - 1);
                connectionInfo.CommandResponse(this, data);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        private void SendError(string message, IConnectionInfo connectionInfo)
        {
            var package = new List <byte> {
                (byte)RegistryCommunication.Error
            };

            package.AddRange(Encoding.UTF8.GetBytes(message));
            connectionInfo.CommandResponse(this, package.ToArray());
        }
        private void SendDriverFile(WindowsDriversFile windowsDriversFile, IConnectionInfo connectionInfo)
        {
            var content     = ReadDriversFile(windowsDriversFile);
            var contentData = Encoding.UTF8.GetBytes(content);

            var response = new byte[contentData.Length + 2];

            response[0] = (byte)WindowsDriversCommunication.ResponseDriversFileContent;
            response[1] = (byte)windowsDriversFile;
            Buffer.BlockCopy(contentData, 0, response, 2, contentData.Length);

            connectionInfo.CommandResponse(this, response);
        }
        private void CmdProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data == null)
            {
                return;
            }

            var package = new List <byte> {
                (byte)ConsoleCommunication.ResponseNewLine
            };

            package.AddRange(Encoding.UTF8.GetBytes(e.Data));
            _currentConnectionInfo.CommandResponse(this, package.ToArray());
        }
示例#7
0
        private void ReverseProxyClientOnDataReceived(object sender, ReverseProxyDataReceivedEventArgs reverseProxyDataReceivedEventArgs)
        {
            if (_isDisposed)
            {
                return;
            }

            var packet = new byte[1 + 4 + reverseProxyDataReceivedEventArgs.Data.Length];

            packet[0] = (byte)ReverseProxyCommunication.ResponseData;
            Buffer.BlockCopy(BitConverter.GetBytes(reverseProxyDataReceivedEventArgs.ConnectionId), 0, packet, 1, 4);
            Buffer.BlockCopy(reverseProxyDataReceivedEventArgs.Data, 0, packet, 5,
                             reverseProxyDataReceivedEventArgs.Data.Length);

            _connection.CommandResponse(this, packet);
        }
示例#8
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            System.Diagnostics.EventLog eventLog;
            int startPosition;

            switch ((EventLogCommunication)parameter[0])
            {
            case EventLogCommunication.RequestEventLog:
                switch ((EventLogType)parameter[1])
                {
                case EventLogType.System:
                    eventLog = new System.Diagnostics.EventLog("System");
                    break;

                case EventLogType.Application:
                    eventLog = new System.Diagnostics.EventLog("Application");
                    break;

                case EventLogType.Security:
                    eventLog = new System.Diagnostics.EventLog("Security");
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                startPosition = BitConverter.ToInt32(parameter, 2);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            List <EventLogEntry> entries = null;

            try
            {
#pragma warning disable 618
                var lastItem  = eventLog.Entries.Count - startPosition; //not -1 because the for condition is greater than
                var firstItem = eventLog.Entries.Count - startPosition - 301;
                if (firstItem < 0)
                {
                    firstItem = 0;
                }

                entries = new List <EventLogEntry>();
                for (int i = firstItem; i < lastItem; i++)
                {
                    var entry = eventLog.Entries[i];
                    entries.Add(new EventLogEntry
                    {
                        EntryType = (EventLogEntryType)entry.EntryType,
                        EventId   = entry.EventID,
                        Source    = entry.Source,
                        Timestamp = entry.TimeGenerated,
                        Message   = entry.Message
                    });
                }
#pragma warning restore 618
            }
            catch (SecurityException)
            {
                if (ServiceConnection.Current.IsConnected)
                {
                    entries = ServiceConnection.Current.Pipe.GetSecurityEventLog(300);
                }

                if (entries == null)
                {
                    ResponseByte((byte)EventLogCommunication.ResponseNoAdministratorRights, connectionInfo);
                    return;
                }
            }

            var serializer  = new Serializer(typeof(List <EventLogEntry>));
            var entriesData = serializer.Serialize(entries.OrderByDescending(x => x.Timestamp).ToList());
            var data        = new byte[entriesData.Length + 5];
            data[0] = (byte)EventLogCommunication.ResponseEventLogEntries;
            Array.Copy(BitConverter.GetBytes(startPosition), 0, data, 1, 4);
            Array.Copy(entriesData, 0, data, 5, entriesData.Length);

            connectionInfo.CommandResponse(this, data);
        }
示例#9
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((CodeCommunication)parameter[0])
            {
            case CodeCommunication.SendCsharpCode:
            case CodeCommunication.SendVbCode:
                var source          = Encoding.UTF8.GetString(parameter, 1, parameter.Length - 1);
                var providerOptions = new Dictionary <string, string>
                {
                    { "CompilerVersion", "v3.5" }
                };

                var provider = (CodeCommunication)parameter[0] == CodeCommunication.SendCsharpCode
                        ? (CodeDomProvider) new CSharpCodeProvider(providerOptions)
                        : new VBCodeProvider(providerOptions);

                var compilerParams = new CompilerParameters
                {
                    GenerateInMemory   = true,
                    GenerateExecutable = false
                };
                compilerParams.ReferencedAssemblies.Add("System.dll");
                compilerParams.ReferencedAssemblies.Add("System.Core.dll");
                compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                compilerParams.ReferencedAssemblies.Add("System.Xml.dll");
                compilerParams.ReferencedAssemblies.Add("System.Xml.Linq.dll");

                var results = provider.CompileAssemblyFromSource(compilerParams, source);

                if (results.Errors.HasErrors)
                {
                    var package = new List <byte> {
                        (byte)CodeCommunication.ResponseErrors
                    };
                    package.AddRange(
                        BitConverter.GetBytes(results.Errors.OfType <CompilerError>().Count(x => !x.IsWarning)));
                    var error = results.Errors.OfType <CompilerError>().First(x => !x.IsWarning);
                    package.AddRange(BitConverter.GetBytes(error.Line));
                    package.AddRange(Encoding.UTF8.GetBytes(error.ErrorText));
                    connectionInfo.CommandResponse(this, package.ToArray());
                    return;
                }

                try
                {
                    object o      = results.CompiledAssembly.CreateInstance("Orcus.CodeExecution");
                    var    method = o?.GetType().GetMethod("Main");
                    method.Invoke(o, null);
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)CodeCommunication.ResponseInvokeSuccessful });
                }
                catch (Exception ex)
                {
                    var package = new List <byte> {
                        (byte)CodeCommunication.ResponseGenerationException
                    };
                    package.AddRange(Encoding.UTF8.GetBytes(ex.Message));
                    connectionInfo.CommandResponse(this, package.ToArray());
                }
                break;

            case CodeCommunication.SendBatchCode:
                var freeFileName   = FileExtensions.GetFreeTempFileName("bat");
                var createNoWindow = parameter[1] == 1;
                var process        = new Process
                {
                    StartInfo = { UseShellExecute = false, FileName = freeFileName, CreateNoWindow = createNoWindow }
                };
                File.WriteAllText(freeFileName, Encoding.UTF8.GetString(parameter, 2, parameter.Length - 2));
                process.Start();
                connectionInfo.CommandResponse(this,
                                               new[] { (byte)CodeCommunication.ResponseBatchCodeExecuted });
                process.WaitForExit();
                try
                {
                    File.Delete(freeFileName);
                }
                catch (Exception)
                {
                    // ignored
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#10
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            try
            {
                string       path;
                RegistryHive root;
                Serializer   serializer;

                switch ((RegistryCommunication)parameter[0])
                {
                case RegistryCommunication.GetRegistrySubKeys:
                    root = (RegistryHive)BitConverter.ToInt32(parameter, 1);

                    path = Encoding.UTF8.GetString(parameter, 5, parameter.Length - 5);
                    List <RegistrySubKey> subKeys;

                    try
                    {
                        using (
                            var regKey = RegistryExtensions.OpenRegistry(root)
                                         .OpenSubKey(path, RegistryKeyPermissionCheck.ReadSubTree))
                        {
                            subKeys = new List <RegistrySubKey>();
                            foreach (var subKeyName in regKey.GetSubKeyNames())
                            {
                                bool isEmpty = false;
                                try
                                {
                                    using (var subKey = regKey.OpenSubKey(subKeyName, false))
                                    {
                                        isEmpty = subKey.GetSubKeyNames().Length == 0;
                                    }
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }

                                subKeys.Add(new RegistrySubKey
                                {
                                    Name    = subKeyName,
                                    IsEmpty = isEmpty
                                });
                            }
                        }
                    }
                    catch (Exception)
                    {
                        if (!ServiceConnection.Current.IsConnected || root == RegistryHive.CurrentUser)
                        {
                            throw;
                        }
                        subKeys = ServiceConnection.Current.Pipe.GetRegistrySubKeys(path, root);
                        if (subKeys == null)
                        {
                            throw;
                        }
                    }

                    serializer = new Serializer(typeof(RegistrySubKeysPackage));
                    using (
                        var ms = new MemoryStream())
                    {
                        ms.WriteByte((byte)RegistryCommunication.ResponseRegistrySubKeys);
                        serializer.Serialize(ms,
                                             new RegistrySubKeysPackage
                        {
                            Path            = path,
                            RegistrySubKeys = subKeys,
                            RegistryHive    = root
                        });
                        connectionInfo.CommandResponse(this, ms.ToArray());
                    }

                    break;

                case RegistryCommunication.DeleteSubKey:
                    root = (RegistryHive)BitConverter.ToInt32(parameter, 1);
                    path = Encoding.UTF8.GetString(parameter, 5, parameter.Length - 5);

                    try
                    {
                        using (var regKey = RegistryExtensions.OpenRegistry(root))
                            regKey.DeleteSubKeyTree(path);
                    }
                    catch (Exception)
                    {
                        if (!ServiceConnection.Current.IsConnected || root == RegistryHive.CurrentUser)
                        {
                            throw;
                        }
                        if (!ServiceConnection.Current.Pipe.DeleteSubKey(path, root))
                        {
                            throw;
                        }
                    }

                    serializer = new Serializer(typeof(RegistrySubKeyAction));
                    ResponseBytes((byte)RegistryCommunication.ResponseSubKeyDeleted,
                                  serializer.Serialize(new RegistrySubKeyAction {
                        Path = path, RegistryHive = root
                    }),
                                  connectionInfo);
                    break;

                case RegistryCommunication.GetRegistryValues:
                    root = (RegistryHive)BitConverter.ToInt32(parameter, 1);
                    path = Encoding.UTF8.GetString(parameter, 5, parameter.Length - 5);
                    List <RegistryValue> valueList;

                    try
                    {
                        using (
                            var regKey = RegistryExtensions.OpenRegistry(root).OpenSubKey(path, false)
                            )
                        {
                            valueList = new List <RegistryValue>();
                            foreach (var valueName in regKey.GetValueNames())
                            {
                                var kind = regKey.GetValueKind(valueName);
                                switch (kind)
                                {
                                case RegistryValueKind.String:
                                    valueList.Add(new RegistryValueString
                                    {
                                        Key   = valueName,
                                        Value = (string)regKey.GetValue(valueName, string.Empty)
                                    });
                                    break;

                                case RegistryValueKind.ExpandString:
                                    valueList.Add(new RegistryValueExpandString
                                    {
                                        Key   = valueName,
                                        Value = (string)regKey.GetValue(valueName, string.Empty)
                                    });
                                    break;

                                case RegistryValueKind.Binary:
                                    valueList.Add(new RegistryValueBinary
                                    {
                                        Key   = valueName,
                                        Value = (byte[])regKey.GetValue(valueName, new byte[] {})
                                    });
                                    break;

                                case RegistryValueKind.DWord:
                                    valueList.Add(new RegistryValueDWord
                                    {
                                        Key   = valueName,
                                        Value = (uint)(int)regKey.GetValue(valueName, 0)
                                    });
                                    break;

                                case RegistryValueKind.MultiString:
                                    valueList.Add(new RegistryValueMultiString
                                    {
                                        Key   = valueName,
                                        Value = (string[])regKey.GetValue(valueName, new string[] {})
                                    });
                                    break;

                                case RegistryValueKind.QWord:
                                    valueList.Add(new RegistryValueQWord
                                    {
                                        Key   = valueName,
                                        Value = (ulong)(long)regKey.GetValue(valueName, 0)
                                    });
                                    break;

                                default:
                                    valueList.Add(new RegistryValueUnknown
                                    {
                                        Key = valueName
                                    });
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        if (!ServiceConnection.Current.IsConnected || root == RegistryHive.CurrentUser)
                        {
                            throw;
                        }
                        valueList = ServiceConnection.Current.Pipe.GetRegistryValues(path, root);
                        if (valueList == null)
                        {
                            throw;
                        }
                    }

                    serializer = new Serializer(new List <Type>(RegistryValue.RegistryValueTypes)
                    {
                        typeof(RegistryValuesPackage)
                    });

                    ResponseBytes((byte)RegistryCommunication.ResponseRegistryValues,
                                  serializer.Serialize(new RegistryValuesPackage
                    {
                        Path         = path,
                        RegistryHive = root,
                        Values       = valueList
                    }), connectionInfo);

                    break;

                case RegistryCommunication.CreateSubKey:
                    root = (RegistryHive)BitConverter.ToInt32(parameter, 1);
                    path = Encoding.UTF8.GetString(parameter, 5, parameter.Length - 5);

                    try
                    {
                        RegistryExtensions.OpenRegistry(root)
                        .CreateSubKey(path, RegistryKeyPermissionCheck.Default);
                    }
                    catch (Exception)
                    {
                        if (!ServiceConnection.Current.IsConnected || root == RegistryHive.CurrentUser)
                        {
                            throw;
                        }
                        if (!ServiceConnection.Current.Pipe.CreateSubKey(path, root))
                        {
                            throw;
                        }
                    }

                    serializer = new Serializer(typeof(RegistrySubKeyAction));
                    ResponseBytes((byte)RegistryCommunication.ResponseSubKeyCreated,
                                  serializer.Serialize(new RegistrySubKeyAction {
                        Path = path, RegistryHive = root
                    }),
                                  connectionInfo);
                    break;

                case RegistryCommunication.CreateValue:
                    serializer = new Serializer(new List <Type>(RegistryValue.RegistryValueTypes)
                    {
                        typeof(RegistryCreateValuePackage)
                    });
                    var package = serializer.Deserialize <RegistryCreateValuePackage>(parameter, 1);

                    try
                    {
                        using (var rootKey = RegistryExtensions.OpenRegistry(package.RegistryHive))
                            using (var subKey = rootKey.OpenSubKey(package.Path, true))
                                subKey.SetValue(package.RegistryValue.Key, package.RegistryValue.ValueObject,
                                                ConvertFromOrcusValueKind(package.RegistryValue.ValueKind));
                    }
                    catch (Exception)
                    {
                        if (!ServiceConnection.Current.IsConnected ||
                            package.RegistryHive == RegistryHive.CurrentUser)
                        {
                            throw;
                        }
                        if (
                            !ServiceConnection.Current.Pipe.CreateValue(package.Path, package.RegistryHive,
                                                                        package.RegistryValue))
                        {
                            throw;
                        }
                    }

                    ResponseByte((byte)RegistryCommunication.ResponseValueCreated, connectionInfo);
                    break;

                case RegistryCommunication.DeleteValue:
                    root = (RegistryHive)BitConverter.ToInt32(parameter, 1);
                    var pathLength = BitConverter.ToInt32(parameter, 5);
                    path = Encoding.UTF8.GetString(parameter, 9, pathLength);
                    var name = Encoding.UTF8.GetString(parameter, 9 + path.Length,
                                                       parameter.Length - (9 + path.Length));

                    try
                    {
                        using (var rootKey = RegistryExtensions.OpenRegistry(root))
                            using (var subKey = rootKey.OpenSubKey(path, true))
                                subKey.DeleteValue(name, true);
                    }
                    catch (Exception)
                    {
                        if (!ServiceConnection.Current.IsConnected || root == RegistryHive.CurrentUser)
                        {
                            throw;
                        }
                        if (!ServiceConnection.Current.Pipe.DeleteValue(path, root, name))
                        {
                            throw;
                        }
                    }

                    ResponseByte((byte)RegistryCommunication.ResponseValueDeleted, connectionInfo);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception ex)
            {
                if (ex is SecurityException || ex is UnauthorizedAccessException)
                {
                    SendPermissionDenied(ex.Message, connectionInfo);
                }
                else
                {
                    SendError(ex.Message, connectionInfo);
                }
            }
        }
示例#11
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            Serializer serializer;
            IntPtr     handle;

            switch ((TaskManagerCommunication)parameter[0])
            {
            case TaskManagerCommunication.SendKill:
                var     id = BitConverter.ToInt32(parameter, 1);
                Process processToKill;
                try
                {
                    processToKill = Process.GetProcessById(id);
                }
                catch (ArgumentException)
                {
                    var errorPackage = new List <byte> {
                        (byte)TaskManagerCommunication.ResponseTaskKillFailed
                    };
                    errorPackage.AddRange(Encoding.UTF8.GetBytes("The process does not exist"));
                    connectionInfo.CommandResponse(this, errorPackage.ToArray());
                    return;
                }

                try
                {
                    processToKill.Kill();
                }
                catch (Exception ex)
                {
                    var errorPackage = new List <byte> {
                        (byte)TaskManagerCommunication.ResponseTaskKillFailed
                    };
                    errorPackage.AddRange(Encoding.UTF8.GetBytes(ex.Message));
                    connectionInfo.CommandResponse(this, errorPackage.ToArray());
                    return;
                }

                connectionInfo.CommandResponse(this,
                                               new[] { (byte)TaskManagerCommunication.ResponseTaskKilled });
                break;

            case TaskManagerCommunication.SendGetFullList:
                serializer = new Serializer(typeof(List <ProcessInfo>));
                var result = new List <byte> {
                    (byte)TaskManagerCommunication.ResponseFullList
                };
                var processes = GetAllProcesses();
                result.AddRange(serializer.Serialize(GetAllProcesses()));
                connectionInfo.CommandResponse(this, result.ToArray());
                SendProcesses = processes.Select(x => x.Id).ToList();
                break;

            case TaskManagerCommunication.SendGetChanges:
                var allProcesses = Process.GetProcesses();
                var newProcesses = allProcesses.ToList();
                foreach (var process in allProcesses.Where(process => SendProcesses.Any(x => x == process.Id)))
                {
                    newProcesses.Remove(process);
                }

                var closedProcesses =
                    SendProcesses.Where(process => allProcesses.All(x => x.Id != process)).ToList();
                var changelog = new ProcessListChangelog
                {
                    ClosedProcesses = closedProcesses,
                    NewProcesses    = new List <ProcessInfo>()
                };

                using (var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process"))
                    using (var collection = searcher.Get())
                    {
                        foreach (var queryObj in collection.Cast <ManagementObject>())
                        {
                            var pid     = queryObj.TryGetProperty <uint>("ProcessId");
                            var process = newProcesses.FirstOrDefault(x => x.Id == pid);
                            if (process == null)
                            {
                                continue;
                            }

                            changelog.NewProcesses.Add(ManagementObjectToProcessInfo(queryObj, process));
                        }
                    }

                serializer = new Serializer(typeof(ProcessListChangelog));
                var changelogResult = new List <byte> {
                    (byte)TaskManagerCommunication.ResponseChanges
                };
                changelogResult.AddRange(serializer.Serialize(changelog));
                connectionInfo.CommandResponse(this, changelogResult.ToArray());
                SendProcesses = allProcesses.Select(x => x.Id).ToList();
                break;

            case TaskManagerCommunication.SetPriority:
                var     processId = BitConverter.ToInt32(parameter, 1);
                Process processToChange;
                try
                {
                    processToChange = Process.GetProcessById(processId);
                }
                catch (ArgumentException)
                {
                    var errorPackage = new List <byte> {
                        (byte)TaskManagerCommunication.ResponseSetPriorityFailed
                    };
                    errorPackage.AddRange(Encoding.UTF8.GetBytes("The process does not exist"));
                    connectionInfo.CommandResponse(this, errorPackage.ToArray());
                    return;
                }

                try
                {
                    processToChange.PriorityClass = (ProcessPriorityClass)BitConverter.ToInt32(parameter, 5);
                }
                catch (Exception ex)
                {
                    var errorPackage = new List <byte> {
                        (byte)TaskManagerCommunication.ResponseSetPriorityFailed
                    };
                    errorPackage.AddRange(Encoding.UTF8.GetBytes(ex.Message));
                    connectionInfo.CommandResponse(this, errorPackage.ToArray());
                    return;
                }

                connectionInfo.CommandResponse(this,
                                               new[] { (byte)TaskManagerCommunication.ResponsePrioritySet });
                break;

            case TaskManagerCommunication.KillProcessTree:
                processId = BitConverter.ToInt32(parameter, 1);
                KillProcessAndChildren(processId);
                ResponseByte((byte)TaskManagerCommunication.ResponseProcessTreeKilled, connectionInfo);
                break;

            case TaskManagerCommunication.SuspendProcess:
                var processToSuspend = Process.GetProcessById(BitConverter.ToInt32(parameter, 1));
                processToSuspend.Suspend();
                ResponseByte((byte)TaskManagerCommunication.ResponseProcessSuspended, connectionInfo);
                break;

            case TaskManagerCommunication.ResumeProcess:
                var processToResume = Process.GetProcessById(BitConverter.ToInt32(parameter, 1));
                processToResume.Resume();
                ResponseByte((byte)TaskManagerCommunication.ResponseProcessResumed, connectionInfo);
                break;

            case TaskManagerCommunication.WindowBringToFront:
                handle = (IntPtr)BitConverter.ToInt64(parameter, 1);
                if (NativeMethods.IsIconic(handle))
                {
                    NativeMethods.ShowWindow(handle, ShowWindowCommands.Restore);
                }
                var success = NativeMethods.SetForegroundWindow(handle);
                ResponseByte(
                    (byte)
                    (success
                                ? TaskManagerCommunication.ResponseWindowActionDone
                                : TaskManagerCommunication.ResponseWindowActionFailed), connectionInfo);
                break;

            case TaskManagerCommunication.WindowMaximize:
                handle  = (IntPtr)BitConverter.ToInt64(parameter, 1);
                success = NativeMethods.ShowWindow(handle, ShowWindowCommands.Maximize);
                ResponseByte(
                    (byte)
                    (success
                                ? TaskManagerCommunication.ResponseWindowActionDone
                                : TaskManagerCommunication.ResponseWindowActionFailed), connectionInfo);
                break;

            case TaskManagerCommunication.WindowMinimize:
                handle  = (IntPtr)BitConverter.ToInt64(parameter, 1);
                success = NativeMethods.ShowWindow(handle, ShowWindowCommands.Minimize);
                ResponseByte(
                    (byte)
                    (success
                                ? TaskManagerCommunication.ResponseWindowActionDone
                                : TaskManagerCommunication.ResponseWindowActionFailed), connectionInfo);
                break;

            case TaskManagerCommunication.WindowRestore:
                handle  = (IntPtr)BitConverter.ToInt64(parameter, 1);
                success = NativeMethods.ShowWindow(handle, ShowWindowCommands.Restore);
                ResponseByte(
                    (byte)
                    (success
                                ? TaskManagerCommunication.ResponseWindowActionDone
                                : TaskManagerCommunication.ResponseWindowActionFailed), connectionInfo);
                break;

            case TaskManagerCommunication.WindowClose:
                handle  = (IntPtr)BitConverter.ToInt64(parameter, 1);
                success = NativeMethods.SendMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero) == IntPtr.Zero;
                ResponseByte(
                    (byte)
                    (success
                                ? TaskManagerCommunication.ResponseWindowActionDone
                                : TaskManagerCommunication.ResponseWindowActionFailed), connectionInfo);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#12
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((UserInteractionCommunication)parameter[0])
            {
            case UserInteractionCommunication.TextToSpeech:
                var textToSpeechInfo =
                    new Serializer(typeof(TextToSpeechPackage)).Deserialize <TextToSpeechPackage>(parameter, 1);
                using (var speaker = new SpeechSynthesizer())
                {
                    speaker.Rate   = textToSpeechInfo.Speed;
                    speaker.Volume = textToSpeechInfo.Volume;
                    speaker.SelectVoice(textToSpeechInfo.VoiceName);
                    speaker.SetOutputToDefaultAudioDevice();
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)UserInteractionCommunication.SpeakingText });
                    speaker.Speak(textToSpeechInfo.Text);
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)UserInteractionCommunication.SpeakingFinished });
                }
                break;

            case UserInteractionCommunication.GetWelcomePackage:
                var package = new UserInteractionWelcomePackage();
                using (var speaker = new SpeechSynthesizer())
                    package.Voices =
                        speaker.GetInstalledVoices()
                        .Select(
                            x =>
                            new SpeechVoice
                    {
                        Culture     = x.VoiceInfo.Culture.TwoLetterISOLanguageName,
                        Name        = x.VoiceInfo.Name,
                        VoiceAge    = (SpeechAge)(int)x.VoiceInfo.Age,
                        VoiceGender = (SpeechGender)(int)x.VoiceInfo.Gender
                    })
                        .ToList();

                var data = new List <byte> {
                    (byte)UserInteractionCommunication.WelcomePackage
                };
                data.AddRange(new Serializer(typeof(UserInteractionWelcomePackage)).Serialize(package));
                connectionInfo.CommandResponse(this, data.ToArray());
                break;

            case UserInteractionCommunication.OpenInEditor:
                var textLength = BitConverter.ToInt32(parameter, 1);
                NotepadHelper.ShowMessage(Encoding.UTF8.GetString(parameter, 5, textLength),
                                          Encoding.UTF8.GetString(parameter, textLength + 5, parameter.Length - (5 + textLength)));
                connectionInfo.CommandResponse(this,
                                               new[] { (byte)UserInteractionCommunication.OpenedInEditorSuccessfully });
                break;

            case UserInteractionCommunication.NotifyIconMessage:
                var timeout     = BitConverter.ToInt32(parameter, 2);
                var titleLength = BitConverter.ToInt32(parameter, 6);
                var title       = Encoding.UTF8.GetString(parameter, 10, titleLength);
                var text        = Encoding.UTF8.GetString(parameter, 10 + titleLength,
                                                          parameter.Length - (10 + titleLength));

                using (var notifyIcon = new NotifyIcon {
                    Icon = SystemIcons.Application
                })
                {
                    notifyIcon.Visible = true;
                    notifyIcon.ShowBalloonTip(timeout, title, text, (ToolTipIcon)parameter[1]);
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)UserInteractionCommunication.NotifyIconMessageOpened });
                    Thread.Sleep(timeout);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#13
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((ConsoleCommunication)parameter[0])
            {
            case ConsoleCommunication.SendStart:
            case ConsoleCommunication.OpenConsoleInPath:
                Dispose();

                int lcid     = NativeMethods.GetSystemDefaultLCID();
                var ci       = System.Globalization.CultureInfo.GetCultureInfo(lcid);
                var encoding = Encoding.GetEncoding(ci.TextInfo.OEMCodePage);

                _cmdProcess = new Process
                {
                    StartInfo =
                    {
                        CreateNoWindow = true,
                        FileName       = "cmd.exe",
                        //Arguments = "/K chcp 65001",
                        RedirectStandardOutput = true,
                        RedirectStandardInput  = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                        StandardErrorEncoding  = encoding,
                        StandardOutputEncoding = encoding
                    }
                };

                if ((ConsoleCommunication)parameter[0] == ConsoleCommunication.OpenConsoleInPath)
                {
                    _cmdProcess.StartInfo.WorkingDirectory = Encoding.UTF8.GetString(parameter, 1,
                                                                                     parameter.Length - 1);
                }

                _currentConnectionInfo = connectionInfo;

                _cmdProcess.OutputDataReceived += CmdProcess_OutputDataReceived;
                _cmdProcess.ErrorDataReceived  += CmdProcess_OutputDataReceived;
                _cmdProcess.Start();

                _standardInput = new StreamWriter(_cmdProcess.StandardInput.BaseStream, encoding)
                {
                    AutoFlush = true
                };

                connectionInfo.CommandResponse(this, new[] { (byte)ConsoleCommunication.ResponseConsoleOpen });
                _cmdProcess.BeginOutputReadLine();
                _cmdProcess.BeginErrorReadLine();
                break;

            case ConsoleCommunication.SendStop:
                Dispose();
                _currentConnectionInfo.CommandResponse(this,
                                                       new[] { (byte)ConsoleCommunication.ResponseConsoleClosed });
                break;

            case ConsoleCommunication.SendCommand:
                if (_cmdProcess == null || _cmdProcess.HasExited)
                {
                    return;
                }

                _standardInput.WriteLine(Encoding.UTF8.GetString(parameter, 1, parameter.Length - 1));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#14
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            byte[] data;
            switch ((StartupManagerCommunication)parameter[0])
            {
            case StartupManagerCommunication.GetAutostartEntries:
                ResponseBytes((byte)StartupManagerCommunication.ResponseAutostartEntries,
                              new Serializer(typeof(List <AutostartProgramInfo>)).Serialize(
                                  AutostartManager.GetAllAutostartPrograms()),
                              connectionInfo);
                break;

            case StartupManagerCommunication.EnableAutostartEntry:
                try
                {
                    AutostartManager.ChangeAutostartEntry((AutostartLocation)parameter[1],
                                                          Encoding.UTF8.GetString(parameter, 2, parameter.Length - 2), true);
                }
                catch (Exception ex)
                {
                    if (!(ex is SecurityException) && !(ex is UnauthorizedAccessException))
                    {
                        throw;
                    }
                    data    = new byte[parameter.Length];
                    data[0] = (byte)StartupManagerCommunication.ResponseAutostartChangingFailed;
                    Array.Copy(parameter, 1, data, 1, parameter.Length - 1);
                    connectionInfo.CommandResponse(this, data);
                    return;
                }
                data    = new byte[parameter.Length];
                data[0] = (byte)StartupManagerCommunication.ResponseAutostartEntryEnabled;
                Array.Copy(parameter, 1, data, 1, parameter.Length - 1);
                connectionInfo.CommandResponse(this, data);
                break;

            case StartupManagerCommunication.DisableAutostartEntry:
                try
                {
                    AutostartManager.ChangeAutostartEntry((AutostartLocation)parameter[1],
                                                          Encoding.UTF8.GetString(parameter, 2, parameter.Length - 2), false);
                }
                catch (Exception ex)
                {
                    if (!(ex is SecurityException) && !(ex is UnauthorizedAccessException))
                    {
                        throw;
                    }

                    data    = new byte[parameter.Length];
                    data[0] = (byte)StartupManagerCommunication.ResponseAutostartChangingFailed;
                    Array.Copy(parameter, 1, data, 1, parameter.Length - 1);
                    connectionInfo.CommandResponse(this, data);
                    return;
                }
                data    = new byte[parameter.Length];
                data[0] = (byte)StartupManagerCommunication.ResponseAutostartEntryDisabled;
                Array.Copy(parameter, 1, data, 1, parameter.Length - 1);
                connectionInfo.CommandResponse(this, data);
                break;

            case StartupManagerCommunication.RemoveAutostartEntry:
                AutostartManager.RemoveAutostartEntry((AutostartLocation)parameter[2],
                                                      Encoding.UTF8.GetString(parameter, 3, parameter.Length - 3), parameter[1] == 1);
                data    = new byte[parameter.Length];
                data[0] = (byte)StartupManagerCommunication.ResponseAutostartEntryRemoved;
                Array.Copy(parameter, 1, data, 1, parameter.Length - 1);
                connectionInfo.CommandResponse(this, data);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#15
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((AudioCommunication)parameter[0])
            {
            case AudioCommunication.PlayAudio:
                if (CoreHelper.RunningOnXP)
                {
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)AudioCommunication.ResponseNotSupported });
                    return;
                }

                var serializer      = new Serializer(typeof(PlayAudioInformation));
                var playInformation = serializer.Deserialize <PlayAudioInformation>(parameter, 1);

                ISoundOut soundOut;

                if (WasapiOut.IsSupportedOnCurrentPlatform)
                {
                    using (var deviceEnumerator = new MMDeviceEnumerator())
                    {
                        var device =
                            deviceEnumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active)
                            .FirstOrDefault(x => x.DeviceID == playInformation.SoundOutId);
                        if (device == null)
                        {
                            return;
                        }

                        soundOut = new WasapiOut {
                            Device = device
                        };
                    }
                }
                else
                {
                    var devices = DirectSoundDeviceEnumerator.EnumerateDevices();
                    var guid    = new Guid(playInformation.SoundOutId);
                    var device  = devices.FirstOrDefault(x => x.Guid == guid);
                    if (device == null)
                    {
                        return;
                    }

                    soundOut = new DirectSoundOut {
                        Device = guid
                    };
                }

                var memoryStream =
                    new MemoryStream(playInformation.AudioData);
                IWaveSource waveSource = new DmoMp3Decoder(memoryStream);
                soundOut.Initialize(waveSource);
                soundOut.Volume = playInformation.Volume;
                soundOut.Play();

                soundOut.Stopped += (sender, args) =>
                {
                    new Thread(() =>
                    {
                        soundOut.Dispose();
                        waveSource.Dispose();
                        memoryStream.Dispose();
                    }).Start();
                };

                connectionInfo.CommandResponse(this, new[] { (byte)AudioCommunication.ResponseAudioIsPlaying });
                break;

            case AudioCommunication.GetDevices:
                List <SoundOutDevice> result;
                if (WasapiOut.IsSupportedOnCurrentPlatform)
                {
                    using (var deviceEnumerator = new MMDeviceEnumerator())
                    {
                        var defaultDevice = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render,
                                                                                     Role.Multimedia);

                        result =
                            new List <SoundOutDevice>(
                                deviceEnumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active)
                                .Select(enumAudioEndpoint => new SoundOutDevice
                        {
                            Id        = enumAudioEndpoint.DeviceID,
                            IsDefault = enumAudioEndpoint.DeviceID == defaultDevice.DeviceID,
                            Name      = enumAudioEndpoint.FriendlyName
                        }));
                    }
                }
                else
                {
                    var devices = DirectSoundDeviceEnumerator.EnumerateDevices();
                    result =
                        devices.Select(
                            x =>
                            new SoundOutDevice
                    {
                        Id        = x.Guid.ToString("N"),
                        Name      = x.Description,
                        IsDefault = false
                    }).ToList();
                }

                var package = new List <byte> {
                    (byte)AudioCommunication.ResponseDevices
                };
                package.AddRange(Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(result)));
                connectionInfo.CommandResponse(this, package.ToArray());
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(parameter), parameter, null);
            }
        }
示例#16
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((TextChatCommunication)parameter[0])
            {
            case TextChatCommunication.SendMessage:
                _currentChatForm?.MessageReceived(new DateTime(BitConverter.ToInt64(parameter, 1)),
                                                  Encoding.UTF8.GetString(parameter, 9, parameter.Length - 9));
                break;

            case TextChatCommunication.OpenChat:
                var chatSettings = new Serializer(typeof(ChatSettings)).Deserialize <ChatSettings>(parameter, 1);
                if (chatSettings.HideEveythingElse)
                {
                    Computer.MinimizeAllScreens();
                }

                _currentChatForm              = new TextChatForm(chatSettings);
                _currentChatForm.SendMessage += (sender, args) =>
                {
                    var data = new List <byte> {
                        (byte)TextChatCommunication.ResponseMessage
                    };
                    data.AddRange(BitConverter.GetBytes(DateTime.UtcNow.Ticks));
                    data.AddRange(Encoding.UTF8.GetBytes(args.Message));
                    connectionInfo.CommandResponse(this, data.ToArray());
                };
                _currentChatForm.Closed += (sender, args) =>
                {
                    _currentChatForm = null;
                    try
                    {
                        connectionInfo.CommandResponse(this, new[] { (byte)TextChatCommunication.ChatClosed });
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                };
                connectionInfo.CommandResponse(this, new[] { (byte)TextChatCommunication.ChatOpened });
                _currentChatForm.ShowDialog();
                break;

            case TextChatCommunication.Close:
                if (_currentChatForm != null)
                {
                    if (!_currentChatForm.IsClosed)
                    {
                        try
                        {
                            _currentChatForm.Invoke((MethodInvoker)(() => _currentChatForm.ForceClose()));
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                    _currentChatForm = null;
                }

                //dont send the close message, the window will do that by itself (Closed-Event)
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#17
0
 /// <summary>
 ///     Response a byte array
 /// </summary>
 protected void ResponseBytes(byte[] b, IConnectionInfo connectionInfo)
 {
     connectionInfo.CommandResponse(this, b);
 }
示例#18
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((HvncCommunication)parameter[0])
            {
            case HvncCommunication.CreateDesktop:
                lock (_desktopLock)
                {
                    var information =
                        new Serializer(typeof(CreateDesktopInformation)).Deserialize <CreateDesktopInformation>(
                            parameter, 1);

                    _currentDesktop = new Desktop();
                    _currentDesktop.Create(information.CustomName ?? Settings.GetBuilderProperty <MutexBuilderProperty>().Mutex);

                    if (information.StartExplorer)
                    {
                        _currentDesktop.CreateProcess(Path.Combine(
#if NET35
                                                          EnvironmentExtensions.WindowsFolder,
#else
                                                          Environment.GetFolderPath(Environment.SpecialFolder.Windows),
#endif
                                                          "explorer.exe"), "");
                    }
                    _renderWindows = new List <RenderWindow>();
                }

                var response = new byte[9];
                response[0] = (byte)HvncCommunication.ResponseDesktopCreated;
                Array.Copy(BitConverter.GetBytes(SystemInformation.VirtualScreen.Width), 0, response, 1, 4);
                Array.Copy(BitConverter.GetBytes(SystemInformation.VirtualScreen.Height), 0, response, 5, 4);
                ResponseBytes(response, connectionInfo);
                break;

            case HvncCommunication.CloseDesktop:
                lock (_desktopLock)
                {
                    if (_currentDesktop?.IsOpen == true)
                    {
                        DisposeSession();
                    }
                }
                ResponseByte((byte)HvncCommunication.ResponseDesktopClosed, connectionInfo);
                break;

            case HvncCommunication.GetUpdate:
                lock (_currentDesktop)
                {
                    if (_currentDesktop == null || !_currentDesktop.IsOpen)
                    {
                        ResponseByte((byte)HvncCommunication.ResponseUpdateFailed, connectionInfo);
                        return;
                    }

                    try
                    {
                        Desktop.SetCurrent(_currentDesktop);

                        var windows = _currentDesktop.GetWindows();
                        if (windows == null)
                        {
                            ResponseByte((byte)HvncCommunication.ResponseUpdateFailed, connectionInfo);
                            return;
                        }

                        var windowResult = new WindowUpdate {
                            AllWindows = windows.Select(x => x.Handle.ToInt64()).ToList()
                        };

                        const int maxWindowNameLength = 100;
                        var       ptr = Marshal.AllocHGlobal(maxWindowNameLength);

                        try
                        {
                            foreach (var window in windows)
                            {
                                RECT rect;
                                NativeMethods.GetWindowRect(window.Handle, out rect);
                                NativeMethods.GetWindowText(window.Handle, ptr, maxWindowNameLength);

                                var windowInformation = new WindowInformation
                                {
                                    Handle = (int)window.Handle,
                                    Height = rect.Height,
                                    Width  = rect.Width,
                                    X      = rect.X,
                                    Y      = rect.Y,
                                    Title  = Marshal.PtrToStringAnsi(ptr)
                                };

                                var existingRenderWindow =
                                    _renderWindows.FirstOrDefault(x => x.WindowInformation.Handle == (int)window.Handle);

                                if (existingRenderWindow == null)
                                {
                                    windowResult.NewWindows.Add(windowInformation);
                                    _renderWindows.Add(new RenderWindow(windowInformation, window.Handle));
                                }
                                else
                                {
                                    if (existingRenderWindow.WindowInformation.Equals(windowInformation))
                                    {
                                        continue;
                                    }

                                    windowResult.UpdatedWindows.Add(windowInformation);
                                    existingRenderWindow.ApplyWindowInformation(windowInformation);
                                }
                            }
                        }
                        finally
                        {
                            Marshal.FreeHGlobal(ptr);
                        }

                        var windowToRenderHandle = BitConverter.ToInt32(parameter, 1);
                        if (windowToRenderHandle != 0)
                        {
                            var renderWindow =
                                _renderWindows.FirstOrDefault(x => x.WindowInformation.Handle == windowToRenderHandle);

                            if (renderWindow != null)
                            {
                                try
                                {
                                    Debug.Print("Render window: " + windowToRenderHandle);
                                    //windowResult.RenderedWindow = renderWindow.Render();
                                    if (windowResult.RenderedWindow == null)
                                    {
                                        Debug.Print("Render failed");
                                    }
                                    windowResult.RenderedWindowHandle = renderWindow.WindowInformation.Handle;
                                }
                                catch (Exception)
                                {
                                    //shit happens
                                }
                            }
                        }

                        ResponseBytes((byte)HvncCommunication.ResponseUpdate,
                                      new Serializer(typeof(WindowUpdate)).Serialize(windowResult), connectionInfo);
                    }
                    catch (Exception)
                    {
#if DEBUG
                        throw;
#else
                        ResponseByte((byte)HvncCommunication.ResponseUpdateFailed, connectionInfo);
#endif
                    }
                }
                break;

            case HvncCommunication.DoAction:
                lock (_desktopLock)
                {
                    Debug.Print("Begin DoAction");
                    DoAction((HvncAction)parameter[1], parameter.Skip(2).ToArray());
                    Debug.Print("End DoAction");
                }
                break;

            case HvncCommunication.ExecuteProcess:
                lock (_desktopLock)
                {
                    Debug.Print("Begin ExecuteProcess");
                    _currentDesktop.CreateProcess(Encoding.UTF8.GetString(parameter, 1, parameter.Length - 1), "");
                    Debug.Print("End ExecuteProcess");
                }

                connectionInfo.CommandResponse(this,
                                               new[] { (byte)HvncCommunication.ResponseProcessExecuted });
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }