Signing with Certificates

Recently, I recorded a Spanish video about how to encrypt/sign information using certificates and I thought it would be nice to write also a post about it. The thing is that when I tried to post it I received an alert about having a post with the same title, I already wrote the post Encrypting with Certificates more than two years ago :(, so while I try to figure out why I have this memory leak in my brain I will write only the missed part: how sign data using X509 certificates.

Since we already have in the previous post the code to load certificates we will focus on two methods Sign and VerifyHash.

   1:  public static byte[] Sign(byte[] hash, 
   2:      X509Certificate2 certificate)
   3:  {
   4:      if (hash == null)
   5:      {
   6:          throw new ArgumentNullException("hash");
   7:      }
   8:      if (certificate == null)
   9:      {
  10:          throw new ArgumentNullException("certificate");
  11:      }
  12:   
  13:      using (RSACryptoServiceProvider provider = 
  14:          new RSACryptoServiceProvider())
  15:      { 
  16:          provider.FromXmlString(
  17:              certificate.PrivateKey.ToXmlString(true));
  18:          return provider.SignHash(
  19:              hash,
  20:              CryptoConfig.MapNameToOID("SHA1"));
  21:      }  
  22:  }
  23:   
  24:  public static bool VerifyHash(byte[] hash, byte[] signature, 
  25:      X509Certificate2 certificate)
  26:  {
  27:      if (hash == null)
  28:      {
  29:          throw new ArgumentNullException("hash");
  30:      }
  31:      if (signature == null)
  32:      {
  33:          throw new ArgumentNullException("signature");
  34:      }
  35:      if (certificate == null)
  36:      {
  37:          throw new ArgumentNullException("certificate");
  38:      }
  39:   
  40:      using (RSACryptoServiceProvider provider = 
  41:          new RSACryptoServiceProvider())
  42:      {
  43:          provider.FromXmlString(
  44:              certificate.PublicKey.Key.ToXmlString(false));
  45:          return provider.VerifyHash(
  46:              hash, 
  47:              CryptoConfig.MapNameToOID("SHA1"), 
  48:              signature);
  49:      }
  50:  }

The idea behind these two methods is the next:

We have one party A who needs to send a message to B. B wants to be sure that the messaged received has not been modified by a third party C. To do that, A will create a digital signature that will be sent together with the message. To generate the signature A needs to compute a hash of the message, this hash is then used with method "Sign". Once A has the signature he can transmit the message and the signature to B.

When B receives the message and the signature, B needs to verify the hash. So, B computes again a hash of the received message and uses the method VerifyHash, which will return true if the message has not been modified. The next code shows you an example on how to call both methods.

   1:  static void Main(string[] args)
   2:  {
   3:      string certificateName = "Test";
   4:   
   5:      X509Certificate2 cert = LoadCertificate(
   6:          StoreName.My, 
   7:          StoreLocation.LocalMachine, 
   8:          certificateName);  
   9:      
  10:      byte[] messageSent = 
  11:          UTF8Encoding.UTF8.GetBytes("Message sent from A to B");
  12:   
  13:      // A generates the signature before send to B
  14:      SHA1Managed sha1 = new SHA1Managed();
  15:      byte[] hashA = sha1.ComputeHash(messageSent);
  16:      byte[] signature = Sign(hashA, cert);
  17:   
  18:      // B receives the message and the digital signature
  19:      byte[] messageReceived = 
  20:          UTF8Encoding.UTF8.GetBytes("Message sent from A to B");
  21:      //byte[] messageReceived = 
  22:      //  UTF8Encoding.UTF8.GetBytes("Message hacked by C");
  23:   
  24:      byte[] hashB = sha1.ComputeHash(messageReceived);
  25:   
  26:      if (VerifyHash(hashB, signature, cert))
  27:      {
  28:          Console.WriteLine("Verified");
  29:      }
  30:      else
  31:      {
  32:          Console.WriteLine("Not verified");
  33:      }
  34:   
  35:      Console.ReadKey();
  36:  }

This piece of code using the rest of methods mentioned shows you how we can verify a message has not been altered during the transmission. If you comment lines 19,20 and uncomment 21,22 you will see that after message has been altered the hash cannot be validated anymore. These short methods are one the basis of security when we try to guarantee information is not being altered from origin to destine. We have used a very basic message, but imagine you have an online shop and you don´t want people can alter from the message the number of items that will be delivered after you have authorized a payment.

Checking similar methods like SignData and VerifyData will be left as an exercise for the reader.

Singleton Pattern

Yesterday I was viewing a video (Spanish) that explains about how to implement the Singleton pattern in .NET. After some implementations the video ends up showing the best way to have a thread safe implementation of the singleton pattern.

The problem is the video ends saying that the next two implementations are exactly the same on a functional level, which is not completely true.

Implementation 1

   1:  public sealed class Singleton1
   2:  {
   3:      private DateTime creationTime;
   4:      private static Singleton1 instance = null;
   5:      private static object synchro = new object();
   6:   
   7:      private Singleton1()
   8:      {
   9:          creationTime = System.DateTime.Now;
  10:      }
  11:   
  12:      public static Singleton1 Instance
  13:      {
  14:          get
  15:          {
  16:              if (instance == null)
  17:              {
  18:                  lock (synchro)
  19:                  {
  20:                      if (instance == null)
  21:                      {
  22:                          instance = new Singleton1();
  23:                      }
  24:                  }
  25:              }
  26:   
  27:              return instance;
  28:          }
  29:      }
  30:   
  31:      public string CreationTime
  32:      {
  33:          get
  34:          {
  35:              return creationTime.ToString("hh:mm:ss.ffffff");
  36:          }
  37:      }
  38:  }

Implementation 2

   1:  public sealed class Singleton2
   2:  {
   3:      private DateTime creationTime;
   4:      private static Singleton2 instance = new Singleton2();
   5:      
   6:   
   7:      private Singleton2()
   8:      {
   9:          creationTime = System.DateTime.Now;
  10:      }
  11:   
  12:      public static Singleton2 Instance
  13:      {
  14:          get
  15:          {
  16:              return instance;
  17:          }
  18:      }
  19:   
  20:      public string CreationTime
  21:      {
  22:          get
  23:          {
  24:              return creationTime.ToString("hh:mm:ss.ffffff");
  25:          }
  26:      }
  27:  }

The second implementation is correct, since it shows how you can avoid the lock while creating the object instance of the Singleton class. The reason why this is thread safe is because .NET guarantees that the Type Constructor (or Type Initializer on the ECMA standard) is executed only once per AppDomain and is thread-safe.

Regardless both of them are thread-safe, the difference is that the first one is lazy loaded while the second one is eager loaded. In order to implement the singleton pattern using a lazy loaded version and still take profit of the Type Constructors, you need to add a container for the object instance of Singleton2. Doing this the Type Constructor will only be initialized when you access the property (or any other member making reference to it). Below you can see the correct implementation for it.

   1:  public sealed class LazyLoading
   2:  {
   3:      private DateTime creationTime;
   4:   
   5:      private LazyLoading()
   6:      {
   7:          creationTime = DateTime.Now;
   8:      }
   9:   
  10:      public static LazyLoading Instance
  11:      {
  12:          get
  13:          {
  14:              return SingletonContainer.instance;
  15:          }
  16:      }
  17:   
  18:      public string CreationTime
  19:      {
  20:          get
  21:          {
  22:              return creationTime.ToString("hh:mm:ss.ffffff");
  23:          }
  24:      }
  25:   
  26:      class SingletonContainer
  27:      {
  28:          internal static readonly LazyLoading instance = 
  29:              new LazyLoading();
  30:      }
  31:  }

User Group Support Services

I have recently started to volunteer as UGSS Regional Lead for EMEA.

For those who know UGSS and the RL, you will know that this is a position covered by Microsoft personnel, my case is a bit different because I agreed to volunteer during this FY to help out Sanjay Shetty who is the official responsible for EMEA and APAC.

If you do not know the UGSS I highly suggest you visit http://ugss.codezone.com, where you will be able to find more information about what UGSS does for the community.

As our manager Graham Jones already mentioned in this post, the role of a regional lead is to help user group leaders to be as successful as possible independently to which organization, if any, their user groups belong. So, if you have any question or suggestion we all will be extremely glad to help you.

In this short period as RL, I have had the possibility to be amazed for the huge amount of projects, initiatives my colleagues are involved.

I'm still landing but I'm pretty sure the community will be also amazed about the good things that are coming out of the work the UGSS does.

Docking as Windows 7 in Vista and XP using Windows Hooks

I was one of those lucky guys who got the Windows 7 virtual machine at the PDC for the first time and I already liked. When the new beta was released I decided to install it on my old laptop and I love it, I really mean it. I think it's great, there are a lot of small features that you immediately like with almost not noticing them. One of them is the cool docking feature that allows you drag a window over the limits of the screen to change it's size and position.

When I saw I immediately wondered how this could be done using C#. The idea would be to detect when a window is being dragged to the limits of our screen, when it reaches them display a frame and finally change the size and position of the window being dragged. 

At a first view, using some Windows Hook and capturing a couple of messages can do the trick. The problem is that we can only install global hooks for WH_KEYBOARD_LL and WH_MOUSE_LL, the other global hooks require a native DLL export to inject itself in another process. This is already a problem because discards the possibility to monitor messages before and after they are processed by a window,  in addition we cannot use either the MouseProc that gives us information about the mouse and more important the value of the HitTest, which is necessary to know what part of the window the user is clicking. What we will do is to try to use the WH_MOUSE_LL with some work around. I already wrote about hooks more than one year ago, you can read it here if you are not familiarized with them.

With that hook we will obtain information about mouse events, we will focus on the messages WM_LBUTTONDOWN, WM_MOUSEMOVE and WM_LBUTTONUP. In the attached code I created a hook helper that captures the hook callbacks and generates .NET events to facilitate its use. You can see below the event handler:

   1:  void hookHelper_HookMouseEvent(object sender,
   2:      HookMouseEventArgs e)
   3:  {
   4:      switch(e.Message)
   5:      {
   6:          case NativeConstants.WM_LBUTTONDOWN:
   7:              CheckWindow(e.Point);
   8:              break;
   9:    
  10:          case NativeConstants.WM_MOUSEMOVE:
  11:              CheckPosition(e.Point);
  12:              break;
  13:    
  14:          case NativeConstants.WM_LBUTTONUP:
  15:              ResizeWindow(e.Point);
  16:              break;
  17:      }
  18:  }

In the method CheckWindow we decide if we Window where the user has clicked is a window we are interested to monitor, to do it we retrieve the window handle using the API WindowFromPoint and doing a Hit test over the window. The Hit test can be done by sending the message WM_NCHITTEST specifying the handle of the window and the coordinates of the point, this will return us a value indicating what part of the window has been clicked, in our case we are interested only if the user clicks the Title of the window, which value is HTCAPTION.

   1:  private void CheckWindow(Point point)
   2:  {
   3:      Win32.NativeStructs.Point p =
   4:          new Win32.NativeStructs.Point();
   5:      p.x = point.X;
   6:      p.y = point.Y;
   7:    
   8:      windowHandle = NativeMethods.WindowFromPoint(p);
   9:      if (windowHandle != IntPtr.Zero)
  10:      {
  11:          IntPtr lParam = new IntPtr(65536 * p.y + p.x);
  12:          IntPtr hitTestPtr = NativeMethods.SendMessage(windowHandle,
  13:              (uint)NativeConstants.WM_NCHITTEST, (uint)0, lParam);
  14:          if ((int)hitTestPtr == NativeConstants.HTCAPTION)
  15:          {
  16:              dragging = true;
  17:          }
  18:      }
  19:  }

The messages, return values and functions are declared in the header Winuser.h, the easier to have all the information about the windows API is to go to MSDN, of course, but also to download the Windows SDK.

Next step is to give to the user the visual clue that something will happen with the window, to do it Windows 7 shows an animation below the pointer and a frame simulating where the window will be placed. To do it we will not code any fancy thing, we can simulate it by just opening a standard .NET form setting its properties ControlBox, ShowInTaskBar and TransparencyKey to our desired values. To know the size we need to give to our frame we just need to check the property WorkingArea from the .NET class System.Windows.Forms.SystemInformation. The only trick we will do is to display the form with the function SetWindowPos, because it allow us controlling the Z-Order of the window and to open the form without activate it, this is handy to avoid our fake frame is placed on top of the window we are actually moving. To do it we use the function SetWindowPos including the handle of the window to insert after and the parameter SWP_NOACTIVATE.

   1:  NativeMethods.SetWindowPos(frame.Handle,
   2:      windowHandle,
   3:      0, 0,
   4:      SystemInformation.WorkingArea.Width / 2,
   5:      SystemInformation.WorkingArea.Height,
   6:      NativeConstants.SWP_SHOWWINDOW |
   7:      NativeConstants.SWP_NOACTIVATE);

We are near to the end, we just need to complete the last step, change the size and position of the window to the desired the values using again the function SetWindowPos for the left and right placement. To maximize we just use the function ShowWindow passing as parameter SW_SHOWMAXIMIZED.

Windows 7 also restores the original size of the window after you drag away from the docked position, this could be done by capturing first the size and position of the window using the functions GetWindowPlacement and SetWindowPlacement, if you use them do not forget to set the length of your WindowPlacement structure using Marshal.SizeOf().

If you are not familiarized with P/Invoke in .NET you can make use of tools like PInvoke Interop Assistant from Microsoft CLR Interop Team or the P/Invoke wiki.

Now that all seems to be under control, if you download the code you will see that we have a big problem. When we release the button the size doesn't seem to change, but it actually changes to the size and position we have given.  The problem is that the window is in the moving state and when we release the button after set our size, it comes back to the last size the window had before releasing the mouse button. If we make use of Microsoft Spy++ we can see that after set the position the window still receives the messages like WM_WINDOWPOSCHANGED or WM_EXITSIZEMOVE.

I've tried with some of the messages captured previously using the function SendMessage to see if I could exit the moving/sizing state but without success. So, at the end I couldn't resolve it using C#, if you have ideas on how this can be solved they will be welcome. As I was joking with a friend a couple of days ago I feel I've lost my "mojo".

It is curious to see how our mind works, when I completely stopped thinking about what message send in order to make it work, I thought I could try the last trick by setting the size after the resize was completed. The way to do that is pretty simply, we just need to enable a timer that starts after we capture the WM_LBUTTONUP.

MadAboutNet.WindowsDocker.zip (404.63 kb)

Xml Documentation Comments - Exceptions II

People who has been working with me knows that I'm a big fan of FxCop (or Code Analysis), I think static code analysis tools are very useful and a must-have in any development team, since ensure developers follow the company's guidelines and  write correct code (at least it helps a lot). In addition, I see them also as a great ally to improve the learning curve of new developers.

While FxCop analyzes managed code assemblies checking for improvements  about design, localization, performance, security, interoperability, etc.  StyleCop focuses mainly in code style guidelines.

In the previous post Xml Documentation Comments - Exceptions I we saw how to document exceptions using the Xml Documentation features. Here we will see how to take profit of StyleCop SDK  to create a custom rule that validates we are documenting those exceptions.

To create our rule we just need to create a class library project, add references to the assemblies Microsoft.StyleCop.dll and Microsoft.StyleCop.CSharp.dll, create a class that inherits from SourceAnalyzer, add an attribute and embed an Xml file with the necessary Metatada for our rules. All these steps are entirely documented in the StyleCop SDK documentation, so I do not waste too much time explaining it.

Before we start we need to know that the StyleCop engine incorporates a custom C# language service that is used to create a rich model representing the original C# code. What our rule will do is to use that model to visit the different elements that can throw exceptions, analyze the element's body to find the throw statements and extract the type of that exceptions, it will extract the exceptions documented using the Xml comments, finally it will compare the thrown exceptions with the documented ones and will add a violation for all the discrepancies found.

We know that we can use throw statements inside methods (including constructors), indexers and properties. So, taking profit of the Visitor implementation that the API provide us we will visit all the CsElement of a CsDocument looking for the declared methods, indexers and properties. Below you can see the callback method we have passed to the WalkDocument method.

   1:  private bool VisitElements(
   2:      CsElement element, 
   3:      CsElement parentElement, 
   4:      List<string> usingDirectives)
   5:  {
   6:      if (this.Cancel)
   7:      {
   8:          return false;
   9:      }
  10:   
  11:      // We store the using directives for future use
  12:      if (element.ElementType == ElementType.UsingDirective)
  13:      {
  14:          usingDirectives.Add(
  15:              ((UsingDirective)element).NamespaceType);
  16:      }
  17:   
  18:      // There are severeal element types that can throw exceptions: 
  19:      // Methods, Constructors, Indexers and Properties
  20:      if (!element.Generated &&
  21:          (element.ElementType == ElementType.Method || 
  22:           element.ElementType == ElementType.Constructor ||
  23:           element.ElementType == ElementType.Indexer || 
  24:           element.ElementType == ElementType.Property))
  25:      {
  26:          this.CheckExceptionDocumentation(element, 
  27:              usingDirectives);
  28:      }
  29:   
  30:      return true;
  31:  }

Lines 17 to 24 allow us filtering the elements for which we are going to check the documentation. You can see also from line 10 to 13 that we store the using directives defined in the document, later on I will explain why.

The next is to analyze more in detail each element we have filtered, what we will do is first look for the exception tags added  in the Xml comments and then compare them with the type of the exceptions thrown in the given element. The first step is as easy as perform a Linq Xml query over a property called Header the CsElement has. For the second one we will create a CodeWalkerStatementVisitor that we will pass to the WalkElement method, this callback will be used to iterate the element's statements looking for all the the throw statements defined.

To do it we only need to check the StatementType property belogning to the class Statement and make sure its type is StatementType.Throw. Once we have the ThrowStatement we can investigate the type of the exception that will be thrown. The demo rule can analyze the next scenarios:

  1. New expressions. i.e. throw new System.Exception();
  2. Literal expressions. i.e. var ex = new Exception(); throw ex;
  3. Method invocation expressions. i.e. throw GetMyExceptionInstance();

The ThrowStatement class has a property called ThrownExpression that allow us identifying the expression used to throw the exception.

For the first scenario, we need to iterate the different tokens of the NewExpression and extract the exception type. This is done in the code using the next method.

   1:  private static string ExtractExceptionType(NewExpression expression)
   2:  {
   3:      for (Node<CsToken> node = expression.Tokens.First; node != null; 
   4:          node = node.Next)
   5:      {
   6:          CsToken token = node.Value;
   7:          if (token.CsTokenType == CsTokenType.Other)
   8:          {
   9:              return token.Text;
  10:          }
  11:      }
  12:   
  13:      return string.Empty;
  14:  }

For the second scenario we have a small handicap, the literal represents a variable that is not defined in the throw statement, instead it is defined in upper statements or even in elements different than the one where the exception is thrown i.e.

   1:  ArgumentNullException ex = new ArgumentNullException();
   2:  public void DoSomething(string value)
   3:  {
   4:      if (value == null)
   5:      {
   6:          throw new ex;
   7:      }
   8:  }

In the code above the element containing the throw statement is the method DoSomething, but the variable ex is defined in a class element.

For this reason before we can obtain the type of the exception, we first need to retrieve the variables defined by the parent statements of the throw statement. After that we just need to find the variable among the retrieved ones to determine its type and return it for further analysis.

The third scenario is the MethodInvocationExpression, here we have the biggest handicaps because there are many possibilities in which we can obtain an exception from a method. The easiest case is a direct method call, we will have MethodInvocationExpression containing the LiteralExpression with the name of the method, but imagine the next situation:

throw new MyClass().GetException();

In this case, the expression is a member access and we need to go to the right side to find the literal with the name of the method.

Once we have the obtained the name of the method, we can perform a search in the Document looking for that Method element in order to retrieve its return type that, of course, will be our exception type. We do not need to worry about overloads with different return types, because even if the CLR supports it C# does not and we are analyzing C# code.

At this point we have been able to retrieve all the exception types thrown by the throw statements and we can compare with the ones we have documented. Unfortunately we are not done yet and there is another point to solve.

The problem we have is that the object model representing the code we analyze, does not stores the type of the variables , return types of methods, etc. as the .NET type "Type". Instead they are represented in best case as a TokenType with a text representation. This has sense for many reasons, one is because StyleCop analyzes code that doesn't necessarily compiles therefore it's possible the type does not exists yet.

So, how this affects to the rule? Since we do not have the real types for the Exceptions we want to verify but string representations of them, the next code will cause a false positive:

   1:  /// <exception cref="System.Exception"></exception>
   2:  public void DoSomething()
   3:  {
   4:      throw new Exception();
   5:  }

The false positive appears because at the time we compare the type throw with the type documented we will compare "System.Exception" with "Exception". That's the reason why we have stored the using directives in a previous step, because before to compare we will try to obtain the full type name doing a Type.GetType() concatenating the different namespaces imported into the document. In case, that we are still not able to get the type (i.e. exception defined in a different assembly not accessible from StyleCop) we will compare both texts without the namespace, this is using Exception instead of System.Exception.

I'm really curious to see if StyleCop will be benefited when the new managed C# compiler is there, part of the project to offer the C# compiler as a service will include a complete language object model. I suppose it will be a natural step to use that new model, but this is way far from today since, regardless the C# team is already working on it, it is supposed to come after C# 4.0.

With this rule we are covering the most common scenarios where exceptions are thrown, but there are cases that will fail. i.e. If the exception thrown is obtained from a method declared in a different document, the rule will not be able to find that method and consequently the type of the exception.

StyleCopRule.zip (21.66 kb)