programming with esskar

Just another WordPress.com weblog

Run CouchDB as service under Windows with AnyService

with one comment

I started loving CouchDB, even under windows. But it lacks a method to run it as a service. So, i wrote myself a little tool called AnyService, to be able to install CouchDB as a windows system service. (Remarks: you can use AnyService to turn any program into a service ;-) )
Here is how it’s done:

AnyService.exe install CouchDB "C:\Program Files\Apache Software Foundation\CouchDB\bin\erl.exe -smp auto -sasl errlog_type error -eval 'application:load(crypto)' -eval 'application:load(couch)' -eval 'crypto:start()' -eval 'couch_server:start([''../etc/couchdb/default.ini'', ''../etc/couchdb/local.ini'']), receive done -> done end.'"
AnyService.exe start CouchDB

Written by esskar

March 30, 2010 at 12:19 pm

Posted in .NET programming

Tagged with , ,

Perl-like-Map in C#

leave a comment »

If you know a little bit of Perl, you probably know the map function (perldoc -f map).
Map takes an expression E and a list L, transforms the elements of L using the expression E and returns a new list with the transformed items. A short example:

my @words = ('foo', 'bar', 'perl', 'is', 'cool');
my @firsts = map { substr($_, 0, 1) } @words;

The above code takes @words and transforms its elements into a list containing only the first letter of each word in @words. (At all perl monks ou there: i know that there are more simple ways to achieve that :-) ).
Anyway, i tried to achieve the above functionalty in C#. It kinda works by using extensions on IEnumerable:

public static IEnumerable<TResult> Map<TSource, TResult>(this IEnumerable<TSource> collection, Func<TSource, TResult> converter)
{
   if(collection == null)
      return null;
   List<TResult> retval = new List<TResult>();   
   foreach (TSource s in collection)
      retval.Add(converter(s));            
   return retval;
}

That’s about it. Last but not least, the above example in a csharpish-way

string[] words = new string[] { "foo", "bar", "perl", "is", "cool", "but", "csharp", "is", "too" };
IEnumerable<char> firsts = words.Map(delegate(string s) { return s.Substring(0, 1); });
// or more .NET 3 style
var firsts = words.Map(s => s.Substring(0, 1));

NICE!

Written by esskar

February 23, 2010 at 7:14 am

JSONBuilder in C#

with one comment

Small JSON Builder (no garanty it will work for every object):

public sealed class JSONBuilder
{
    private List<object> m_objects = new List<object>();

    public void Append(object obj)
    {
        m_objects.Add(obj);
    }

    private static void EncodeAny(StringBuilder sb, object o)
    {
        if (o == null)
            sb.Append("null");
        else if (o is string || o is Enum || o is Guid || o is char)
            JSONBuilder.EncodeString(sb, o.ToString());
        else if (o is sbyte || o is byte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong || o is decimal || o is double || o is float)
            sb.Append(Convert.ToString(o, System.Globalization.NumberFormatInfo.InvariantInfo));
        else if (o is bool)
            sb.Append(o.ToString().ToLower());
        else if (o is IDictionary)
            JSONBuilder.EncodePairs(sb, o as IDictionary);
        else if (o is Array || o is IList || o is ICollection)
            JSONBuilder.EncodeArray(sb, o as IEnumerable);
        else
            JSONBuilder.EncodeObject(sb, o);
    }

    private static void EncodeObject(StringBuilder sb, object o)
    {
        Type t = o.GetType();
        bool addComma = false;            

        sb.Append("{");            
        foreach (MemberInfo member in t.GetMembers())
        {
            if (member.MemberType != MemberTypes.Property) continue;
            PropertyInfo pi = t.GetProperty(member.Name);
            if (pi == null) continue;
            MethodInfo mi = pi.GetGetMethod();
            if (mi == null || pi.GetSetMethod() == null) continue; // we could serialize, but could not deserialize

            if (addComma) sb.Append(',');
            JSONBuilder.EncodePair(sb, member.Name, mi.Invoke(o, null));
            addComma = true;
        }
        sb.Append("}");
    }

    private static void EncodePair(StringBuilder sb, string s, object o)
    {
        JSONBuilder.EncodeString(sb, s);
        sb.Append(':');
        JSONBuilder.EncodeAny(sb, o);
    }

    private static void EncodeArray(StringBuilder sb, IEnumerable i)
    {
        sb.Append('[');
        bool addComma = false;
        foreach (object o in i)
        {
            if (addComma) sb.Append(',');
            JSONBuilder.EncodeAny(sb, o);
            addComma = true;
        }
        sb.Append(']');
    }

    private static void EncodePairs(StringBuilder sb, IDictionary i)
    {
        sb.Append('{');
        bool addComma = false;
        foreach (DictionaryEntry o in i)
        {
            if (addComma) sb.Append(',');
            JSONBuilder.EncodePair(sb, o.Key.ToString(), o.Value);
            addComma = true;
        }
        sb.Append('}');
    }

    private static void EncodeString(StringBuilder sb, string s)
    {
        sb.Append('"');
        foreach (char c in s)
        {
            switch (c)
            {
                case '\t': sb.Append("\\t"); break;
                case '\r': sb.Append("\\r"); break;
                case '\n': sb.Append("\\n"); break;
                case '"':
                case '\\': sb.Append("\\" + c); break;
                default: sb.Append(c >= ' ' && c < 128 ? c.ToString() : "\\u" + ((int)c).ToString("X4")); break;
            }
        }
        sb.Append('"');
    }

    public static string Build(object o)
    {
        JSONBuilder json = new JSONBuilder();
        json.Append(o);
        return json.ToString();
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        if (m_objects.Count == 0) JSONBuilder.EncodeAny(sb, null);
        else if (m_objects.Count == 1) JSONBuilder.EncodeAny(sb, m_objects[0]);
        else JSONBuilder.EncodeArray(sb, m_objects);
        return sb.ToString();
    }
}

I use it to store objects into the registry and still be able to edit the values there by hand.
An extension that helps me here is:
namespace System
{
    public static class ObjectExtension
    {
        public static string ToJSON(this object obj)
        {
            return JSONBuilder.Build(obj);
        }
    }
}

Next blog entry will be a JSON”Unbuilder” … :-) stay tuned.

Written by esskar

February 18, 2010 at 2:28 pm

Simulate a Click

with 5 comments

Small snippet to kinda simulate a click on a control

static public class ControlExtensions
{
        static public void SimulateClick(this Control control)
        {
            if (control != null)
            {
                MethodInfo method = typeof(Control).GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
                if (method != null)
                    method.Invoke(control, new object[] { EventArgs.Empty });                
            }
        }
}

Does the job for me – so far.

Written by esskar

February 17, 2010 at 7:12 am

Posted in .NET programming

Tagged with , ,

Update as fast as possible but slow down a bit

leave a comment »

You may think updateing your forms or controls in realtime is easy.
Let’s consider the following scenario: you have a server-client application where the server sends his clients messages. Your clients displays those messages in a Label, displaying always that newest message. The messages are send asynchronously.
So, here is some code that updates our Label

class ClientForm : Form
{
    private Label m_label;

    public ClientForm()
    {
        m_label = new Label();
        // add code to initialize and position the label
        this.Controls.Add(m_label);
    }

    // this message is called by some other thread, so we have to
    // ensure that we dispatch the call to the UI thread
    private delegate void DisplayServerStatusMessageCallback(string msg);
    public void DisplayServerStatusMessage(string serverStatusMessage)
    {
         if (!this.InvokeRequired)
         {
             m_label = serverStatusMessage;
         }
         else
         {
            this.Invoke(new DisplayServerStatusMessageCallback(this.DisplayServerStatusMessage), serverStatusMessage);
         }
    }
}

The above code is fine as long as the server message come in slowly (let’s say 1-5 per second).

Now consider the scenario when the server sends 1000 messages a second, then the code above would probably freeze your application (even though you call Invoke). The problem is that your code will invoke all the time and has no time to do someting else. Bummer! :-)

So, i came up with a little class called UITimerUpdater. The idea behind that class is that it uses a timer to notify you when it is okay to update your form or controls.
Have a look:

public sealed class UITimerUpdater : IDisposable
{
    private object m_sync = new object();                
    private Timer m_timer;
    private Control m_control;
    private Action m_updateCallback;
    private int m_syncing = 0;
    private bool m_disposed = false, m_notify = false, m_notifyAlways = false, m_fireAfterSync = false;

    public UITimerUpdater(Control control, int updateTimeout, Action updateCallback)
        : this(control, updateTimeout, updateCallback, false)
    {
    }

    public UITimerUpdater(Control control, int updateTimeout, Action updateCallback, bool notifyAlways)
    {
        if (control == null)
            throw new ArgumentNullException("control");
        if (updateCallback == null)
            throw new ArgumentNullException("updateCallback");

        m_control = control;
        m_updateCallback = updateCallback;
        m_notifyAlways = notifyAlways;

        m_timer = new Timer();
        m_timer.Interval = updateTimeout;
        m_timer.Tick += new EventHandler(OnTimerTick);
        m_timer.Start();            
    }

    ~UITimerUpdater()
    {
        this.Dispose(false);
    }

    private void Fire()
    {
        if (m_notify || m_notifyAlways)
        {
            m_control.UIThread(m_updateCallback); // see ControlExtensions below
            m_notify = false;
        }         
    }

    public void Sync(Action action)
    {
        this.Sync(action, false);
    }

    public void Sync(Action action, bool uisafe)
    {
        this.Sync(action, uisafe, false);
    }

    public void SyncAndFire(Action action)
    {
        this.SyncAndFire(action, false);
    }

    public void SyncAndFire(Action action, bool uisafe)
    {
        this.Sync(action, uisafe, true);
    }

    private void Sync(Action action, bool uisafe, bool fire)
    {
        if (action == null)
            throw new ArgumentNullException("action");

        this.BeginSyncing();
        try
        {
            if (uisafe) m_control.UIThread(action);
            else action.Invoke();                
        }
        finally { this.EndSyncing(fire); }
    }

    private void OnTimerTick(object sender, EventArgs e)
    {
        m_timer.Stop();
        lock (m_sync)
        {
            if (m_syncing <= 0)
                this.Fire();                
        }
        m_timer.Start();
    }

    public void BeginSyncing()
    {
        lock (m_sync) { m_syncing++; }
    }

    public bool IsUpdateing
    {
        get { lock (m_sync) { return m_syncing > 0; } }
    }

    public void EndSyncing()
    {
        this.EndSyncing(true);
    }

    public void EndSyncing(bool tryToFire)
    {
        lock (m_sync)
        {
            if (m_syncing <= 0)
                throw new InvalidOperationException("You have to call BeginUpdate first.");
            m_notify = true;
            m_syncing--;
            m_fireAfterSync = m_fireAfterSync || tryToFire;
            if (m_fireAfterSync)
            {
                if (m_syncing == 0)
                {
                    this.Fire();                    
                    m_fireAfterSync = false;
                }
            }
        }
    }

    #region IDisposable Members

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!m_disposed)
        {
            if (disposing)
            {
                m_timer.Stop();
                m_timer.Dispose();
            }
            m_disposed = true;
        }
    }

    #endregion
}


// an extension to System.Windows.Forms.Control to allow calling Control.Invoke more easyly.
namespace System.Windows.Forms
{
    public delegate void ActionControl(Control c);

    static public class ControlExtensions
    {
        static public void UIThread(this Control control, Action code)
        {
            if (control.InvokeRequired) control.BeginInvoke(code);
            else code.Invoke();
        }

        static public void UIThread(this Control control, ActionControl code)
        {
            if (control.InvokeRequired) control.BeginInvoke(code, control);
            else code.Invoke(control);
        }

        static public void UIThreadInvoke(this Control control, Action code)
        {
            if (control.InvokeRequired) control.Invoke(code);
            else code.Invoke();
        }        
    }
}

As i always post code without any comments ( :) ), let’s see how you can use it by changing the above client example:

class ClientForm : Form
{
    private Label m_label;
    private UITimerUpdater m_updater;
    private string m_newestServerStatusMessage;

    public ClientForm()
    {
        m_label = new Label();
        // add code to initialize and position the label
        this.Controls.Add(m_label);
        m_updater = new UITimerUpdater(this, 1000, this.UpdateServerStatusMessage);
    }
    
    // this is now called once every second by the UITimerUpdater 
    private void UpdateServerStatusMessage()
    {
       // display the newest message
       m_label.Text = m_newestServerStatusMessage;
    }

    public void DisplayServerStatusMessage(string serverStatusMessage)
    {
         // save the newest serverStatusMessage
         m_updater.Sync(delegate() { m_newestServerStatusMessage = serverStatusMessage; });
         // you could also call
         // m_update.BeginSyncing();
         // try { m_newestServerStatusMessage = serverStatusMessage; }
         // finally { m_update.EndSyncing(); }
    }
}

HTH

Written by esskar

February 15, 2010 at 2:17 pm

Mojolicious

leave a comment »

Since i’ve never liked C# and web programming, i falled back to my 2nd-choice programming language: Perl.
Perl combined with Mojolicious and Mojolicious::Lite.
To get a feeling how easy it is to write great web applications, here is a sample of a Paste application in less than 130 lines of code:

Paste application powered by Mojo and Mojolicious::Lite

Written by esskar

January 13, 2010 at 1:20 pm

Posted in Perl programming

Tagged with , ,

Secure Remote Password protocol (SRP)

with one comment

The Secure Remote Password Protocol (SRP) is a password-authenticated key agreement protocol. Before, I used digest algorithm (similar to Digest access authentication) to authenticate my users. As I had to add encryption to my message system (not 100% encrytion means only some messages are confidential) I decided to implement SRP as it

  • allows to securly authenticate a user
  • creates a common key that can be used as an encryption key
  • is something new to implement as I like to implement new stuff :-)

Before I start, some helpful extensions I will be using along the way:

namespace System.IO
{
    public static class StreamExtension
    {
        public static void Write(this Stream s, byte[] buffer)
        {
            s.Write(buffer, 0, buffer.Length);
        }

        public static int Read(this Stream s, byte[] buffer)
        {
            return s.Read(buffer, 0, buffer.Length);
        }
    }
}

using System.Runtime.InteropServices;

namespace System.Security
{
    public static class SecureStringExtension
    {
        public static string ConvertToUnsecureString(this SecureString securePassword)
        {
            if (securePassword == null)
                throw new ArgumentNullException("securePassword");

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
    }
}

Implementing SRP involves a lot of BigInteger calculations, such as multiplying and taking the exponent of some large number. The .Net framework does not yet implement such a BigInteger class, so I’m using some classes from Mono. I included Mono.Math.BigInteger, Mono.Math.Prime.ConfidenceFactor and .PrimalityTests, Mono.Math.Prime.Generator.NextPrimeFinder, .PrimeGeneratorBase, and .SequentialSearchPrimeGeneratorBase.

As the protocol description says, it all starts with N and g:
N should be a secure prime, which means that N is calculated by N=2q + 1 where q is also a prime. Finding such an N is easy but takes a lot of time specially if N should be greater than 1024 bits. N and g don’t have to be secure, so you can just define them once.

Here is a N of bit length 2048 encoded as Base64

string N_Base64 = "rGvbQTJKmpvxZt5eE4lYL69ytmUZh+4H/DGSlD21YFCjcynLtKCZ7YGT4HV3Z6E91SMSq0s"
				+ "DMQ3Nf0ip2gT9UOgIOWntt2ewz2CVF5oWOrNmGgX71fqq6CkYqZYvC5O4Vfl5k+yXXuqoDX"
				+ "QK2/T/dHNZ0EHVwz6nHSgeRGsUdzvKl7Q6I/uAFna9IHpDbGSB8dK5B4cXRhpbnTLmiPh3S"
				+ "FRFI7UksNV9Xqd6J3XS7PoDLPvb9S+zeGFgJ5AE5Xrmr4dOcwPOUymczAQce8MI2CpWmPOo"
				+ "0MOCca41+Onb+7aUtcgD2J965DXeI21SX1R1m2XjcvzWjvIPpxEfnkr/cw==";
BigInteger N = new BigInteger(Convert.FromBase64String(N_Base64));

g is just a generator of the multiplicative group. So, it is used in caluclations like g^x where x is very large. Most people would probably choose g=2. But i’m not “most people”, so i set g=3.

As you look further into the description, you’ll see the that there are a lot of variables needed on both sides (server and client side). To make life easier, let’s define a base class for that:

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

using System.Security;
using System.Security.Cryptography;

using Mono.Math;

namespace Esskar.Security.Authen.SRP
{
	public abstract class SRPBase
	{
		// initialize some random number generaror
		private static RandomNumberGenerator s_rng = RandomNumberGenerator.Create();
	
		/// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
		public SRPBase(BigInteger N, BigInteger g)           
		{            
			if (N == null)
				throw new ArgumentNullException("N");
			if (g == null)
				throw new ArgumentNullException("g");
			this.N = N;
			this.g = g;                        
		}

		/// <summary>
        /// N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible
        /// </summary>
		public BigInteger N { get; private set; }

		/// <summary>
        /// g is a generator of the multiplicative group
        /// </summary>
		public BigInteger g { get; private set; }
	}
}

The next parameter that will be defined is k. k is a parameter derived by both sides; for example, k = H(N, g), where H() is a hash function; e.g., SHA-256. This goes into our SRPBase class:
namespace Esskar.Security.Authen.SRP
{
	public abstract class SRPBase
	{
		private BigInteger m_k;

		/// <summary>
        /// k is a parameter derived by both sides; for example, k = H(N, g).
        /// </summary>
		public BigInteger k
		{
			get
			{
				if (m_k == null)
				{
					byte[] both = SRPHelper.JoinArrays(this.N.GetBytes(), this.g.GetBytes());
					byte[] hash = SRPHelper.ShaInstance.ComputeHash(both);
					m_k = new BigInteger(hash);
				}
				return m_k;
			}
		}
	}
}

s, the small salt, is calculated on the server side and send to the client. So s has to be a getter/setter property.
We also extend our constructor to be able to pass s as a parameter, and define I and p (Username and Password of the user to authenticate).
namespace Esskar.Security.Authen.SRP
{
	public abstract class SRPBase
	{
		private BigInteger m_s;
				
		/// <param name="userName">I is an identifying username.</param>
        /// <param name="password">p is the user's password.</param>
		/// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
		public SRPBase(string userName, SecureString password, BigInteger N, BigInteger g)           
			: this(userName, password, null, N, g) { }
		
		/// <param name="userName">I is an identifying username.</param>
        /// <param name="password">p is the user's password.</param>
		/// <param name="s">s is a small salt.</param>
		/// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
		public SRPBase(string userName, SecureString password, byte[] s, BigInteger N, BigInteger g)           
		{            
			if (N == null)
				throw new ArgumentNullException("N");
			if (g == null)
				throw new ArgumentNullException("g");
			if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (password == null)
                throw new ArgumentNullException("password");
			this.UserName = userName;            
            this.Password = password.Copy();
			this.s = s;
			this.N = N;
			this.g = g;                        
		}
		
		/// <summary>
        /// I, is an identifying username.
        /// </summary>
        public string UserName { get; private set; }

        private SecureString Password { get; set; }
		
		public byte[] s
        {
            get
            {
				// not set yet, generate some random data
                if (m_s == null)
                {
                    m_s = new byte[16];
                    lock (s_rng) { s_rng.GetNonZeroBytes(m_s); }
                }
                return m_s;
            }
            set { m_s = value; }
        }
	}
}

Now we have everything to calculate x = H(s, p), and the host password verifier v = g^x. Hint: If you do not want to store the password on the server side as clear text, you can store only v and s only. If you plan to change g, you better off to store g along as well.
namespace Esskar.Security.Authen.SRP
{
	public abstract class SRPBase	
	{
		private BigInteger m_x, m_v;
	
		/// <summary>
        /// x = H(s, p)
        /// </summary>
        public BigInteger x
        {
            get
            {
                if (m_x == null)
                {
                    byte[] innerBytes = Encoding.UTF8.GetBytes(this.UserName + ":" + this.Password.ConvertToUnsecureString());
                    byte[] bytes = SRPHelper.JoinArrays(this.s, innerBytes);
                    byte[] hash = SRPHelper.ShaInstance.ComputeHash(bytes);
                    m_x = new BigInteger(hash);
                }
                return m_x;
            }
        }
		
		/// <summary>
        /// v is the host's password verifier, v = g^x, x = H(s,p).
        /// </summary>
        public BigInteger v
        {
            get
            {
                if (m_v == null)                
                    m_v = this.g.ModPow(this.x, this.N);                
                return m_v;
            }            
        }
	}
}

Let’s go on. A and B are both calculated. A is calculated on the client side as A = g^a, and B is calculated on the server side as B = kv + g^b. But values are exchanged; so at some time, both sides contain A and B, so we make some stub implementation for both properties and at them to our constructors.
namespace Esskar.Security.Authen.SRP
{
	public abstract class SRPBase	
	{
		private byte[] m_K;
	
		/// <param name="userName">I is an identifying username.</param>
        /// <param name="password">p is the user's password.</param>
        /// <param name="A">A = g^a, calculated by the client, send to the server</param>
        /// <param name="B">B = kv + g^b, calculated by the server, send to the client</param>
        /// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
        public SRPBase(string userName, SecureString password, BigInteger A, BigInteger B, BigInteger N, BigInteger g)
            : this(userName, password, null, A, B, N, g) { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName">I is an identifying username.</param>
        /// <param name="password">p is the user's password.</param>
        /// <param name="s">s is a small salt.</param>
        /// <param name="A">A = g^a, calculated by the client, send to the server</param>
        /// <param name="B">B = kv + g^b, calculated by the server, send to the client</param>
        /// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
        public SRPBase(string userName, SecureString password, byte[] s, BigInteger A, BigInteger B, BigInteger N, BigInteger g)           
        {            
            if (N == null)
                throw new ArgumentNullException("N");
            if (g == null)
                throw new ArgumentNullException("g");
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (password == null)
                throw new ArgumentNullException("password");

            this.N = N;
            this.g = g;            
            this.A = A;
            this.B = B;
            this.s = s;
            this.UserName = userName;            
            this.Password = password.Copy();
        }
		
		/// <summary>
        /// Carol calculates A = g^a and sends it to Steve
        /// </summary>
        public virtual BigInteger A
        {
            get; set;
        }

        /// <summary>
        /// Steve calculates B = kv + g^b and sends it to Carol
        /// </summary>
        public virtual BigInteger B 
        {
            get; set;
        }
		
		/// <summary>
        /// Secret
        /// </summary>
        public abstract BigInteger S { get; }
		
		/// <summary>
        /// Strong Session Key
        /// </summary>
        public byte[] K
        {
            get
            {
                if (m_K == null)
                    m_K = SRPHelper.ShaInstance.ComputeHash(this.S.GetBytes());
                return m_K;
            }
        }
	}
}

As you noticed, we added two more properties: the abstract getter property S as well as K. S is the secret that is calculated on both sides and must never be exchanged. The client calculates S as S=(B – kg^x)^(a + ux), and the client defines S=(Av^u)^b. a and b are both random numbers, generated on client and server and also get never exchanged. Funny is, that S on both sides are equal. Well, it’s not funny it’s pure math and it took me some time to convince myself that both equations for S are equivalent. :-) K is just K=H(S). K can later be used as an encryption key.

To finish up our SRPBase class, we are now able to define M1 and M2. M1 is first send to the server. The server itself calculates M1 with the information it collected and compares the received M1 with it’s own M1. If both are equal, the server has proof that the client knows the right username + password combination. It then sends M2 to the client. Client does the same thing now. It calculates its own M2, compares and verifies. We go in detail later.

namespace Esskar.Security.Authen.SRP
{
	public abstract class SRPBase	
	{
		/// <summary>
        /// M1, Carol sends M1 to Steve
        /// M1 = H(H(N) XOR H(g) | H(I) | s | A | B | K)
        /// </summary>
        public virtual byte[] M1
        {
            get
            {
                byte[] hg = SRPHelper.ShaInstance.ComputeHash(this.g.GetBytes());
                byte[] hN = SRPHelper.ShaInstance.ComputeHash(this.N.GetBytes());

                byte[] gNXorBytes = SRPHelper.XorArrays(hN, hg);
                byte[] userNameBytes = Encoding.UTF8.GetBytes(this.UserName);
                byte[] hUserNameBytes = SRPHelper.ShaInstance.ComputeHash(userNameBytes);
                
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(gNXorBytes);
                    ms.Write(hUserNameBytes);
                    ms.Write(this.s);
                    ms.Write(this.A.GetBytes());
                    ms.Write(this.B.GetBytes());
                    ms.Write(this.K);

                    return SRPHelper.ShaInstance.ComputeHash(ms.ToArray());
                }
            }
        }

        /// <summary>
        /// M2, Steve sends M2 to Carol
        /// M2 = H(A | M1 | K).
        /// </summary>
        public byte[] M2
        {
            get
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(this.A.GetBytes());
                    ms.Write(this.M1);
                    ms.Write(this.K);

                    return SRPHelper.ShaInstance.ComputeHash(ms.ToArray());
                }
            }
        }	
	}
}

Now, we define our client side, class SRPRequest:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;

using Mono.Math;

namespace Esskar.Security.Authen.SRP
{
    public class SRPRequest : SRPBase
    {
        private BigInteger m_a, m_S;
                
        /// <summary>
        /// SRP Request, constructed on the client side
        /// </summary>
        /// <param name="userName">I is an identifying username.</param>
        /// <param name="password">p is the user's password.</param>
        /// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
        public SRPRequest(string userName, SecureString password, BigInteger N, BigInteger g)
            : base(userName, password, null, null, N, g) { }
        
        /// <summary>
        /// a is random
        /// </summary>
        private BigInteger a
        {
            get
            {
                if(m_a == null)
                    m_a = BigInteger.GenerateRandom(1024);
                return m_a;
            }
        }

        /// <summary>
        /// A = g^a
        /// </summary>
        public override BigInteger A
        {
            get
            {
                if (base.A == null)
                    base.A = this.g.ModPow(this.a, this.N);
                return base.A;
            }
        }

        /// <summary>
        /// Secret calculated on the client, (B - kg^x)^(a + ux)
        /// </summary>
        public override BigInteger S
        {
            get
            {
                if (m_S == null)
                    m_S = (this.B + (this.N - ((this.k * this.g.ModPow(this.x, this.N)) % this.N))).ModPow(this.a + this.u * this.x, this.N);
                return m_S;
            }        
        }
    }
}

and our ServerSide, class SRPReply
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;

using Mono.Math;

namespace Esskar.Security.Authen.SRP
{
    public class SRPReply : SRPBase
    {
        private BigInteger m_b;

        /// <summary>
        /// SRP Reply, constructed on the server side
        /// </summary>
        /// <param name="userName">I is an identifying username.</param>
        /// <param name="password">p is the user's password.</param>
        /// <param name="A">A = g^a, calculated by the client, send to the server</param>
        /// <param name="N">N is a safe prime. Must be large enough so that computing discrete logarithms modulo N is infeasible</param>
        /// <param name="g">g is a generator of the multiplicative group</param>
        public SRPReply(string userName, SecureString password, BigInteger A, BigInteger N, BigInteger g)
            : base(userName, password, A, null, N, g) { }

        /// <summary>
        /// random number
        /// </summary>
        private BigInteger b
        {
            get
            {
                if (m_b == null)
                    m_b = BigInteger.GenerateRandom(1024);
                return m_b;
            }
        }
                        
        /// <summary>
        /// B = kv + g^b
        /// </summary>
        public override BigInteger B
        {
            get
            {
                if (base.B == null)
                    base.B = (this.k * this.v + this.g.ModPow(this.b, this.N)) % this.N;
                return base.B;
            }            
        }

        /// <summary>
        /// Secret calculated on the server: (Av^u)^b
        /// </summary>
        public override BigInteger S
        {
            get  { return (this.A * this.v.ModPow(this.u, this.N)).ModPow(this.b, this.N); }
        }
    }
}

Nice. We now have everything to authenticate our users.
Here a little test. (Note that this test does not send any data, it just verifies that our client and server calculate the right things).
public static class SRPTester
{
	private static string N_Base64 = "rGvbQTJKmpvxZt5eE4lYL69ytmUZh+4H/DGSlD21YFCjcynLtKCZ7YGT4HV3Z6E91SMSq0s"
								   + "DMQ3Nf0ip2gT9UOgIOWntt2ewz2CVF5oWOrNmGgX71fqq6CkYqZYvC5O4Vfl5k+yXXuqoDX"
								   + "QK2/T/dHNZ0EHVwz6nHSgeRGsUdzvKl7Q6I/uAFna9IHpDbGSB8dK5B4cXRhpbnTLmiPh3S"
								   + "FRFI7UksNV9Xqd6J3XS7PoDLPvb9S+zeGFgJ5AE5Xrmr4dOcwPOUymczAQce8MI2CpWmPOo"
								   + "0MOCca41+Onb+7aUtcgD2J965DXeI21SX1R1m2XjcvzWjvIPpxEfnkr/cw==";

	private static Mono.Math.BigInteger g = new Mono.Math.BigInteger(3);

	public static SRPRequest ClientRequest(string userName, SecureString password)
	{
		return new SRPRequest(userName, password, new BigInteger(Convert.FromBase64String(N_Base64)), g);
	}

	public static SRPReply ServerReply(string userName, SecureString password, BigInteger A)
	{
		return new SRPReply(userName, password, A, new BigInteger(Convert.FromBase64String(N_Base64)), g);
	}
	
	static void Main(string[] args)
	{
		string userName = "foo";
		SecureString password = new SecureString();

		SRPRequest srpRequest = SRPTester.ClientRequest(userName, password);

		// We generated the request, and have to send A to the server. Somehow.
		// The server takes A to initialize it's reply

		SRPReply srpReply = SRPTester.ServerReply(userName, password, srpRequest.A);
		if ((srpRequest.A % srpReply.N) == 0) // safeguard 1
			throw new Exception("A mod N is zero.");                            

		// The server sends now s and B to the client, the client adds them to its object
		if ((srpReply.B % srpRequest.N) == 0) // safeguard 2
			throw new Exception("B mod N is zero.");

		srpRequest.B = srpReply.B;
		srpRequest.s = srpReply.s;
		if (srpRequest.u == 0) // safeguard 3
			throw new Exception("u is zero.");

		// now, the client sends M1 to the server and it verifies that its M1 is equal to the M1 of the client

		if (!SRPHelper.Equals<byte>(srpRequest.M1, srpReply.M1))
			throw new Exception("M1 not equal M1.");

		// if everything looks good, the server sends now its M2 to the client and the client verifies M2

		if (!SRPHelper.Equals<byte>(srpRequest.M2, srpReply.M2))
			throw new Exception("M2 not equal M2.");
	}
}

To make this post complete, here is the code of the SRPHelper class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;

namespace Esskar.Security.Authen.SRP
{
    /// <summary>
    /// Some useful functions used frequently
    /// </summary>
    public static class SRPHelper
    {
        /// <summary>
        /// Sha256 Instance used to compute hashes
        /// </summary>
        public static SHA256 ShaInstance = SHA256.Create();        

        /// <summary>
        /// Joins two byte arrays to one single byte array by concating them
        /// </summary>
        /// <param name="b1">first byte array</param>
        /// <param name="b2">second byte array</param>
        /// <returns></returns>
        public static byte[] JoinArrays(byte[] b1, byte[] b2)
        {
            byte[] ba = new byte[b1.Length + b2.Length];
            Buffer.BlockCopy(b1, 0, ba, 0, b1.Length);
            Buffer.BlockCopy(b2, 0, ba, b1.Length, b2.Length);
            return ba;
        }

        
        /// <summary>
        /// XORs the elements of two arrays and returns the resulting array
        /// </summary>
        /// <param name="array1"></param>
        /// <param name="array2"></param>
        /// <returns></returns>
        public static byte[] XorArrays(byte[] b1, byte[] b2)
        {
            if (b1 == null)
                throw new ArgumentNullException("b1");
            if (b2 == null)
                throw new ArgumentNullException("b2");
            if (b1.Length == 0)
                throw new ArgumentOutOfRangeException("b1 can not be zero length.");
            if (b1.Length != b2.Length)
                throw new ArgumentOutOfRangeException("b1.Length != b2.Length");

            byte[] ba = new byte[b1.Length];
            for (int i = 0; i < b1.Length; i++)
                ba[i] = (byte)(b1[i] ^ b2[i]);
            return ba;
        }
        
        /// <summary>
        /// Checks if the elements of two arrays are equal
        /// </summary>
        public static bool Equals<T>(IList<T> a, IList<T> b) where T : IComparable<T>
        {
            if (a == null)
                throw new ArgumentNullException("a");
            if (b == null)
                throw new ArgumentNullException("b");
            bool retval = a.Count == b.Count;
            if (retval)
            {
                for (int i = 0; retval && i < a.Count; i++)
                    retval = a[i].CompareTo(b[i]) == 0;
            }
            return retval;
        }
    }
}

Written by esskar

November 3, 2009 at 9:41 am

… at your Service (Part I)

leave a comment »

Implementing a Service in C# is easy, straight forward and there a lot of examples out there that show you how to do it.
Myself, i wrote an abstract base class to fullfil my needs:

using System;
using System.ServiceProcess;

public abstract partial class WinService : ServiceBase
{
   public WinService() : this(null) { }
   
   public WinService(string name)
   {
      if (string.IsNullOrEmpty(name)) 
         name = this.GetType().Name;

      if (name.Length > ServiceBase.MaxNameLength)
         throw new ArgumentException("Length of name must not exceed " + ServiceBase.MaxNameLength, "name");

      this.ServiceName = name;
      this.CanStop = true;
      this.CanShutdown = true;
      this.CanPauseAndContinue = false;
      this.CanHandleSessionChangeEvent = false;
      this.CanHandlePowerEvent = false;
   }   
}

So, you implemented your Service,

public class TestService : WinService
{
   protected override void OnStart(string[] args)
   {
       // add your code here
   }    
}

installed it and it is now ready to run.

public partial class WinService
{
    public void Run()
    {
       ServiceBase.Run(this);
    }
}

TestService ts = new TestService();
ts.Run();

But how do you test it?
Running your application from the command line or from inside visual studio will popup a message box telling you that a Service has to be installed and be started with the Windows Service Administrative tool.

Working around this is simple. As every process is started by another process (cmd.exe is the process that starts any application when you call them from the command line, explorer.exe is usally involved when you start an application by double-click, …). So the idea is the check if your program is started by the Service Control Manager process (services.exe) or not and act the right way (Check my previous post about finding a process’ parent)

public partial class WinService
{
   public void Run()
   {
      this.Run(null);
   }

   public void Run(System.Windows.Forms.ApplicationContext appContext)
   {
      Process parent = Process.GetCurrentProcess().GetParentProcess();
      if (parent != null && parent.MainModule.ModuleName.Equals("services.exe", StringComparison.InvariantCultureIgnoreCase))
      {
         ServiceBase.Run(this);
      }
      else
      {
         this.OnStart(null);
         if (appContext != null)
            System.Windows.Forms.Application.Run(appContext);
      }
   }
}

Q.E.D.

Written by esskar

October 5, 2009 at 7:34 am

Process Extension: GetParentProcess

with one comment

Microsoft suggests to use the performance counter to find the parent process.
I find this quite slow and failed to work when running as service (i had to call it before calling ServiceBase.Run), so i use the native Win32 approach.

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace System.Diagnostics
{
    public static class ProcessExtension
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(SafeFileHandle hObject);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern SafeFileHandle CreateToolhelp32Snapshot(uint flags, uint processid);   

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool Process32Next(SafeFileHandle handle, ref ProcessEntry32 pe); 

        [StructLayout(LayoutKind.Sequential)]
        private struct ProcessEntry32
        {
            public int dwSize;
            public uint cntUsage;
            public int th32ProcessID;
            public IntPtr th32DefaultHeapID;
            public uint th32ModuleID;
            public uint cntThreads;
            public int th32ParentProcessID;
            public int pcPriClassBase;
            public uint dwFlags;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
            public string szExeFile;
        }; 

        public static Process GetParentProcess(this Process process)
        {
            Process retval = null;

            int pid = process.Id;

            SafeFileHandle snapShot = CreateToolhelp32Snapshot(0x2, 0);
            try
            {
                ProcessEntry32 pe32 = new ProcessEntry32();
                pe32.dwSize = 296; // Marshal.SizeOf(pe32);
                while (Process32Next(snapShot, ref pe32))
                {
                    if (pid == pe32.th32ProcessID)
                    {
                        retval = Process.GetProcessById(pe32.th32ParentProcessID);
                        break;
                    }
                }
            }
            finally { CloseHandle(snapShot); }

            return retval;
        }
    }
}

so I’m simply able to call

Process parentProcess = Process.GetCurrentProcess().GetParentProcess();

Written by esskar

October 5, 2009 at 6:55 am

InvokeRequired

leave a comment »

Everybody who is developing forms application in .net must be sick of the

if(this.InvokeRequired) { this.Invoke(...); } else { ... } 
pattern. At least I am. So i looked for a pretty solution, and I found one: Avoiding InvokeRequired

Written by esskar

September 4, 2009 at 9:38 am

Posted in .NET programming

Follow

Get every new post delivered to your Inbox.