Logo




Subscribe:
RSS 2.0 | Atom 1.0
Categories:

Sign In


[Giagnocavo]Michael::Write()

 Thursday, December 11, 2008
Full Typed Faults in Silverlight 2 (FaultException)
Silverlight 2 doesn't support faults, so you can't catch them. That sucks, since WCF's FaultException<T> is pretty useful. In Beta 1 I did a vile hack to get some data. After reading online, Id determined that Silverlight should be able to intercept the fault message and interpret it. Unfortunately, some of the handy classes to insert yourself into the stack aren't in Silverlight's WCF. Fortunately, there is a sample that does most of it:

http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660

In the "Message Inspectors" sample. This sample has code to let you inspect messages, and it also has a sample where they throw "raw" faults (i.e., "wrapped exceptions", aka "ExceptionDetail"). Why they stopped there is beyond me. With a bit of hacking (I must say, this SOAP stuff looks very complex), I got it to recognize any fault type, and throw a FaultException<T>. Well, not a FaultException<T>, 'cause there is a neutered FaultException class already in System.ServiceModel from Silverlight. So I named mine "SLFaultException" (SL for Simple Lame).

To get the fault thrown, you need to hookup the SilverlightFaultMessageInspector. From the demo code:
            EndpointAddress address = new EndpointAddress("http://127.0.0.1:52620/Service.svc");
            BasicHttpMessageInspectorBinding binding = new BasicHttpMessageInspectorBinding(new SilverlightFaultMessageInspector());
            ServiceClient proxy = new ServiceClient(binding, address);
            proxy.DoWorkCompleted += new System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_DoWorkCompleted);
            proxy.DoWorkAsync();
You also need to register the assembly's types so that the fault throwing code can find the fault detail to deserialize. There's no way in Silverlight to get all the loaded assemblies (as far as I know). So we do this:
   System.ServiceModel.SilverlightFaultMessageInspector.RegisterCurrentAssembly();

This registers the calling assembly's types to be searched when a fault detail is received.

Now the only thing that needs to be done is fixup the HTTP 500 status code to a 200. The MS sample has a behaviour to do this. But that's annoying, having another DLL to deploy and deal with. So I do this in the Global.asax:
        protected void Application_EndRequest(object sender, EventArgs e) {
if (HttpContext.Current.Request.PhysicalPath.EndsWith(".svc", StringComparison.OrdinalIgnoreCase) &&
HttpContext.Current.Response.StatusCode == 500 &&
!HttpContext.Current.Request.Browser.Crawler &&
HttpContext.Current.Request.Browser.EcmaScriptVersion.Major > 0) {
// Set 200 if its a faulted service request
HttpContext.Current.Response.StatusCode = 200;
}
}
From there, go ahead and catch SLFaultException<T> just like you would a FaultException<T>.

Overall, this proved far easier than I expected. I'm at a complete loss why they didn't ship faults in SL2. I mean, if I hacked _something_ out in an hour or two, I'm sure someone who had some clue of what they're doing could have done so easier. Heck, they even have the real WCF source -- I was stuck using Reflector for parts :P.

SilverlightFaultsBinary.zip (13.81 KB)

SilverlightFaultsSource.zip (61.55 KB)
Code
Thursday, December 11, 2008 2:04:45 AM UTC  #    Comments [3]  |  Trackback

 Wednesday, December 03, 2008
Windows Live Installer for Windows 2008
I wanted to install the new Windows Live -- Messenger looks better (normal windows instead of custom, yey!). Unfortunately, the installer (wlsetup-web) has an annoying version check. Fortunately, it's nothing OllyDbg couldn't patch.

For the paranoid, you can check it against the original:

>fc wlsetup-web.exe wlsetup-web.original.exe
Comparing files wlsetup-web.exe and WLSETUP-WEB.ORIGINAL.EXE
00019DDD: C3 6A
00019DDE: 90 20

I've only tested on Windows 2008, 32 Bit, English, and I only installed Messenger. But it appears to work just fine. (I had to manually uninstall the current Messenger version first.)

Here's to hoping the final version of the "new wave" of Live removes this check for us. Enjoy!

wlsetup-web.exe (990.5 KB)
Misc. Technology
Wednesday, December 03, 2008 2:48:06 AM UTC  #    Comments [1]  |  Trackback

 Tuesday, December 02, 2008
Command line WCF Proxy Generation for Silverlight 2 RTM

I have a scenario where my web service app exposes several interfaces, and I want to use all of them from the Silverlight UI. The code generated by SvcUtil isn't completely compatible with Silverlight's WCF, meaning you need to do a lot of fixup to make it work in SL. Looking in the forums, I see mentions of "slsvcutil" and "slwsdl", but I've been unable to actually find these programs. The only thing that Silverlight has is "Microsoft.Silverlight.ServiceReference.dll", in the "Program Files\Microsoft SDKs\Silverlight\v2.0\Tools\ServiceReference" folder.

I opened that DLL up in ildasm, and it appears to just be some classes that work on a ServiceContractGenerator. Digging in deeper, yep, they just go through the generated CodeDOM and fixup stuff that isn't compatible. For instance, IExtensibleDataObject isn't supported. SL WCF also doesn't handle having Sync and Async methods (i.e, SomeOp and Begin/EndSomeOp) since they both have the same action. (You'll get an "An item with the same key has already been added" error.)

My main problems with the cutesy "Add Service Reference" UI are:
 - I can't figure out how to tell it to use mutliple WSDL files and share the data types.
 - It generates a ton of files and VS gets all obsessive over them for some reason.
 - It generates a lot of extra code (like the useless ClientBase stuff, and the idiotic/useless "event based async pattern" code). Extra code just clutters up Intellisense, so why bother?

[Add Service Reference is great for demos and perhaps simple one-offs... I can't imagine dealing with it for anything slightly complicated.]

So, I took the MSDN code sample for the ServiceContractGenerator, and hacked it up to do what I needed. Then I added the 2 lines to pass it through the Silverlight ServiceReference fixup thing, and presto - things look great. Usage is simple:

Usage: slsvchack <clr namespace> <outputfile> <wsdl1> .. <wsdlN>

The options are hard-coded to what I use and makes the most sense for Silverlight apps (in my opinion). I want to do a full fledged "SLSvcUtil.exe", but I think the right approach there is to dissassemble SvcUtil and patch in the Silverlight.ServiceReference stuff. But, I don't have the time right now.

Code: slsvchack.cs.txt (2.95 KB) [It's in C# 'cause the MSDN sample was, and my edits were minor. ]
Binary: slsvchack.exe (8.5 KB) [I'm too lazy to link in the Microsoft.Silverlight.ServiceReference.dll, so you'll need the Silverlight SDK installed.]
Code
Tuesday, December 02, 2008 7:56:09 PM UTC  #    Comments [1]  |  Trackback

 Saturday, November 29, 2008
Follow up on Obfuscation and VistaDB
Recently I mentioned how a lot of companies use obfuscation unnecessarily, and it ends up hurting legitimate customers while doing nothing to prevent "crackers". Specifically, I mentioned VistaDB, as the obfuscation tool was injecting invalid IL, causing Mono to reject the assembly.

Jason Short replied to me and I detailed the exact problems with the obfuscator (along with a few F# scripts to unobfuscate and remove the bad IL). They then released a new build with the obfuscation removed -- which Mono now happily loads.

I just wanted to give kudos to VistaDB for doing this. Not many companies are smart enough to realise that their "protection" tools are useless and do a 180 on such a stance.
Code | Security
Saturday, November 29, 2008 7:12:05 PM UTC  #    Comments [0]  |  Trackback

 Tuesday, November 25, 2008
XmlSerialization for F# Types
On a current project, I'm using F# with ASMX Web Services (Mono, so no WCF). I started off declaring some types like this:

type Account() =
    [<DefaultValue>]
    val mutable Name : string
    [<DefaultValue>]
    val mutable Data : byte array


We have to tag "default value" to tell F# it should go generate the default (Unchecked.defaultof<'a>) -- in this case, null.

Unfortunately, the serialized XML is not what we want. Currently F# generates both a public field ("_Name") and a get/set property ("Name") to access it. I'm not sure why this is, but there's probably some interesting reason (the part of the spec is 10.2.7 Explicit Fields, but it doesn't mention the implementation). The workaround is simple: tag the field with "XmlIgnore".

As of F# 1.9.3.7, you can choose to target an attribute at the property or the field for a val in a class type. See: http://blogs.msdn.com/dsyme/archive/2007/11/30/full-release-notes-for-f-1-9-3-7.aspx (I didn't find this part in the spec.)

So, the revised declaration for the XmlSerialization-friendly type is:

type Account() =
    [<DefaultValue; field: XmlIgnore>]
    val mutable Name : string
    [<DefaultValue; field: XmlIgnore>]
    val mutable Data : byte array


I found that to add a lot of noise, so I aliased them:

type DV = DefaultValueAttribute
type XI = XmlIgnoreAttribute

type Account() =
    [<DV; field: XI>] val mutable Name : string
    [<DV; field: XI>] val mutable Data : byte array


Now it works just fine and creates the XML we'd expect.

One other thing might bite you: null. F# rightfully eschews null. If you have a function that returns one of these types, you'll find it won't let you return null:

> let test() : Account = null;;
  let test() : Account = null;;
  -----------------------^^^^^
stdin(6,24): error FS0043: The type 'Account' does not have 'null' as a proper value.

This is generally good, but unfortunately, interop with the unenlightened world is sometimes necessary. The right way to do this is:

let test() : Account = Unchecked.defaultof<Account>;;

That's a bit too verbose for my liking, since I have to go annotate the type. A simple function will get around that:

> let inline getnull() = Unchecked.defaultof<_>;;
val inline getnull : unit -> 'a

> let test() : Account = getnull();;
val test : unit -> Account

Yes, I know it's not null, but default, but I think the purpose is clear enough.

F#
Tuesday, November 25, 2008 2:16:33 AM UTC  #    Comments [0]  |  Trackback

 Saturday, November 08, 2008
Software protection
I've been meaning to write about this for a while. It's a very simple topic, but developers get all emotional and stop being rational as soon as the magic "code protection" and "piracy" words get invoked. I'd like to say I'm not promoting copyright infringement nor saying developers don't deserve to be compensated for their work. Now that that's out of the way...

The two things most developers want to stop are unauthorized installing (license enforcement) and "code protection". Code protection is a very weak concept, mainly revolving around thinking people are gonna steal your precious algorithms. Protection is easy to deal with, so I'm going to cover that now.

Before VMs like .NET were popular, most of the code protection I've seen revolved around the code that implements the license enforcement. Developers would write all sorts of nasty-clever-clever code to make things hard for the crackers. You see this sometimes when you run an application and it complains about a debugger being installed or running. With Java and .NET, disassembly got easier. This made it extra easy to patch any license code, since the dissassembled code was in a high level language like IL. The response, and our first enemy of the day, was obfuscation.

Obfuscation takes your assembly and screws up all the metadata. On top of that, it might go and rewrite sections of your code to obfuscate the flow of the program, or perhaps indirectly load strings. The downside of course is that debugging gets really hard cause all your method names are now unreadable, reflection is broken, etc. Depending on the techniques an obfuscator uses, you can run into some other troubles. For instance, whatever obfuscator VistaDB uses is really broken, as it generates bad IL that just happens to work on MS CLR, but crashes (rightly so) on Mono. Not to mention that certain IL tricks are not verifiable, hence you can't use the code in lower-trust scenarios.

But what does obfuscation accomplish? Crackers ALWAYS win. Even the "most difficult" license system with hardware dongles and activation get cracked. The response I usually hear is "well it raises the bar". So. What. "Raising the bar" is totally pointless. Bruce Schneier talked about this.

For physical security, raising the bar is good in general. For example, if you buy a safe, it'll prevent a lot of thieves from getting to the valuables. Sure, there are higher level thieves, but you've weeded out a lot of the population around you, and the benefit is very real. Now some punk kids can't just go in and vandalize and "casually steal" your valuables.

But for computerized tech, the "bar" is the highest level attacker. If your valuable is "cracking my serial verification code", as soon as the "high level theif" cracks it, he can go write a simple program anyone can download. So the REAL bar is "user googles for a crack". That's what needs to sink past all the emotional nonsense developers go through when protecting their code. No matter what kind of complex protection schemes you put in, then obfuscate it on top of that, if the product has value, _someone_ will crack it, and all your users can just download the crack.

This isn't a maybe, this isn't a "possibly", this isn't theoretic, this is the exact reality. There is *nothing* you as a developer can do to prevent this (apart from make your product suck so much no one cares). [If there is, I'd love to hear it.]

So, obfuscation has zero value in preventing cracks, serials from getting out. And it has downsides. Just read the VistaDB blogs/forums to see real world problems only because they use an obfuscator.

What about "protecting special algorithms"? From who? If your competitors are good, they'll figure things out regardless. If they suck, they won't be able to do much with it anyways. I think the biggest threat is some overseas group disassembling your code, slapping their logos on it, and reselling it. That's a clear and obvious loss if they are making sales. But, obfuscation isn't really going to stop it, just raise the bar a tiny bit. In this case, since you're dealing with a limited number of "pirate companies" that exist for profit, perhaps obfuscating has a bit of value. But think: If someone can not know your source code, not be able to provide support, etc. etc., but can still outsell you and your marketing, perhaps you have business issues.

The one other place I hear people using obfuscation is to protect an app from "casual hacking". WTF does that mean? You mean you're afraid your sales clerk might decompile the PoS application, but give up quickly? You think it means you can safely store passwords in the binary? I'm not sure what such developers are thinking, but I'm guessing they did a poor security analysis of the situation.

As a side note, this is not particular to VM platforms like Java and .NET. Check out Hex Rays. They do a fine job *decompiling* optimized native code. I've seen it in action; it makes it easy to take any native app, decompile it, figure it out, then work with the assembly code. So these .NET devs thinking they are so leet cause Reflector messes up and hence no one can figure it out... sigh.

Finally, a nice real-live demo. Look at Spore and other games using heavy DRM and protection mechanisms. Obviously Eletronic Arts has an unlimited budget for getting the "best" type of protection. Yet the protection proved utterly useless against piracy. Just goto ThePirateBay.org and search. Yet they certainly introduced more bugs and user hate. (Of course, the REAL motive behind such DRM is killing the used games market. For this, all they need is stuff that honest users won't break.)

P.S. The reason I finally wrote all this is because VistaDB just took the silliness to the next level. I got their 3.4 Trial, but it crashes on Mono because the obfuscator emits totally invalid IL code. Their official response was that Trials arent tested on Mono. I bought the product and the "stable" builds still have the same busted IL code. Awesome protection; stopping paying users from using the software rocks!

I suppose I could understand IF they had some awesome trade secrets. BUT, they provide a source code license. So an evil VistaDB competitor just buys a source code license to get all the details. How is obfuscation helping ANYONE here? (Note the runtime has no licensing; only the developer install.)

Code | Security
Saturday, November 08, 2008 12:06:00 AM UTC  #    Comments [4]  |  Trackback

 Monday, November 03, 2008
Common Conceptual Issues with F#
Several times I've had to explain a few basic F# things to new users. I ran into some of these too when I first looked at F#. If you've been looking at F#, but some things still don't click, I hope this will help break the chains of C/imperative languages. I'm assuming you know a bit about F#, perhaps from the Quick Tour or the F# Tutorial file that comes with the Visual Studio integration.

Functions always take and receive exactly one argument.
Despite anything you see, in F#, there's only one argument, and only one return value. Let's look at how this plays out (I suggest firing up F# interactive and playing around):

> let inc x = x + 1;;
val inc : int -> int

> let add x y = x + y;;
val add : int -> int -> int

[I like to read -> as "to", because it's short and sweet.] So, for the case of "inc x", we see the signature is quite simple and expected "int to int". But for add? We see "int to int to int". What this actually means is "a function that takes an integer, and returns a function that takes an integer and returns an integer".

The same signature in C# would look like this: Func<int, <Func<int,int>>> or "Func<int,int> Add(int x)". [Some day, think how odd it is to have two ways of representing the function.] So when we call the F# function, we're really passing in the first argument, getting a new function, then applying the second argument. Something like this:

1. add x y
2. (add x) y
3. closure1 y
4. final-result

"closure1" is what we get from the "partial" application of add. I'll touch on this in a minute.

So how do we _really_ pass in two arguments at once? We put two arguments into one value, a tuple. We write it like this:

> let add (x, y) = x + y;;
val add : int * int -> int

Notice the new type signature: "int by int to int" or "int int tuple to int". In C#, this would be:

int add(Tuple<int,int> arguments) { return Tuple.A + Tuple.B; }

But F# nicely provides support for tuples [via pattern matching], so we can write them much more naturally. This syntax also works on the way out:

> let pow23 x = x*x, x*x*x;;
val pow23 : int -> int * int
// "int to int int tuple"

> let square, cube = pow23 7;;
val square : int
val cube : int

> square, cube;;
val it : int * int = (49, 343)


There's never no value
Another common typo/misunderstanding is when creating a function with no arguments:

> let sayHi = printfn "Hi";;
val sayHi : unit

Hi
> sayHi;;
val it : unit = ()

Oh, what happened here? Remember how _everything_ takes and returns exactly one value? The same is true of functions that "don't return a value", such as printf. Instead of "not returning a value" like C's void, functions return a special type called unit with one value, ().

Armed with this, let's see what the sayHi definition actually says. It says "let a value called sayHi equal to the result of printfn". Well, since the result of printfn is unit, sayHi becomes unit. The execution happens immediately, and subsequent uses of sayHi just get the value, unit.

To actually do what we want, we need to take an argument. Then F# knows we're a function value:

> let sayHi() = printfn "Hi";;
val sayHi : unit -> unit

> sayHi;;
val it : (unit -> unit) = <fun:clo@0>

> sayHi();;
Hi
val it : unit = ()


By explicitly taking a unit parameter, sayHi becomes a function (type unit to unit). Notice that if we just write "sayHi", we're just going to get the _value_ of it (a function), not apply (execute) the function.

Partial application
OK, so a side effect of this system of "take on param and return a function that takes the next", is that we can compose with just parts of a function. For instance, to write an increment function, we can do this:

> let add x y = x + y;;
val add : int -> int -> int

> let inc x = add x 1;;
val inc : int -> int


So far, nothing interesting. However, we can also write this more effectively:

> let inc = add 1;;
val inc : (int -> int)


Aha! What's happening here is what happens "secretly" each time we call add with 2 parameters. We're just using the intermediate result, the closure of "add 1", and assigning that function value to inc. In C#, it'd be something like this:
public static Func<int, int> Add(int x) {
    return y => x + y;
}
public static Func<int, int> Inc = Add(1);
// and "full application" of add looks like this: Add(1)(2)
[BTW, this isn't really currying in F#. Currying is taking a method of type "a' * 'b -> 'c" and turning it into "'a -> 'b -> 'c". Since F# methods are "automatically curried", there's no need for a "curry" step (well, except perhaps when using .NET methods, which are always "tupled", but that's another story).]

[Side note: a function like "add" is superfluous, because in F#, operators are functions:
> (+);;
val it : (int -> int -> int) = <fun:clo@18>
> let inc = (+) 1;;
val inc : (int -> int)
]

The pipeline


F# appears to have all this complicated syntax, with |> <| >> << and so on. But, these operators are defined in F# code, and follow some basic rules. They aren't magic or have any special compiler support.

The most important function operator is |>. A quick search of the F# source shows:
C:\Program Files\FSharp-1.9.6.2\source\fsharp\FSharp.Core\prim-types.fs(2062):       
        let inline (|>) x f = f x


(Operators are surrounded in parentheses to define them and to use them as functions with prefix notation.)
The type signature is:
> (|>);;
val it : ('a -> ('a -> 'b) -> 'b) = <fun:clo@23>

This is "alpha to a function alpha to beta to beta". That probably didn't help. Perhaps looking at the type of function application will help:

> let apply f x = f x;;
val apply : ('a -> 'b) -> 'a -> 'b


This demonstrates that a function application is really just taking a function "alpha to beta", giving it an alpha, and getting a beta. [I'm open to suggestions on better ways to pronounce type arguments.]

So, glance back up at the pipeline operator. We can see it's really just function application _in reverse_. What is the use of such a construct? If you've used C# 3.0's LINQ extension methods or a Unix shell, you probably already know. By reversing the function application, we can write things in a much more natural order. To modify something from the F# Quick Tour:

> let filterTypes name =
-   System.AppDomain.CurrentDomain.GetAssemblies()
-   |> Seq.map (fun a -> a.GetTypes()) |> Seq.concat
-   |> Seq.map (fun a -> a.Name)
-   |> Seq.filter (fun s-> s.Contains name);;

val filterTypes : string -> seq<string>

> filterTypes "Coll";;
val it : seq<string>
= seq ["ICollection"; "EvidenceCollection"; "GCCollectionMode"; "CollectionBase"; ...]
>


Now, this is a bit embarrassing, but this took me a long time to get. I stared at this and re-read the F# manual for probably an hour. How could something so simple do such "complex" stuff?? Once I finally got used to the idea of functions being normal values, and the whole "one arg one value" bit, it snapped together. The other operators (<|, >>, <<) are pretty easy to follow once the basics are understood (going through prim-types.fs is a great experience).

What else?
I hope this all helps fit some pieces together. Feel free to use the MSN thing on the side of my site to ask questions or give me suggestions. Thanks!

Edit: Also check out F# function types: fun with tuples and currying (From an F# team member's blog.)


Code | F#
Monday, November 03, 2008 9:07:15 PM UTC  #    Comments [1]  |  Trackback

 Tuesday, October 28, 2008
F# 1.9.6.2 and Silverlight 2
Compiling for Silverlight 2 is a bit of a pain still. It's even worse with F#, because the Silverlight project system cannot tell when you're building your F# components correctly (using the right flags). So you get this error:

---------------------------
Microsoft Visual Studio
---------------------------
You can only add project references to other Silverlight projects in the solution.
---------------------------
OK  
---------------------------

This happens even if you set up the F# compiler options correctly by adding:
--standalone --noframework --cliroot "C:\program Files\Microsoft Silverlight\2.0.31005.0"

It still happens if you reference the DLL directly (FSLib1\bin\debug), you get the same error! Apparently VS or Silverlight projects go and try to find the project relating to the DLLs when you add a reference. So, the solution is easy: Move the DLL somewhere else. Then you can add a file reference, and it will work just fine.

One more problem. I get an FSC error when I turn optimize code on:
C:\test\SilverlightApplication1\FSC(0,0): error FS0193: internal error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain the namespace, module or type 'MarshalByRefObject'

If I leave optimize code off, then it seems to work. Good luck.

http://stackoverflow.com/questions/237044/how-does-silverlight-determine-an-assembly-is-silverlight


F#
Tuesday, October 28, 2008 10:27:50 PM UTC  #    Comments [5]  |  Trackback

 Monday, October 13, 2008
Mono or CLR in FreeSWITCH
mod_managed is now in the FreeSWITCH tree. This replaces mod_mono, and allows selection of either the Microsoft CLR or Mono 2.0+ as the runtime engine to use. All the interfaces, and most of the code, are identical for both versions. Modules written on Mono will work on the CLR version and vice versa.

Check it out.

Code | FreeSWITCH
Monday, October 13, 2008 10:43:10 PM UTC  #    Comments [0]  |  Trackback

 Friday, October 10, 2008
Banco Industrial Fail: Online Banking Hours
In this image, we see Banco Industrial (Guatemala) online bank. The Flash applet displays:

  System Hours - Monday to Sunday: From 6:00am to 22:00 hours. Last day of month: From 6am to 21:30 hours

WTF? Closing the online bank? By the way, who writes "Monday to Sunday?" And a 30 minute difference on the last day of the month? The levels of incompetence here just stack up, but it's par for the country.

Guatemala
Friday, October 10, 2008 3:13:41 AM UTC  #    Comments [2]  |  Trackback

VoIP Security - Peering
Every now and then I read an article on VoIP security. These articles almost always go over the obvious stuff such as lack of encryption, eavesdropping and ensuring you firewall your networks and so on. While certainly major issues, especially for a corporate deployment, there are still some other interesting issues.

One thing that keeps getting mentioned is the possibility for VoIP peering. Peering allows VoIP providers to send calls directly to each other (possibly over the Internet, maybe over [semi-]private connections). The main idea is cost savings, since the call doesn't need to go out over the public telephone network (PSTN).

To accomplish this, they'll set up a shared database mapping telephone numbers to VoIP providers. So, when a VoIP provider attempts to place a call, it'll consult this directory first. If it finds the number in there, it'll send it direct to the provider instead of over the PSTN. All the providers sign some sort of contract to say they'll be careful with the database and not populate it with invalid entries. Let's just assume the VoIP provider is trustworthy and hires trustworthy people (this is a stupid assumption, but I've had a peering company tell me this, as the security problems are too obvious without this assumption).

This system actually holds true inside of a VoIP provider's own network. A provider will want to terminate directly to a customer instead of out via the PSTN then back into their own network. So they'll probably have a directory of their own numbers so they can route those directly.

Well first off, now every peering member's security is bound by the security of every other member. If just one "trustworthy" peering provider gets compromised (not a hard task - more on that later), they can pollute the shared directory and hijack phone numbers. Being able to redirect a financial institution's phone number sounds like a profitable attack. An attacker can simply route the call to their system, then pass it through to the PSTN to avoid detection by users. Note that none of the security technologies available can prevent problems with a subverted, trusted, directory.

But it gets easier...
Many providers let you port your existing number to them when you sign up. From my limited experience, I've seen some of them immediately activate the number for you, so you can get started and going with their network while the port happens. A port can take a bit of time (and for now, let's assume the porting system is secure), so this sounds like a reasonable approach.

Wrong. First off, the new customer's number will probably go right into the provider's internal database, so all calls from that provider will go to the customer attacker. Depending on the size of the provider, this could be a pretty decent attack in and of itself.

But now, suppose the peering contract didn't specify not provisioning ports-in-progress, or if it did, the implementation people messed up. Now ALL the VoIP providers have been compromised, by a single provider who was agressive in their porting tactics.

Eventually it'll probably get resolved, but even a few hours or days of compromising a valuable phone number can be a significant attack.

What's the threat?
As a consumer, in general, I'd not worry too much about people trying to tap my line, just like I rarely worry about the safety of my wired Internet connection. But similar to intercepting credit card info versus hacking a company's database, this is a much juicier target. An attacker who pulls this off gets access to bulk information. Thus, I think the threat of something like this happening is much higher than having my individual calls monitored.

Security | VoIP
Friday, October 10, 2008 12:25:14 AM UTC  #    Comments [0]  |  Trackback

 Wednesday, September 24, 2008
Empty check on IEnumerable without consuming
One common issue with IEnumerables is that you can't find out anything about them until you use them. A frequent scenario is wanting to know if the IEnumerable is empty before you go ahead and use it. For example, you may want to write a result set to a file, but only if there's actually data.

As far as I know, the .NET Framework has no built-in classes to facilitate this, so I hacked up my own. You use it by wrapping an IEnumerable inside an EmptyCheckEnumerable. Then, when you check the IsEmpty property, it gets the enumerator and calls MoveNext once. When you then go to consume it, it intercepts the MoveNext call and simply returns the previous value. From then on, it just passes through. The result is that you don't consume the IE twice, which can be necesary for performance or other reasons.

Example:
var res = new EmptyCheckEnumerable<object>(dc.Execute<object>("SELECT * FROM foo"));
if (!res.IsEmpty) {
  // allocate resources and consume the IE - will only execute the SELECT once
}
I suggest creating a "ToEmptyCheck" extension method to flow type information.
Code:

EmptyCheckEnumerable.cs.txt (2.14 KB)
Code
Wednesday, September 24, 2008 10:11:30 PM UTC  #    Comments [3]  |  Trackback

 Friday, September 19, 2008
Objects versus Closures - a koan
In a previous comment, someone mentioned the OO mindset ("mold" -- quite appropriate). I don't want to go into it much, but simply "quote for win" something from here http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html. It's a nice take on things and I got a kick out of it:

"
  The venerable master Qc Na was walking with his student, Anton.  Hoping to
prompt the master into a discussion, Anton said "Master, I have heard that
objects are a very good thing - is this true?"  Qc Na looked pityingly at
his student and replied, "Foolish pupil - objects are merely a poor man's
closures."

  Chastised, Anton took his leave from his master and returned to his cell,
intent on studying closures.  He carefully read the entire "Lambda: The
Ultimate..." series of papers and its cousins, and implemented a small
Scheme interpreter with a closure-based object system.  He learned much, and
looked forward to informing his master of his progress.

  On his next walk with Qc Na, Anton attempted to impress his master by
saying "Master, I have diligently studied the matter, and now understand
that objects are truly a poor man's closures."  Qc Na responded by hitting
Anton with his stick, saying "When will you learn? Closures are a poor man's
object."  At that moment, Anton became enlightened.

"
Code | F# | Humour
Friday, September 19, 2008 6:00:50 PM UTC  #    Comments [0]  |  Trackback

 Thursday, September 18, 2008
Update on mod_mono in FreeSWITCH
FreeSWITCH's mod_mono plugin should now work fine on Linux. Additionally, it's in the Visual Studio Solution file, all you need to do is compile mod_mono (it won't build by default). There's also now support for running mod_mono inside FreeSWITCH inside another managed application, just in case you're embedding FreeSWITCH.

For more info: http://wiki.freeswitch.org/wiki/Mod_mono

FreeSWITCH
Thursday, September 18, 2008 2:24:38 AM UTC  #    Comments [0]  |  Trackback

SQL 2008 Change Tracking with LINQ-to-SQL
I hacked up a little class to enable us to use SQL 2008's Change Tracking feature with LINQ-to-SQL. Change Tracking allows you to see which keys (and optionally columns) have changed in the database from a specific version. The SQL docs have a great overview with lots of examples and information.

Basically, we get a special CHANGETABLE function to SELECT from, which gives us the change information and keys. Additionally, there is the issue of versioning. Changes are only kept so long, so we want to make sure the last version we sync'd is still compatible, otherwise we have to re-initialize.

Finally, in order for our change SELECTs to be coherent, we need to snapshot the database. The easiest way to get this is by turning on Snapshot Isolation. Snapshot isolation allows us to read a virtual snapshot of the database. Any changes made from when we begin our transactions are not visible to us and we do not lock anything we read.

Here's an excerpt from a class I have to provide change tracking for our database:
public DbDataChangeProvider(long lastVersion) {
    this.lastVersion = lastVersion;
    this.txScope = ChangeTracking.GetSnapshotScope();
    
    var validV = ChangeTracking.GetValidVersionForAll(dataContext);
    baseline = lastVersion < validV;
    currentVersion = ChangeTracking.GetCurrentVersion(dataContext);
}
We take in the last version, then initialize a SnapshotScope. We get the minimum valid version and see if we're going to have to generate a baseline (re-init) or not. Next, we grab the current version of the database, so consumers can save the version for when they sync up next.

To get changed keys, you can do this:
ChangeTracking.GetChangedKeys<string>(dataContext, "Accounts", "AccountName", lastVersion, System.Data.Linq.ChangeAction.Delete);

This will give you an enumeration of all the Deleted keys; use other ChangeActions to get Insert or Updated. There's also a filter (SQL string) to limit further.

To get changed _items_, you can pass in a Queryable, like this:
ChangeTracking.GetChangedItems<Account>(dataContext, dataContext.Accounts.Where(a=>a.Balance>10), "Accounts", "AccountName", lastVersion);

The code should (seems to work for me) figure out your query and inject the JOIN to the CHANGETABLE function. The code is linked at the end of this article. Some of the functions use a Tuple type; if you don't have it, I've posted it elsewhere on this site. Or, you can delete those methods; they are only for 2-key tables.

ChangeTracking.cs.txt (9 KB)
Code | Misc. Technology
Thursday, September 18, 2008 2:03:46 AM UTC  #    Comments [0]  |  Trackback