external authentication login script using c#

I don't know if anybody has already done it, but this is a small script which allows external authentication using C# under windows.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ExternalAuthenticationCSharpScript
{
	class Program
	{
		static void Main(string[] args)
		{
			const int maxbuflen = 1000;		// maximum buffer len
			int read;				// number of bytes read
			char[] charray = new char[maxbuflen];	// buffer
			
			String opcode;				// operation code
			String username;			// username
			String password = "";			// password

			// Read data from stdin
			read = Console.In.Read(charray, 0, 2);
			if (read != 2)
			{
				return;
			}

			// Perform big endian conversion
			int len = charray[1] + (charray[0] * 256);
			// Check for buffer overrun
			if (len > maxbuflen)
			{
				return;
			}

			// Read opcode, username and password
			read = Console.In.ReadBlock(charray, 0, len);
			
			// Splits the data
			string data = new string(charray);
			string[] elements = data.Split(':');

			opcode = elements[0];
			username = elements[1];
			if (elements.Length > 2)
				password = elements[2];

			/*
			 * PERFORM AUTHENTICATION HERE
			 */
			
			// Prepare return value, first short is always 2
			charray[0] = (char)0;
			charray[1] = (char)2;
			
			// Second short is 1 for success, 0 for failure
			charray[2] = (char)0;
			charray[3] = (char)1; // or 0 for failure

			// Send return value
			Console.Out.Write(charray, 0, 4);

			return;
		}
	}
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

sizeof(char) in .NET is 2.

sizeof(char) in .NET is 2. This code will break if the incoming data is sufficiently large. Use a binary reader to read the correct number of bytes from stdin.

// (this should be outside your while(true) loop)
var stdinStream = Console.OpenStandardInput();
var binReader = new BinaryReader(stdinStream);

// Read data from stdin
var b1 = binReader.ReadByte();
var b2 = binReader.ReadByte();

// Perform big endian conversion
int len = b2 + (b1 * 256);

// Check for buffer overrun
if (len > maxbuflen)
    throw new InternalBufferOverflowException(string.Format("{0} > {1}", len, maxbuflen));
                   
// Read opcode, username and password
var bytes = binReader.ReadBytes(len);
var data = ASCIIEncoding.ASCII.GetString(bytes);
string[] elements = data.Split(':');

// etc etc ...

I added this page, so people

I added this page, so people can find your example easier: check_csharp

not anonymous anymore

Sorry, didn't register to the site before posting. Now I have an account.
fc

Syndicate content