Mar242009

Still Arrays?

     I am a moderator in one of the Turkish forums: ceviz.net. Although I can’t as much time as before, I am still checking the forum to see what difficulties people are facing. I can’t still believe that people are still using arrays in C#, and not surprisingly most of their problems are related with arrays too. I can’t think of 1 reason to use arrays (unless you are targeting clr 1.1 or some old function that requires array). They are not type safe, they are not dynamic, you have to reallocate space when it is full etc.

    I really want to know why not List<T> but still arrays? Is it the syntax that is scary? For example one of the members asked a question in the forum complaining about his application being crashed every time he runs his program. Here is his application:

   1:  string[] myArray = {"a","b","c"};
   2:  string[] wanted={};
   3:  Random rnd  = new Random();
   4:  int index = rnd.Next(0,3);
   5:  wanted[0] = myArray[index];

The problem with this small function is obvious, the programmer is assigning a value at line 5 to an array location that never been allocated. This type of bugs usually happen when you use array, and if you are really really lucky (or unit test your code and get a good code coverage), you will catch the bug quickly. As an answer to this question, i adviced him to use either new to allocated space, or use List which is a much better way. Here is the version with List<T>

   1:  List<string> myArray = new List<string>{"a","b","c"};
   2:  List<string>wanted = new List<string>();
   3:  Random rnd = new Random();
   4:  int index = rnd.Next(0,3);
   5:  wanted.Add(myArray[index]);

It is this simple but I am sure that in a few days, I will see another question in the forum complaining about a program crash smile_sad


Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Mar222009

ASP.NET MVC and CSRF

I was at the MIX’09 this year thanks to Lynn Langit. There were so many interesting sessions however I was more interested in the MVC ones. I attended both Scott Hanselman’s blog an Phil Haack’s sessions. They were great, one of the nice thing was CSRF protection in asp.net mvc framework.

What is CSRF? CSRF (Cross site request forgery) is an attack that tricks the victim into loading a page that contains a malicious request. CSRF is a confused deputy type of attack. It basically means, if Bob wants to kill Alice, he doesn't have to do it himself, if he can convince Sheriff that Alice is a bad person, the deputy will be confused and do the job for Bob. 
The attacker hopes that you will be logged into your account (any account that he will be targeting),  then tries to trick your browser to do a post or if the website isn't programmed good a get request on your behalf. This attack is usually combined with XSS (cross site scripting) attacks. A very simple example of this would be this:

<img src="http://stocks.com/buy.aspx?sym=MSFT&shares=500">

Over here the attacker assumes a couple of things:

  1. The victim has an account with stocks.com
  2. The victim is logged into his account, or selected the remember me section in the login page
  3. stocks.com is bad designed that a get request is good enough to buy shares
  4. The victim will somehow see visit our page to activate this link

Number 4 is easy, as all we need is either start sending spam emails saying that if you send this to 10000 people Microsoft will be donating some big bucks to a cancer sick kid, or go to a forum(s) that has XSS vulnerability, and create an account with the signature above, and start posting messages so whoever loads the message will be calling the image source. Number 1 is not a bad assumption either, if we send our message to enough people, even if 0.1% of people has a stocks.com account, that would be enough. Number 3 is… just think how many of you as programmers check post vs. get.

Do you think nobody will make these mistakes? Do you know about Sammy attack? One guy attacked myspace with CSRF and in less than 24 hours he had millions of friends.

What are the typical defense techniques against CSRF attacks?

  1. Check referrer: This is not always possible as some companies (AOL) changes the referrer in the http header.
  2. CAPTCHA: using those weird written characters on the page and asking the user to type in what they see, may be a solution but it is not accessible (and if you are building a site for government your site must be accessible)
  3. Password reauthentication: Before critical operations such as buy this stocks, complete transaction etc, ask the user to enter his password again.
  4. Dont use GET: For critical operations such as buy stocks, complete transactions etc, don't accept get request, but require post requests. This will not solve the problem, but will help with the solution.
  5. ViewStateUserKey: this is one the hidden gems in asp.net web forms i guess as only a few of the developers know about this. This is a property of the page class, and it assigns a unique identifier to each user and keeps it in the viewstate. You can only set this value at the Page_Init event, Page_Load is too late, and will throw an exception. Basically you can just assign the session id to this variable at page_init, and nature of asp.net web forms will check the viewstate , and if it is been modified throws and error.  This works only on post actions

How about ASP.NET MVC?
If you watch Phil Haack’s MIX’09 session, he explained the defense technique in details. Basically ASP.NET MVC has an anti-forgery helper. The algorithm works like this: Put a value in the cookie, trusted modern browsers don't let cross domain cookie shares, put the same value in the form as a hidden value, in the postback compare these 2 values. Let’s say your action method is CompleteCheckout(), and you want to protect this function from CSRF attacks. First thing you do is to apply filter attribute: ValidateAntiForgeryToken, so your action method would be like:

   1:  [AcceptVerbs(HttpVerbs.Post)]
   2:  [ValidateAntiForgeryToken]
   3:  public ActionResult CompleteCheckout()
   4:  {
   5:     billing.ChargeCreditCard(shoppingCart);
   6:     shipping.ShipToClient(shoppingCart);
   7:     return View();
   8:  }

This filter basically means, check the value in the cookie, and compare it with the value from form value. As a second step we have to put the value in the form field, there is an helper method for this, and the syntax is simple:

<%=Html.AntiForgeryToken()%>

 

When you call this helper function from your view page, it generates a hidden type with the name “__RequestVerificationToken” which is a base64 encoded value. And that’s it :) Now if the values do not match, the framework will throw an exception and the attacker couldnt confure the deputy :)

Thanks to Phil’s team to make this so easy.



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Mar122009

Timewarner & Hackers!!

Timewarner cable internet service sucks in Redlands area.  Connection is dropping every other day, very very slow connection maybe even slower than a dialup, help desk not answering phone calls etc. They are very luck that they are monopoly in my area. Interestingly every time I call timewarner (of course after waiting about 50 minutes on the phone listening a message a rep will be with me shortly), they tell me it is the modem problem i have at home. However all my friends who has unfortunately timewarner cable internet at their home has the same problem. If all my friends in Redlands area are not using my modem at home, i guess it is Timewarner stupid, unreliable service in our area.

More interestingly i get a call from them once a month, offering a phone service over internet, i always give the same expression to them, “Is this a joke?”, and tell them how bad their service is… Guess what they credit my account for the days i cant connect, however i am ok to pay to a service that actually works :), and now Timewarner is proud to give me a service that doesnt work :)

Anyways to cut the long story, short, after many calls, they send me the email below, and basically they are saying hackers are attacking Timewarner to cut their internet service. It is the most stupid excuse that can come from a company as there is nobody to dispute it . Here is the email from Timewarner.
=========================================================

Thank you for your inquiry.
During the past week, hackers have launched a series of attacks on Time
Warner Cable's servers.  Time Warner Cable is working with law
enforcement agencies to resolve these crimes.
As a result of these attacks, you may have experienced a temporary
"outage" when attempting to surf the Web, including an intermittent
"page cannot be displayed" error message. The outages did not result in
services being 100% unavailable, and were limited to sporadic timeouts
which appeared to be random events.  Some users may have experienced a
total disconnect, however. These types of attacks are not uncommon,
especially for a network as large as ours. We suspect that the attackers
are using "zombie computers," or hijacking unsuspecting subscribers'
machines to perpetrate the attack without its owner's knowledge.
All of us at TWC take these attacks extremely seriously. As previously
mentioned, we are working with the appropriate law enforcement agencies
that specialize in investigating these types of crimes. We will pursue
prosecution of all perpetrators to the fullest extent of the law. We
apologize for the inconvenience that these attacks may have caused and
encourage you to report any suspicious activity. Instructions for
reporting security abuse are located at http://help.rr.com.
If you have any further questions, please do not hesitate to contact us
at the number listed below. Our telephone representatives are available
24 hours a day, 7 days a week. Have a nice day!
Time Warner Cable
(888)TW-CABLE
(888)892-2253



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Mar112009

Multiview and Validators

One of my colleague had a problem today which was an interesting one I guess. In his project, he had a multview control, and 4 views. Except the last view, each of these views had some validations. Interestingly all the validators, except the custom validation controls were working. I googled some stuff, and came up with a weird solution :).
When the user clicks the next button, in the code my friend was calling Page.Validate() and right after that Page.IsValid, however, when this button onclick is triggered, the views aren't activated yet so, the view is always valid :).

My weird fix was activate view on the button onclick, call vaidatations such as :

viewMany.ActiveViewIndex = 1;
Page.Validate();
if(!IsValid)
   return;
viewMany.ActiveViewIndex = 2;

 

any other suggestions?



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Mar082009

Vista Clipboard Locked?

I was working on a project that required me copying and pasting lots of text from a word document to Visual Studio. After sometime,  i couldn't copy paste anything. When i hit Control C at Word, i wasn't getting any error, however i couldn't paste the text too. I tried copy paste from notepad to notepad too, but wasn't working still. I copied clipboard.exe from my XP virtual pc, to Vista machine to see the clipboard content (Unfortunately Vista doesn't have clipboard.exe). I ran the clipboard.exe, and clipboard application went into a infinite loop, and i had to kill it from task manager. I was googleing lot’s of clipboard issues with Vista, however most of the solutions didn’t solve my problem. I decided to backtrack. I rebooted the machine, and noted down every step to find out what causes clipboard lock. Every time i run a virtual pc, with a shared folder to host Vista machine, the clipboard gets locked. I guess virtual pc, locks the clipboard when you share a folder, and don't release it, until you stop the share.

I dont know if it is a bug or not, but i solved the problem by not sharing from Virtual PC :)



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Mar062009

Castle Windsor Lifestyles

One of my friends told me that he didn't understand Lifestyles concept in Castle Windsor. Event though the documentation is very clear, wrote him a very simple application to explain the concept.  Before I jump into the code, let me repeat the information from the document first :).
Lifestyles help us to tell the Windsor container to how we want our components to be created. Castle Windsor gives us 5 different Lifestyles to accommodate our needs for different needs. Here is the list:

  1. Singleton (the default): As the name implies, only one instance of the component will be created, so when the object is request from the container, the object will be created once, and after request swill get a copy of the first request created object. This is the default behavior of the container.
  2. Transient: For each request from the container, a new instance for that object will be created.
  3. PerThread: It is singleton per thread, so within the same thread, all request will the same object, different threads will get new objects
  4. Pooled Instances: objects will be pooled to avoid unnecessary constructors
  5. Custom: what ever you code :)

Of course this information is same as in the documentation, and my friend ask me a demo, so let’s create one. In my demo, i will create a console application, so go ahead a create a demo application named: WindsorLifeStyles. Add references to: Castle.Core.dll  ,Castle.MicroKernel.dll, Castle.Windsor.dll, Castle.DynamicProxy.dll
Let’s add a very simple interface to our project:

public interface INotifier
{
    int MessageCounter { get; }
    string GetMessage();
}

If we drive a class from this interface, such as a StringNotifier class, it could be as simple as this:

public class StringNotifier : INotifier
    {
        private int MessageCounter_;
        public int MessageCounter
        {
            get { MessageCounter_++;
                return MessageCounter_;
            }
        }

        public string GetMessage()
        {
            return string.Format("MessageCounter: {0}", MessageCounter);
        }
    } 

There is no magic here, a class with a getter to a private variable, and each time, the value is read, it is incremented. Also a function that returns a string with the counter.  Now we need a class that uses our StringNotifier class, let’s call this NotifyClient, and here is the code:

   1:   public class NotifyClients
   2:      {
   3:          private INotifier notifier;
   4:   
   5:          public NotifyClients(INotifier notifier)
   6:          {
   7:              this.notifier = notifier;
   8:          }
   9:   
  10:          public void SendMessage(string msg)
  11:          {
  12:              string suffix = notifier.GetMessage();
  13:              Console.Out.WriteLine("Message from {0}, {1}",msg,suffix);
  14:          }
  15:      }

This is class that uses INotifer interface we defined, and in its contructor it takes it as a parameter. We have a dependency here. The SendMessage function merges the INotify().GetMessage() result with a parameter that is passed to it, and prints it to the console. It is time to code our Main function and also register our objects to the container. First let’s create the container:

IWindsorContainer container = new WindsorContainer();

After creating the container, it is time to register our classes to the container, so that we can call them later and also resolve the dependencies. Here is 2 lines of code that register the objects:

container.AddComponent("NotifyClients",typeof(NotifyClients));
container.AddComponent("StringNotifier",typeof(INotifier),typeof(StringNotifier));

It is time to consume the objects now, I will ask to the container to give me three NotifyObjects, and then call the SendMessage function:

   1:  NotifyClients notify1 = (NotifyClients)container["NotifyClients"];
   2:  notify1.SendMessage("notify1");
   3:   
   4:  NotifyClients notify2 = (NotifyClients)container["NotifyClients"];
   5:  notify2.SendMessage("notify2");
   6:   
   7:  NotifyClients notify3 = (NotifyClients)container["NotifyClients"];
   8:  notify3.SendMessage("notify3");

Before you run the application, can you guess the result? Here is the result:

Message from notify1, MessageCounter: 1
Message from notify2, MessageCounter: 2
Message from notify3, MessageCounter: 3

As you can see the counter is incremented, even if the ask the container to give us a brand new object, this happened because by default container uses Singleton Lifestyles and only and only 1 instance is created with this model. What if we want a completely brand new object each time we request it? then we have to change the lifestyle for that object. Go back to your StringNotifier class and add [Transient] attribute to your class so that it looks :

 [Transient]
    public class StringNotifier : INotifier
    { .....

Do the same thing for NotifyClient class, and run the application again, this time you will see that the MessageCounter is always 1 as for each request object, container created a brand new one. You can apply the other lifestyles and test your application but hope this brief introduction helps :)

Let the power surround you

Volkan



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses