November 2004 - Posts

Texas Hold’em Poker and how to randomize

Whether you’re a blogger or a regular reader of blogs you’ve probably noticed the flood of Texas Hold’em poker spam littering blog comments. Online gambling is a shady business and it represents a raft of risks. Would you give your credit card details to a company using the same marketing practices as eastern European porn-barons and the Nigerian mafia? How do you know if your opponents are cheating insiders or players acting in collusion?
When it comes to e-business a key concern is “is this safe”? With Texas Hold’em poker this has not been the case.
The software, developed at the end of the nineties by ASF Software Inc., had a major flaw. The flaw enabled anyone to deduct the order of the cards in any shuffled deck from the cards in your hand and on the table.
A deck of cards has 52 card and there are approximately 2^226 ways you can shuffle these cards.
The game was developed using Borland Delphi and the shuffle algorithm used the built in random generator function using the number of seconds since midnight as the random number seed. The Delphi random function is a classic example of a linear congruential function
The key misassumption the programmers have made is that the random function actually creates random numbers. The following code will print 66, 14, 12, 52 and 16 every time it’s run.

public static void CreateRandomNumbers() {
            Random r=new Random(42);
            for (int i=0;i<5; i++) {
                        Console.WriteLine(r.Next(100));
            }
}

As you can see, even though the class is named Random, it yields highly predictable results.
A 32-bit number has approximately 4 billion random variations; however the Texas Hold’em game used the number of milliseconds since midnight as a random seed. There are only 86,400,000 possible variations since this is the number of milliseconds per day. Since the random seed was the number of seconds since midnight, the system clock on a hacker’s computer could easily be synchronized with the Texas Hold’em clock.
With the two initial dealt cards and the cards laying face up on the table one can generate shuffles until a perfect match, which is a shuffle with the same cards in the same order is found. This is trivial, since knowing the random seed has narrowed the number of possible variations to around 200,000.

The flaw was discovered in 1999 by Cigital and ASF Software should have sorted the issue by now. Though I think they’ve gone out of business, at least their URL points to a spam site today. Whether you play against a hacker generating hands or not, I reckon there is a fair chance you’re getting screwed if you play Texas Hold’em poker with anyone of the spammers.
If you’re writing poker software, shuffle your decks using a proper random generator. The CryptGenRandom WIN32 function yields real random numbers by adding process and thread ids, CPU counters and hashes of the user and computer name into the mix. This gives the algorithm lots of entropy, hence lots of randomness. If you create a proper shuffling algorithm, your poker software might be more of a success than Texas Hold’em poker and you won’t have to resort to spamming blogs in a desperate attempt to make people waste money in your online casino.

The Starbucks Integration Pattern

ThoughtWorker Gregor Hohpe has noticed that Starbucks uses an asynchronous integration model when serving their customers. He’s written a geeky, yet funny analysis of the business interactions of coffee shopping. The article is a fresh take on mundane business integration concepts, much in line with his book “Enterprise Integration Patterns”.

Read “Starbucks does not use two phase commit.”

The inner workings of generics

The CLR program manager, Joel Pobar has posted an extraordinary article on the inner workings of generics. It is an advanced topic, but Joel explains the different concepts very well. A must read for those who want to dig deeper.

Iconfusion

Earlier this week one of my coworkers told me that he’d gotten some sort of virus or spyware that neither the virus scanner nor AdAware was able to detect.
He’d stumbled across the parasite by accident while using the task manager to monitor the memory and CPU usage of a service he was debugging. The parasite was an executable running as the SYSTEM account with a different name for the executable after every reboot.
To be on the safe side, I opened my task manager and found a process with a similar name and the exact same size running as the SYSTEM account.
The actual executable was located in the Windows\temp directory and had a cute little puppy as its icon. I made a copy of the file, before I killed the process.
Viruses often have messages hidden within them, so I opened the file in a hex viewer to take a closer look at it. I was both relived and surprised of what I found.
The file had a reference to a debug symbol database file named OfcDog.pdg (D:\OfficeScan\src\Client\OfcDog\Release\OfcDog.pdb). Trend Micro OfficeScan is the virus scanner we use so this file was probably not hostile. Just to be sure I located OfcDog.exe and it was a verbatim copy of the shady executable I had running on my computer.

I reckon that the reason for renaming the process on every reboot is to make it harder for hostile code, such as a virus, to kill the process. However, when having an executable that does such a thing it should be easy to understand what it is. If the developers at Trend Micro had used the same icon for this file as tray icon, I would have recognized it immediately. Having a cute puppy as an icon might seem like a fun idea since the file has “dog” in its name, but when used with applications that appear to be shady in the first place, it only makes users more suspicious.
The morale of the story is that one should always use icons that make sense to the user. An icon should be a picture or symbol that is universally recognized to be representative of something. Using something different only causes iconfusion.

Listing all ASP.NET pages and user controls in an assembly

“Milsnips” asked a question in the dotnet.framework.aspnet newsgroup about how to programatically check his ASP.NET web application and return a list of all the ASPX and ASCX pages in the project. He only wanted those who were part of the assembly and none of the pages or controls that had been excluded from his project.
If he follows the default naming pattern for pages and code-behind classes, eg. WebForm1.aspx inherits from the WebForm1 class. The following code snippet will do the trick:

Type[] allTypes=Assembly.GetExecutingAssembly().GetTypes();
ArrayList pagesAndUserControls=new ArrayList();
foreach (Type type in allTypes) {
            if (type.IsSubclassOf(typeof(System.Web.UI.Page))||type.IsSubclassOf(typeof(System.Web.UI.UserControl))) {
                        pagesAndUserControls.Add(String.Format("{0}.{1}",type.Name,
                                    type.IsSubclassOf(typeof(System.Web.UI.Page))?"aspx":"ascx"));
            }
}

A slightly different version of this post has also been published as an answer in the newsgroup.

How about weekly builds of Whidbey and Orcas?

Towards the end of the Java ”Tiger” (J2SE 5.0) project, a snapshot of the binaries was released every week. This enabled early adopters to have access to all the latest bug fixes and changes. The Java community was so enthusiastic about this, that Sun now has decided to release weekly snapshot of not only the binaries, but also the source code for Java “Mustang”. Wouldn’t it be cool if Microsoft did something similar? What some of the bugs in Whidbey went away each week? And wouldn’t it be great to get a flying start on developing with Orcas immediately after .NET 2.0 is released next year?

(Yes, I know that Longhorn previews where handed out at PDC, but I’m thinking of publicly available releases. Not just for the few at PDC or the elite who are “down” with the dudes at Microsoft.)

Running NUnitASP tests in Test Driven .NET

When it comes to unit testing, Test Driven .NET and NUnit is a killer combination. Once in a while I’ve also used NUnitASP to automate dead-boring point, click and type testing of web pages. NUnitASP is a NUnit extension, so it integrates perfectly with the NUnit GUI or Test Driven .NET – at least it used to do that. After upgrading from NUnit 1.11 to the superior 2.2 release NUnitASP tests ran in the NUnit test runner, but I was left with an ApplicationException telling me that the type declaring the test could not be found when running them in Test Driven .NET.
Since the 2.2 release of NUnit has a more of a dotnetty feel to it than its predecessors, having to revert to an earlier version was not an option. I decided to investigate the issue.
NUnitASP is based on 1.x style NUnit. The use of the deprecated Assertion class instead of the Assert class makes this evident. NUnit has become stricter on the visibility of test fixture members. While test methods always have been required to be public, NUnit 1.x allowed the setup and teardown methods to be private. In NUnit 2.x these methods must be public as well.

To resolve the issue I downloaded the source code for NUnitASP and changed the visibility of the SetUp and TearDown methods in the WebFormTestCase class, built my own assembly and changed the reference in my test suite.
Doing this enables you to run tests in Test Driven .NET, however there are some issues that you still have to workaround.
The NUnitASP framework declares setup and teardown handlers in the WebFormTestCase class. These methods conflict with setup and teardown methods in your test fixture. This could be solved by making further changes to the WebFormTestCase class. However, I prefer to keep the changes to this class to a minimum so I suggest that you shadow the implementation of the BaseSetUp and BaseTearDown methods in your test fixture if you need a setup or teardown handler.

Here is an example of a shadowed setup handler:
[SetUp]
new public void BaseSetUp() {
            base.BaseSetUp();
            Browser.GetPage(home.ToString());
}

Coding Horror

The source code the winning entries in this year’s International Obfuscated C Code Contest is out. These are by far the worst bits of code I’ve seen in a while. Check out this Manga like CRC inserter or this Maze Navigator. The only way this tab/space/linefeed stenographer code could be made less readable would be to write it in Whitespace.
One thing is for sure, the next time I get called to help debug a do-everything-and-then-some-in-the-event-handler application saying “it was the worst code I’ve seen” would be a lie.