Wednesday, August 02, 2006

Hello!

I am still working on a big web application in work. I will glad to tell you about the application, but this is for other conversation. I am glad to say that we are close to the end of the project and doing now last fine tuning on it.

The thing that I had to deal with for the last days is all the issue with publishing application errors in orderly fashion to the event viewer. The reason of doing it is to get the ability of tracking in runtime, bugs, errors or exceptions that can be appear while the application is in production. In this case we don't have the CLR debugger to find what was wrong (if something happend of course...), so we must publish the exception to the system's event viewer or just  to a simple Log file (which less recommended then publishing to the system's event viewer).

Now, to the implementation (the imporatnt thing!!!)

In order to publish error to the event viewer, we need to use the Microsoft.ApplicationBlocks.ExceptionManagement assembly of Microsoft. This assembly expose us all the publishing tools that we will need to publish an errors (and more...).

In my web application, in global.asax file, in Application_Error method, I wanted to publish the exception to the event viewer. It is very important to do it there, because in every application error, like runtime errors, exceptions and actions that the application and systme doesn't know to deal with, this method is being called (by the application of course).

Now, before publishing the error to the event viewer, you need to distinguish between the different exceptions. Do it with your own information about every exception that is happening but, it is important to know that also in every response's redirect (Response.Redirect (" ... ", true) or server's transfer (Server.Transfer (" ... ", true) an ThreadAbortException is being raised.

Exception lastError = Server.GetLastError();

if (Server.GetLastError() is ThreadAbortException || lastError.InnerException is ThreadAbortException)
{
   // Eat the exception - caused by Response.Redirect(..., true) or Server.Transfer(..., true).
   Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(lastError.GetBaseException());
   Server.ClearError();
}
else
{
   Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(lastError.GetBaseException());
   Server.ClearError();
   Server.Transfer("~/Error.aspx", false);
}

By this example you can see the publish exceptions handling.

Now, do not forget to declare in the web.config file the appliation name and the exceptions pulishing handling:

<exceptionManagement mode="on">
        <publisher assembly="Microsoft.ApplicationBlocks.ExceptionManagement" type="Microsoft.ApplicationBlocks.ExceptionManagement.DefaultPublisher" applicationname="APPLICATION_NAME"/>
</exceptionManagement>

One more thing... you need to register this assembly with the appliation name in the registry in purpose to let the application all the rights to publish the error in the event viewer, if you won't do it, the system won't let you write to the event viewer and you will get the exception: The event source ExceptionManagerInternalException does not exist and cannot be created with the current permissions. security exception and you will spend planty of time trying to solve it :) (like me...)

How to register this to the registry you ask?

Open notepad and write there this code:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application\APPLICATION_NAME]
"EventMessageFile"="C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll"

Save this file with .reg extension and double click on it, this will register this to the system's registry.

So, bye for now...

Posted by: Eran Nachum (c)
Post Date: 8/2/2006 7:47:28 AM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [2] | Trackback   #
 Sunday, July 23, 2006

Hello and good week to all!

These days I am starting to publish here (in my blog ofcourse) a series of articles that discusses with Web Serivces and the most important issue - Security over Web Services (using Microsoft technology ofcourse), because it is quite simple to write a web service that receives/retrieves data and 'do you thing...', but the complexity comes when you want to secure this data that runs over non-secured protocols or web-lines.

This article assumes that you are familier with web services, its porpuse and its implementation and assimilations, if not, you should read some basic tutorials before you start to read this article. (You can fine general example here).

Introduction
WS-SecurityProtocol defines all web services expansion security topics. Its goal is to let you build and use SOAP messages exchange in secured way. This term is quite flexble and it designed in a specific way in order to constitute the base of building a secured Web Service by the different security models like: SSL, Kerberos, PKI.
WS-SecurityProtocol supplies a full support for large number of security tokens, trusted domains, signature formats and encryption technologies.

This component supplies 3 basic mechanisms: Message Confindentiality, Message Integrity, Security Token Propagation. These mechanisms, each one by it own, doesn't supplies perfect security solution, therefore in actual fact, WS-SecurityProtocol builds a block that uses a combination of all there mechanisms and different enhancements to supply a perfect sucurity solution

Main Facts
Before I start explaining and showing the protocol's structure, I want to stand on the basic definitions and terms this protocol is uses:

  • Claim - the client's claim (like: name, identity, key, group, rights and more...)
  • Security Token - represent a set of tokens.
  • Signed Security Token - this is a claimed and encrypted by a specific authority (like: Kerberos ticket or X.509 certificate) security token.
  • Proof-of-possession - information that used by a specific "proof process" in purpose to describe the sender data.
  • Integrity - a process that comes to note that the sent data hasn't changed while sending the message.
  • Confidentiality - a process that comes to ensure that the data is protected and just specific authorized 'players' are allowed to watch it.
  • Digest - an encrypted sum of the data sent stream.
  • Signature - this is an encrypted communication between the Proof-of-possession and the digest. This action creates a symetric key and public signatures.
  • Attachment - this is the physical data that is transfered using the SOAP messages, but is not a part of the SOAP envelop.

We want to ensure that the SOAP message is encrypted properly to avoid dangers, like:

  1. The message could be readen and be changed by malicious user.
  2. Malicious user can send fake message through the Web Service and by that to get secret information.

Message Security Model

The WS-SecurityProtocol works under the Message Security Model, that comes to prevent such cases like mentioned above. Its behavior is:

The Security Token declares on Claims and Signatures, this mechanism supplies a proof to the knowledge of the sender (in simple words, the data that the sender holds). In addition, the Signature can bind itself with the Claims in the Security Token (in assumption the token is secured).

Claim can be supported (or not) by "secured authority", which is a set of claims, which encrypted or digitally signed by this authority is usually represented by Signed Security Tokens. An example to Signed Security Token set is X.509 Certificate - which by this set of claims, the binding is executed between the client identity and the the public key.
Claim that is not supported by any "secured authority", can be secured only when the connection (binding) between the sender and the receiver is secured (secured line, like SSL etc...), for an example, they can agree on a specific message name that is accepted by both of them and by that only they will know that the message is meant for them (because they are both will look forward to get the same name).

Another type of non-secured claim (which is not supported by any "secured authority") called proof-of-possesion. As I descibed earlier, this term confirms that the user has "pieces" of knowledge that diagnosed by the other 'players' which related to it. For an example, lets take a look of username/password security token, the proof-of-possession here, combines another security token in order to confirm the sender's claim. I need to note here, that Digital integrity (see above if you already forgot) for a message can be used as a proof-of-possession, but in theis case it will not considered as a security token.

Message Protection

Another model that comes to prevent such cases as mentioned above (remember...?).
This model claims that all the messages that are being sent, supposed to be encrypted in order to not be negatively affected by hostile factors. The Integrity based message is supplied by leverage of an XML signature with security tokens, in order to notice that the messages has been sent with no data changes of bad influences. This mechanism supports many signatures and players.

A confidentiality (see above for a definition), based message, uses XML encryption with secutity tokens to ensure that the message's parts will be confidential.

In order to supply the the maximum security to the SOAP message, that we'll want to send, there is a need to build the XML file that includes all the filters and headers definitions.
The structure of the XML file includes the <Security> tag, which symbolizes the security definitions. Under this tag it is possible to define all the information about the message security issue.

An XML file cannot hold more that one security tag, this in purpose to allow that each tag (security XML) will taget to other destination. This tag and all its data under, represents the signature steps and the encryption type that the sender used with to send the message.

A typical WS-SecurityProtocol example:

Line 001 and 002, describes the SOAP envelope. Line 003 opens the headers definitions that describes the message. Line 004 to 008, describes the sending message type, the source and destination.

Line 009, open the Security's filters definitions. This label defines the security definitions that the receiver need to be up to (in order to watch the message ofcourse). This header label is closed in line 029.

Lines 010 to 012, describes the security token that message uses, here the usage is username token. (Here the assumption is that the password is well known by the service, and by that, only username is being sent).

Lines 013 to 028 defines the digital signature. By this example, the signature is based on the key that generated from the sender password. Lines 014 to 021, explains the digital signature. Line 015 defines how to normilize the sent information.

Lines 017 to 020, chooses the elements we want to signature. In this example (by line 017), we can see that the body is digitally signed (<s:Body> label, which you can see in line 031).

Line 022, holds tha signature value that derivated from the encrypted information. Lines 023 to 027, holds an information about the security token location, which combined with the signature. In more explicit, lines 024 - 025, defines that this token is located in a specific URL address.

Line 031 to 033 holds the message body.

That it for now. More tutorials at:

Comments will be appriciated...

Posted by: Eran Nachum (c)
Post Date: 7/23/2006 7:44:39 AM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [0] | Trackback   #
 Tuesday, July 18, 2006

Many articles and approaches claims that it doesn't matter what is the application security level, or what is the security level of the environment the application is stored in (like working under SSL using https protocol etc...), you should always save all passwords and secret data encrypted. That because there is always a chance, even little one, that someone could steal your confidential data.

There are many hashing functions and alogorithms, several are MD5, SHA1 and more... but, these algorithms are too old (compare to our modern days), there generates 'only' a 128 bits value, so the space of posible resulting values is 2128 in size, which by creating a crack script, like the passcracking project the hash could be broken.

Because of these limitaions and cracking possibilities it is not recommended to use this type of hasing functions. Better solution you wiil see later... (hold on :) ).

One way Hash Functions

The following definitions are taken from the Bruce Schneier's Book: Applied Cryptography Second Edition:

A one-way hash function, H(M), operates on an arbitrary-length pre-image message, M. It returns a fixed-length hash value, h.

h = H(M), where h is of length m

Many functions can take an arbitrary-length input and return an output of fixed length, but one-way hash functions have additional characteristics that make them one-way [1065]:

Given M, it is easy to compute h.
Given h, it is hard to compute M such that H(M)= h.
Given M, it is hard to find another message, M’, such that H(M) = H(M’).

In some applications, one-wayness is insufficient; we need an additional requirement called collision-resistance.

It is hard to find two random messages, M and M’, such that H(M) = H(M’).

Now, by getting the main idea of the basic hashing algorithm by the Bruce Schneier's Book definitions, I want to show you better alternatives that comes to replace and enrich the old ones.

WHIRPOOL generates a 512 bits output, RIPEMD, uses 160, 128 or 320 bits output, but I want to focus in the SHA-2, function that generates 256, 512 bits ouputs, because there is available API in Microsoft.NET framework.

The main classes that implements this cryptografic algorithms are:

  • System.Security.Cryptography.SHA256Managed
  • System.Security.Cryptography.SHA384Managed
  • System.Security.Cryptography.SHA512Managed

Now to the implementations. The following code below shows you an example how to use this function in porpuse to encrypt a password or just confidential data that you want to store hashed:

byte[] data, encryptedBytes;
string hashedPassword = string.Empty;

data = Encoding.Default.GetBytes(plainPassword);
System.Security.Cryptography.SHA256 sha2 = new System.Security.Cryptography.SHA256Managed();
encryptedBytes = sha2.TransformFinalBlock(data, 0, data.Length);
foreach (byte b in sha2.Hash)
   hashedPassword += Convert.ToString(b, 16).ToUpper().PadLeft(2, '0');

sha2.Clear();
// hashedPassword holds the hashed string

This example above encript the plain pasword using SHA-2 algorithm.

The following example uses a salt which comes to help reduce the risk of dictionary attacks, the code appends random bytes (so-called "salt") to the original plain text before generating hashes. Please keep in mind that salt can only help against prebuilt dictionaries. If an intruder gets access to your system and uses a brute force attack, salt will not provide much value.

string hashedPassword = string.Empty;
//generate a random salt value by using the following code
byte[] salt = new byte[32];
System.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);
byte[] salt = Encoding.Default.GetBytes(userName);

//Convert the plain string password into bytes
byte[] plainPasswordBytes = System.Text.UnicodeEncoding.Unicode.GetBytes(plainPassword);
// Append salt to password before hashing
byte[] combinedBytes = new byte[plainPasswordBytes.Length + salt.Length];
System.Buffer.BlockCopy(plainPasswordBytes, 0, combinedBytes, 0, plainPasswordBytes.Length);
System.Buffer.BlockCopy(salt, 0, combinedBytes, plainPasswordBytes.Length, salt.Length);

//Create hash for the password + salt
System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);

//Append the salt to the hash
byte[] hashPlusSalt = new byte[hash.Length + salt.Length];
System.Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length);
System.Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length);

foreach (byte b in hashPlusSalt)
   hashedPassword += Convert.ToString(b, 16).ToUpper().PadLeft(2, '0');

// hashedPassword holds the hashed string

That's it, now use it properly and try to avoid as much as you can from brut attacking...

Posted by: Eran Nachum (c)
Post Date: 7/18/2006 9:23:57 AM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [2] | Trackback   #
 Sunday, July 16, 2006

Hey all, how are you?

I bumped on very strange and awkward thing while working on Visual Studio 2005, you can see the pic attached:

Are you familier with this??? :)

p.s
This thing vanished just after I restart my Visual Studio, funny!

Posted by: Eran Nachum (c)
Post Date: 7/16/2006 5:14:59 PM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [0] | Trackback   #
 Tuesday, July 11, 2006

Didn't I tell you that I love .Net 2.0? If I didn't I am saying it now...

This is new a method in .NET 2.0, but who plays with it should know it by now. Instead of working hard trying to sort a collection (or a list which is a descendant of it) of some entities, now you have the Sort method, which does it for FREE and in better performence.
Any case I decided to show a simple example to whom that doesn't know it or just want to be impressed again from it.

* Comment: I assumes in this post that you are familier with Generics and delegates.

Let's assume that you have an entity structured like:

public struct Entity
{
   private int _id;
   private string _name;

   // and more...

   public int Id
   {
      get{return _id;}
      set{_id = value;}
   }
   public string Name
   {
      get{return _name;}
      set{_name = value;}
   }
}

Now, suppose you have a list of these entities and you want to sort it by their name and display it sorted. Follow the example code below and see how it easy using anonymous delegate:

//sortDirecion is a global variable that determines the sort direction
int sortParam = sortDirection == "Ascending" ? 1 : -1;

entitiesList.Sort(new Comparison<Entity>(
   delegate(Entity e1, Entity e2)
   {
      return sortParam * e1.Name.CompareTo(e2.Name);
   })
};

Nice & easy that's it (with no sofisticated actions).

Some more tutorials about anonymous delegates (or delegates in general) you can find in Oren Elenbogen's (a team leader in my department) blog here.

So, be well.
p.s. Again... I will be glad to head some comment or sharpening.

Posted by: Eran Nachum (c)
Post Date: 7/11/2006 9:19:32 AM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [5] | Trackback   #
 Saturday, July 08, 2006

Hello all!

I know that I didn't write for a long time, this is because I am very busy these days. In work, we are at the end of a big web application project, and the stress is start to overflow. At home, I am also working on my own project (Haverut.co.il, if you forgot or didn't know), but this Saturday, I decided to share a problem that I had encountered it while working at home with Typed Datasets to connect and retrieve data from the database.

I am developing my website project under Visual Studio 2005 and SQL Server 2000 (this is because my web-hosting server is supports only SQL Server 2000). When I had installed VS. 2005, SQL Server Express 2005 had automaticlly been installed, this situation created 2 versions of SQL server databases.

Now to the BUG...
When I had tried to debug a flow that connect to the DB and grab some data from it, the application had been crashed on run time error and the exception sayed: "Unable to connect to debugger on 'COMPUTERNAME' (Error = 0x80070057). Ensure that client-side components, such as SQLLE.DLL, are installed and registered on 'COMPUTERNAME'. Debugging disabled for connection 51."
Very annoying bug, firstly because I didn't encountered it before and basicly because there is no troubleshooting tips at Microsoft help & support (you can see it yourself here).

Microsoft are saying that because the 2 different versions of SQL Sever on the computer, the T-SQL debugger uses the SQL startup account of the default instance (which is SQL 2005 Express edition) and it doesn't appropriate the SQL Server that I am working with (which is SQL 2000).
After long seeking for a resolve in the web I didn't find anything, so firstly I uninstalled SQL Server 2005 Express from the computer - it didn't helped much, and after long combinations and attempts I decided to install again SQL Server 2000 SP 3... I returned to the application, debuged the specific flow and a MIRACLE - it worked...

Now I can continue working on my Haverut.co.il web site (evetually...). So, if you have any questions about it or some comments I will glad to hear.

Now I am going to enjoy my Shabbat vacation in a trek in Zavitan water fall with my wife and good friends, be well...

Posted by: Eran Nachum (c)
Post Date: 7/8/2006 11:34:22 AM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [1] | Trackback   #
 Thursday, June 29, 2006

Hello!

Long time no posted new post to the blog regarding the hard work on Tigers project at work, but while programming and programming, I encoutered with new asp.net 2.0 Page property that called Previous Page.
This property holds all the web controls with its data and infromation of the previous page of the current page that you are in.

I found this property very useful and it can do you 'Easy Life' while getting data from the previous page that you came from (or the user that uses your application).

For example: suppose you want to use specific information from the page that you are just have been redirected from, like search term text. In the 'old fasioned' way, you needed to save this data in the Session variable or to send it by the query string of the url address and it will be expose to everyone, but PreviousPage property comes to avoid this ways by saving all the previous page data by looking for the specific control that holds the data, For example:

if (Page.PreviousPage != null)
{
   if (Page.PreviousPage.FindControl("txtSearchTerm") != null)
   {
      string term = ((TextBox)Page.PreviousPage.FindControl("txtSearchTerm")).Text;

      //do your thing with this data...
   }
}

Here I checked if there is a previous page and if it contains the txtSearchTerm Textbox controls, grab its data and use it.

Is it nice or not?

Posted by: Eran Nachum (c)
Post Date: 6/29/2006 7:38:26 PM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [2] | Trackback   #
 Tuesday, June 20, 2006

This post refers to all of you that holds a personal site or administrates sites and wants to know some analytics and statitctics about site fraffic.

Google (the amazing...) came out with very sophisticated site analytics tool that can tell you "everything you want to know about how your visitors found you and how they interact with your site. You'll be able to focus your marketing resources on campaigns and initiatives, and improve your site to convert more visitors" (Google's qoute).

I had very impressed, initially, of the user's interface graphic design and the diverse statistic summaries, and the most valuable thing here is that, this is very easy to implement - you need to add small script to your site and that's it!!!

For more info you can try it here. I already inserted the script code on my differents sites.

Bye for now...

Posted by: Eran Nachum (c)
Post Date: 6/20/2006 7:51:25 AM (Jerusalem Standard Time, UTC+02:00)
Disclaimer | Comments [2] | Trackback   #