Skip to content

Instantly share code, notes, and snippets.

@peterblazejewicz
Created January 1, 2025 22:08
Show Gist options
  • Save peterblazejewicz/2a1e03054beafc6ce36bead2d09c233b to your computer and use it in GitHub Desktop.
Save peterblazejewicz/2a1e03054beafc6ce36bead2d09c233b to your computer and use it in GitHub Desktop.
Named pipes communication snip
using Shared;
var pipeClient =
new NamedPipeClientStream(".", "testpipe",
PipeDirection.InOut, PipeOptions.None,
TokenImpersonationLevel.Impersonation);
Console.WriteLine("Connecting to server...\n");
pipeClient.Connect();
var ss = new StreamString(pipeClient);
// Validate the server's signature string.
if (ss.ReadString() == "I am the one true server!")
{
// The client security token is sent with the first write.
// Send the name of the file whose contents are returned
// by the server.
ss.WriteString("killprocess");
}
else
{
Console.WriteLine("Server could not be verified.");
}
pipeClient.Close();
// Give the client process some time to display results before exiting.
Thread.Sleep(4000);
using Shared;
await using var pipeServer =
new NamedPipeServerStream("testpipe", PipeDirection.InOut);
Console.WriteLine("Waiting for connection...");
await pipeServer.WaitForConnectionAsync();
Console.WriteLine("Client connected [{0}].", pipeServer.SafePipeHandle.ToString());
try
{
Console.WriteLine("Connected to client.");
// Read the request from the client. Once the client has
// written to the pipe its security token will be available.
var 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!");
var message = ss.ReadString();
// Display the name of the user we are impersonating.
Console.WriteLine("Message received {0} as user: {1}.",
message, pipeServer.GetImpersonationUserName());
}
// Catch the IOException that is raised if the pipe is broken
// or disconnected.
catch (IOException e)
{
Console.WriteLine("ERROR: {0}", e.Message);
}
Console.WriteLine("Disconnecting...");
pipeServer.Close();
using System.Text;
namespace Shared;
public class StreamString(Stream ioStream)
{
private readonly UnicodeEncoding _streamEncoding = new();
public string ReadString()
{
var len = 0;
len = ioStream.ReadByte() * 256;
len += ioStream.ReadByte();
var inBuffer = new byte[len];
ioStream.ReadExactly(inBuffer, 0, len);
return _streamEncoding.GetString(inBuffer);
}
public int WriteString(string outString)
{
var outBuffer = _streamEncoding.GetBytes(outString);
var len = outBuffer.Length;
if (len > UInt16.MaxValue)
{
len = (int)UInt16.MaxValue;
}
ioStream.WriteByte((byte)(len / 256));
ioStream.WriteByte((byte)(len & 255));
ioStream.Write(outBuffer, 0, len);
ioStream.Flush();
return outBuffer.Length + 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment