NegotiateStream Sample

One of the features i really like in .NET 2.0 is that you get Kerberos support. NegotiateStream is an implementation of AuthenticatedStream (as SslStream is), so the source code is very similar to my last post.

Notice that you can access the client identity with the RemoteIdentity property. This is a WindowsIdentitiy object that you can use construct a WindowsPrincipal to call IsInRole on and you can set Thread.CurrentPrincipal to use the .NET role based security infrastructure. nice!

NegotiateStream.zip (8.01 KB)

The Server

static void Main(string[] args)
{
    TcpListener listener = new TcpListener(4242);
    listener.Start();

    Console.WriteLine(“Waiting for incoming connection…”);
    TcpClient client = listener.AcceptTcpClient();

    Console.WriteLine(“Authenticating…”);
    NegotiateStream kerb = new NegotiateStream(client.GetStream());

    kerb.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials,
        ProtectionLevel.EncryptAndSign,
        TokenImpersonationLevel.Impersonation);

    Console.WriteLine(“Client Identity: {0}”, kerb.RemoteIdentity.Name);

    WindowsPrincipal principal = new WindowsPrincipal((WindowsIdentity)kerb.RemoteIdentity);
    Console.WriteLine(“Is Admin? : {0}”, principal.IsInRole(WindowsBuiltInRole.Administrator));

    Thread.CurrentPrincipal = principal;
    
    
    DoSomethingOnlyDevelopersCanDo();
}

[PrincipalPermission(SecurityAction.Demand, Role=@”LEASTPRIVILEGEDevelopers”)]
static void DoSomethingOnlyDevelopersCanDo()
{
    Console.WriteLine(“Developers only”);
}

The Client

static void Main(string[] args)
{
    TcpClient client = new TcpClient();
    client.Connect(“localhost”, 4242);

    NegotiateStream kerb = new NegotiateStream(client.GetStream());
    kerb.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, “dbaier/leastprivilege”,
        ProtectionLevel.EncryptAndSign,
        System.Security.Principal.TokenImpersonationLevel.Impersonation);

    StreamWriter writer = new StreamWriter(kerb);
    writer.WriteLine(“Hello Kerberized Server”);
}

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s