RunAsClient() public method

public RunAsClient ( PipeStreamImpersonationWorker impersonationWorker ) : void
impersonationWorker PipeStreamImpersonationWorker
return void
Ejemplo n.º 1
0
    private static void ServerThread(object data)
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);

        int threadId = Thread.CurrentThread.ManagedThreadId;

        // Wait for a client to connect
        pipeServer.WaitForConnection();

        Console.WriteLine("Client connected on thread[{0}].", threadId);
        try
        {
            // Read the request from the client. Once the client has
            // written to the pipe its security token will be available.

            StreamString ss = new StreamString(pipeServer);

            // Verify our identity to the connected client using a
            // string that the client anticipates.

            ss.WriteString("I am the one true server!");
            string filename = ss.ReadString();

            // Read in the contents of the file while impersonating the client.
            ReadFileToStream fileReader = new ReadFileToStream(ss, filename);

            // Display the name of the user we are impersonating.
            Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",
                filename, threadId, pipeServer.GetImpersonationUserName());
            pipeServer.RunAsClient(fileReader.Start);
        }
        // Catch the IOException that is raised if the pipe is broken
        // or disconnected.
        catch (IOException e)
        {
            Console.WriteLine("ERROR: {0}", e.Message);
        }
        pipeServer.Close();
    }
Ejemplo n.º 2
0
    private static void ServerThread(object data)
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);
        int threadId = Thread.CurrentThread.ManagedThreadId;

        //wait for client to connect
        pipeServer.WaitForConnection();

        Console.WriteLine("Client connected on thread[{0}].", threadId);
        try
        {
            //Read the request from the client. Once the client has
            //written to the pipe its security token will be available.
            //We might not need this security token ? 
            //We need interprocess communication on the same computer
            StreamString ss = new StreamString(pipeServer);

            //Verify our identity to the connected client using a 
            //string that the client anticipates

            ss.WriteString("I am the one true server!");
            string filename = ss.ReadString();

            //Read in the contents of the file while impersonating the client.
            ReadFileToStream fileReader = new ReadFileToStream(ss, filename);

            //Display the name of the user we are impersonating. //Impersonating ? 
            Console.WriteLine("Reading file: {0} on thread{1} as user: {2}.",
                filename, threadId, pipeServer.GetImpersonationUserName()); //So impersonation is nothing but name of client at the other end ? Cool!
            pipeServer.RunAsClient(fileReader.Start);
        }
        catch(IOException e)
        {
            Console.WriteLine("ERROR: {0}", e.Message);
        }
        pipeServer.Close();
    }
Ejemplo n.º 3
0
        private static void ServerThread(object data)
        {
            var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);
            int threadId = Thread.CurrentThread.ManagedThreadId;

            pipeServer.WaitForConnection();

            Console.WriteLine("Client connected on thread[{0}].", threadId);
            try
            {
                StreamString ss = new StreamString(pipeServer);
                ss.WriteString("I am the one true server!");
                string filename = ss.ReadString();
                ReadFileToStream fileReader = new ReadFileToStream(ss, filename);
                Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",
                    filename, threadId, pipeServer.GetImpersonationUserName());
                pipeServer.RunAsClient(fileReader.Start);
            }
            catch (IOException e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
            }
            pipeServer.Close();
        }
Ejemplo n.º 4
0
        /// <summary>
        ///   Starts the listener.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void StartListener()
        {
            if (_cancellationTokenSource.Token.IsCancellationRequested) {
                return;
            }

            try {
                if (IsRunning) {
                    Logger.Message("Starting New Listener {0}", listenerCount++);
                    var serverPipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, Instances, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
                        BufferSize, BufferSize, _pipeSecurity);
                    var listenTask = Task.Factory.FromAsync(serverPipe.BeginWaitForConnection, serverPipe.EndWaitForConnection, serverPipe);

                    listenTask.ContinueWith(t => {
                        if (t.IsCanceled || _cancellationTokenSource.Token.IsCancellationRequested) {
                            return;
                        }

                        StartListener(); // spawn next one!

                        if (serverPipe.IsConnected) {
                            var serverInput = new byte[BufferSize];

                            serverPipe.ReadAsync(serverInput, 0, serverInput.Length).AutoManage().ContinueWith(antecedent => {
                                var rawMessage = Encoding.UTF8.GetString(serverInput, 0, antecedent.Result);
                                if (string.IsNullOrEmpty(rawMessage)) {
                                    return;
                                }

                                var requestMessage = new UrlEncodedMessage(rawMessage);

                                // first command must be "startsession"
                                if (!requestMessage.Command.Equals("StartSession", StringComparison.CurrentCultureIgnoreCase)) {
                                    return;
                                }

                                // verify that user is allowed to connect.
                                try {
                                    var hasAccess = false;
                                    serverPipe.RunAsClient(() => {
                                        hasAccess = PermissionPolicy.Connect.HasPermission;
                                    });
                                    if (!hasAccess) {
                                        return;
                                    }
                                } catch {
                                    return;
                                }

                                // check for the required parameters.
                                // close the session if they are not here.
                                if (string.IsNullOrEmpty(requestMessage["id"]) || string.IsNullOrEmpty(requestMessage["client"])) {
                                    return;
                                }
                                var isSync = requestMessage["async"].IsFalse();

                                if (isSync) {
                                    StartResponsePipeAndProcessMesages(requestMessage["client"], requestMessage["id"], serverPipe);
                                } else {
                                    Session.Start(requestMessage["client"], requestMessage["id"], serverPipe, serverPipe);
                                }
                            }).Wait();
                        }
                    }, _cancellationTokenSource.Token, TaskContinuationOptions.AttachedToParent, TaskScheduler.Current);
                }
            } catch /* (Exception e) */ {
                RequestStop();
            }
        }
        private async void btnStartServer_Click(object sender, EventArgs e)
        {
            try
            {
                btnStartServer.Enabled = false;

                using (NamedPipeServerStream pipe = new NamedPipeServerStream(txtPipeName.Text,
                    PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                {
                    await Task.Factory.FromAsync(pipe.BeginWaitForConnection,
                        pipe.EndWaitForConnection, null);

                    UserToken token = null;

                    if (pipe.IsConnected)
                    {
                        pipe.RunAsClient(() => token = TokenUtils.GetTokenFromThread());
                        pipe.Disconnect();
                    }

                    if (token != null)
                    {
                        TokenForm.OpenForm(token, false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnStartServer.Enabled = true;
            }
        }
Ejemplo n.º 6
0
            /// <summary>
            /// Does the client of "pipeStream" have the same identity and elevation as we do?
            /// </summary>
            private bool ClientAndOurIdentitiesMatch(NamedPipeServerStream pipeStream)
            {
                string ourUserName, clientUserName = null;
                bool ourElevation, clientElevation = false;

                // Get the identities of ourselves and our client.
                ourUserName = GetIdentity(false, out ourElevation);
                pipeStream.RunAsClient(delegate() { clientUserName = GetIdentity(true, out clientElevation); });

                Log("Server identity = '{0}', server elevation='{1}'.", ourUserName, ourElevation);
                Log("Client identity = '{0}', client elevation='{1}'.", clientUserName, clientElevation);
                return (ourUserName == clientUserName && ourElevation == clientElevation);
            }
Ejemplo n.º 7
0
        public void ServerThread()
        {
            NamedPipeServerStream pipeServer = new NamedPipeServerStream("FTPbox Server", PipeDirection.InOut, 5);
            int threadID = Thread.CurrentThread.ManagedThreadId;

            pipeServer.WaitForConnection();

            Log.Write(l.Client, "Client connected, id: {0}", threadID);

            try
            {
                StreamString ss = new StreamString(pipeServer);

                ss.WriteString("ftpbox");
                string args = ss.ReadString();

                ReadMessageSent fReader = new ReadMessageSent(ss, "All done!");

                Log.Write(l.Client, "Reading file: \n {0} \non thread [{1}] as user {2}.", args, threadID, pipeServer.GetImpersonationUserName());

                List<string> li = new List<string>();
                li = ReadCombinedParameters(args);

                CheckClientArgs(li.ToArray());

                pipeServer.RunAsClient(fReader.Start);
            }
            catch (IOException e)
            {
                Common.LogError(e);
            }
            pipeServer.Close();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Does the client of "pipeStream" have the same identity and elevation as we do?
        /// </summary>
        private static bool ClientAndOurIdentitiesMatch(NamedPipeServerStream pipeStream)
        {
            var serverIdentity = GetIdentity(impersonating: false);

            Tuple<string, bool> clientIdentity = null;
            pipeStream.RunAsClient(() => { clientIdentity = GetIdentity(impersonating: true); });

            CompilerServerLogger.Log($"Server identity = '{serverIdentity.Item1}', server elevation='{serverIdentity.Item2}'.");
            CompilerServerLogger.Log($"Client identity = '{clientIdentity.Item1}', client elevation='{serverIdentity.Item2}'.");

            return
                StringComparer.OrdinalIgnoreCase.Equals(serverIdentity.Item1, clientIdentity.Item1) &&
                serverIdentity.Item2 == clientIdentity.Item2;
        }