Category Archives: .NET

NOD32 IMON Component Is Just Plain Dangerous

Recently I started to receive some rather strange error messages from some .NET programs I had written that made use of the WebRequest class. The exception was something like this:

System.IO.IOException: Unable to read data from the transport connection: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.. ---> System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at System.Net.UnsafeNclNativeMethods.OSSOCK.recv(IntPtr socketHandle, Byte* pinnedBuffer, Int32 len, SocketFlags socketFlags)
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode) 

This means that the native recv method was trying to muck with protected memory: a fairly bad and low level failure! This kind of thing shouldn't really be able to happen because the .NET Socket class is very robust and well tested, so I broke out the native code debugging features of Visual Studio to try and figure out what was going on. This involved allowing native code debugging on the project, and turning off "Just My Code" in the VS debugging options. Furthermore, I turned on automatic debugging symbol loading using the MS symbol server (located here). This done, I reran the application and look what I saw:

        ntdll.dll!_KiFastSystemCallRet@0()
        ntdll.dll!_NtWaitForSingleObject@12()  + 0xc bytes
        kernel32.dll!_WaitForSingleObjectEx@12()  + 0x84 bytes
        ntdll.dll!ExecuteHandler2@20()  + 0x26 bytes
        ntdll.dll!ExecuteHandler@20()  + 0x24 bytes
>    ntdll.dll!_KiUserExceptionDispatcher@8()  + 0xf bytes
        imon.dll!20b2472a()
        [Frames below may be incorrect and/or missing, no symbols loaded for imon.dll]
        imon.dll!20b20bca()
        imon.dll!20b06e21()
        imon.dll!20b23afa()
        imon.dll!20b23afa()
        imon.dll!20b239f1()
        imon.dll!20b239f1()
        imon.dll!20b239de()
        imon.dll!20b24d79()
        kernel32.dll!_MultiByteToWideChar@24()  + 0x76 bytes
        imon.dll!20b19418()
        imon.dll!20b212ae()
        imon.dll!20b0602a()
        [Managed to Native Transition]
        System.dll!System.Net.Sockets.Socket.Receive(byte[] buffer = {Dimensions:[2]}, int offset = 0, int size, System.Net.Sockets.SocketFlags socketFlags = None, out System.Net.Sockets.SocketError errorCode = Success) + 0x139 bytes
        System.dll!System.Net.Sockets.Socket.Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) + 0x1d bytes
        System.dll!System.Net.Sockets.NetworkStream.Read(byte[] buffer, int offset, int size) + 0x78 bytes

I wasn't expecting to see this because recv is actually located in Ws2_32.dll! It looked like the imon DLL was actually hooking this call and then blowing up internally due to some bug. I happened to know that this was part of the NOD32 internet protection suite I have installed, and indeed once that was disabled my programs no longer threw the exception! This is a clear case of a bug in their product, so I reported it to them. Unfortunately, their response was not particularly helpful:

In our next major release (3.0), we are doing away with IMON after
many years and replacing it with two more utilities.

In 1992, when NOD32 was introduced, very few programs operated at the
Winsock level. Today, in addition to Google and Microsoft, 100's of
other developers are creating software in this manner. That would be
fine, except for the fact that any app that operates here needs the
top spot in the stack, and only one program can have it.

As it is now, it can't be enabled at all on a server.

IMON was just the first layer of defense, a supplement. The strengths
of NOD32 are AMON, which scans every file that performs an action, as
it performs that action and the advanced heuristics which is stopping
90%+ of all new threats, before a definition is even written.

By quitting IMON now, you'll not only allow both programs to operate
together, but you'll also lose no coverage.

So what I'm taking away from this experience is that NOD32s IMON is just broken, and potentially dangerous: from now on I'll be turning it off on all my installations of NOD32, and I recommend you do the same.

Arbitrary Restrictions On C# Generic Constraints

I'm really feeling the pain of the simplicity of C#s generics system. I have found some situations where I could introduce more type safety by being able to refer to a type parameter on the left hand side of a generic constraint which is not a parameter of the immediate definition, but rather that of an enclosing class. For an example of what I mean, see this:

public interface IMarker<T>

{ }public class TestList<T>

{

    public void Add<S>(S item) where T : IMarker<S>

    { }

}

public class Program

{

    public static void Main()

    {

        new TestList<IMarker<int>>().Add<int>(2); // Yep!

        new TestList<IMarker<string>>().Add<int>(2); // Nope!

    }

}

Alas, in their wisdom Microsoft have decided this is too advanced a feature for the unwashed masses to get their hands on, so I will have to struggle forward with runtime checks..

Bitesize Functional Programming: Active Patterns

Welcome to the first in what I hope will be an ongoing series of blog posts on research in functional programming. I see a lot of really neat papers come and go that show the great things that are happening in this design space, and I'm hoping to open their discoveries to a slightly wider audience by providing more what I hope are readable descriptions of them for people who don't have the time to trawl through 20 pages or so. By using examples liberally I hope I can provide an alternative to the sometimes rather dry language of the abstracts. Anyway, that explained we can get on with the show!

A really cute paper just came up on Lambda the Ultimate, about the implementation of a new feature in the .NET functional programming language F# called Active Patterns. The basic idea is to let you pattern match not just structurally, like this:

> data Animal = Armadillo String
| Mink String
| FunctionalProgrammer String Integer
>
> show (Armadillo name) = name
> show (Mink name) = name
> show (FunctionalProgrammer name iq) = name ++ ", IQ of " ++ (show iq)

But also FUNCTIONALLY, by letting you define your own match functions:

> (|Text|Element|) xmlNode = if xmlNode.ContentType = Text then Text (xmlNode.Text) else Element (xmlNode)
>
> match myXMLNodeInstance of
> Text s -> print ("Looks like a text node containing " ++ (show s))
> Element e -> print ("Hmm, it's something else!")

And actually it goes beyond this because your pattern matching functions can receive arguments before the data you actually want to pattern match on, or can be partial functions (i.e. fail to pattern match on some inputs). Their "curried" nature lets the authors of the paper define a function which lets them write a pattern matching on the Nth bit of an integer, and on that integer rotated N times, where N is potentially supplied at runtime. This clearly has great potential for expressiveness!

I think that's quite enough about active patterns, but I must say that I'm quite tempted to go and add F# to my repetoire now :-). Coming up next time, possibly: data parallel Haskell (concurrency for free!) or constructor tagging (cute optimisation for lazy functional languages).

Global Hotkeys With .NET

So, last year while working at Resolver Systems I worked with the author of Movable Python, which is a fairly neat application that lets you carry Python around on a USB stick. As an intellectual exercise I reimplemented the core functions in C# with a slightly less eccentric interface (no offence meant, Michael!), but was suprised to find I had to roll my own code to setup global hotkeys to run scripts, which was a nice feature of Movable I wanted to try and add.

The Win32 APIs for this are themselves are pretty grungy (all sorts of nastiness with bitflags and message loops), but I think I've been fairly successful in abstracting that away in this simple class, which you can get from here. With this, you can setup a hotkey like this:

Hotkey hk = new Hotkey();
hk.KeyCode = Keys.1;
hk.Windows = true;
hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };

if (!hk.GetCanRegister(myForm))
{ Console.WriteLine("Whoops, looks like attempts to register will fail or throw an exception, show an error/visual user feedback"); }
else
{ hk.Register(myForm); }

// .. later, at some point
if (hk.Registered)
{ hk.Unregister(); }

Obviously this is a bit of a kitchen sink example to try and show every feature, but even then it's a damn sight easier than what you would use to set up even a basic usage manually with P/Invoke. If you are wondering about the requirement for a form parameter to Register and GetCanRegister, this is simply a requirement of the underlying APIs, probably due to the fact that they signal hotkey presses in the application message loop rather than via a callback.

I hope someone finds this useful and to facilitate that process I hereby place all the code into the public domain to be messed around with to your hearts content. Enjoy!