Tuesday, 12 February 2013

Role Based Access Control

This introduction to aspects of Identity and Access Control in Microsoft .NET 1.0 through 4.0 serves as groundwork for examination, in a later article, of the same issues in .NET 4.5. We start with two short interface declarations:

IIdentity and IPrincipal

These two interfaces first appeared in 2002, with the initial release of .NET 1.0 (and ASP.NET 1.0):
interface IIdentity
{
  bool IsAuthenticated { get; }
  string AuthenticationType { get; }
  string Name { get; }
}

interface IPrincipal
{
  IIdentity Identity { get; }
  bool IsInRole(string roleName);
}
For developers these interfaces abstract, and their implementing classes encapsulate, the most important features of identity-related concerns. IIdentity deals only with authentication: Name obviously identifies the user; AuthenticationType describes how that user became authenticated (e.g. via Windows Authentication or Kerberos, or some other custom mechanism); and IsAuthenticated indicates whether the user is actually authenticated at all (client-server apps sometimes allow anonymous users). IPrincipal extends this provision into the adjacent realm of authorization, by providing the single method IsInRole allowing the aggregated IIdentity to be interrogated at the first level of role-based access control granularity.

Thread.CurrentPrincipal

Not to be confused with the Win32 "thread token", this is a static property of the Thread class, giving access to the currently executing thread's IPrincipal implementation. So not strictly static then, as every thread in your system can have a different value of IPrincipal. More sort of thread-static. It is set up when the security context for a client is established, either by the startup code of a desktop app, or by some runtime in the case of an ASP.NET or WCF server app.

WindowsIdentity and WindowsPrincipal

When the AuthenticationType indicates Windows Authentication, these are the concrete System.Security.Principal classes used to wrap the Windows security token, encapsulating the Windows account of the current desktop app process (or of the client, in a client-server system):
// Get Windows account user name
var id = WindowsIdentity.GetCurrent();
var userName = id.Name;
// Check that user belongs to Builtin\Users
var principal = new WindowsPrincipal(id);
var isUser = principal.IsInRole(@"Builtin\Users");
Note that while this code works, it is not advisable to refer to user groups using strings. For one thing, the built-in group names are localized. For another, an administrator might change the name of a group, obviously breaking any hard-coded string based checks. For reasons like these, Windows internally uses not strings but immutable Security IDs (SIDs) to reference both users and groups:
var account = new NTAccount(userName);
Console.WriteLine(account); // MY-DOMAIN\johnk

var sid = account.Translate(typeof(SecurityIdentifier));
Console.WriteLine(sid); // S-1-5-21-29562463-4174942564-1615450050-1377

foreach (var group in id.Groups)
  Console.WriteLine(group.Translate(typeof(NTAccount)));
This last line prints the list of groups as human-readable strings, e.g.,
MY-DOMAIN\Domain Users
Everyone
BUILTIN\Users
NT AUTHORITY\INTERACTIVE
CONSOLE LOGON
NT AUTHORITY\Authenticated Users
NT AUTHORITY\This Organization
LOCAL
MY-DOMAIN\Local Group
MY-DOMAIN\Employment House
MY-DOMAIN\Development
Remove the Translate call to see the raw security IDs underlying your group names.

Returning to the earlier question about the interrogation of roles, we can now use the idea of a security identifier, together with the provided enumeration WellKnownSidType, to determine for example whether the current user is a local administrator:
var localAdmins = new SecurityIdentifier(
  WellKnownSidType.BuiltinAdministratorsSid, null);
Console.WriteLine(principal.IsInRole(localAdmins));
The second parameter to the above SecurityIdentifier constructor is itself a SID. As suggested by its parameter name domainSid, domains also have security IDs, and can be passed around as such when required. For example, to determine whether the user is a domain administrator, you have to supply the SID of the relevant domain, which in this case is the user's account domain:
var domainAdmins = new SecurityIdentifier(
  WellKnownSidType.BuiltinAdministratorsSid, id.User.AccountDomainSid);
Console.WriteLine(principal.IsInRole(domainAdmins));
Lastly, to answer the original question about whether the user is a member of the built-in users group,
var users = new SecurityIdentifier(
  WellKnownSidType.BuiltinUsersSid, null);
Console.WriteLine(principal.IsInRole(users));
UAC Reminder

Ah, yes. Do remember when interpreting these results client side, that the returned values respect User Account Control (UAC), enabled by default since Windows Vista. UAC prefers to run client processes without administrative privileges, unless instructed otherwise (e.g. by Run as Administrator).

GenericIdentity and GenericPrincipal

So much for the WindowsIdentity and WindowsPrincipal classes. These are ideal when your user list is stored in Windows itself, for example when you use Active Directory. But what if your user list is in some other repository, such as a SQL database?

Using the GenericIdentity and GenericPrincipal classes, you can manage user names and roles for yourself, persisting them in your own custom credential store, while still taking advantage of those very useful IIdentity and IPrincipal properties - and specifically, the IsInRole method. Using System.Threading, we have (assuming that Alice has previously supplied a correct password, or otherwise authenticated):
var id = new GenericIdentity("alice");
var roles = new[] { "Sales", "Marketing" }
var user = new GenericPrincipal(id, roles);
Thread.CurrentPrincipal = user;
This sets up the necessary principal for subsequent use. Later - say, during the execution of some other method on this thread - we might want to find out the current user name, and whether she is in Sales:
var user = Thread.CurrentPrincipal;
Console.WriteLine(user.Identity.Name); // alice
Console.WriteLine(user.IsInRole("Sales")); // True
Authorization and Roles

Whichever IIdentity and IPrincipal implementations we use, the mechanisms of role-based authorisation are the same. Here are four alternatives, from the imperative to the declarative, all of which resolve directly or eventually into IsInRole calls:
  1. make direct calls to Thread.CurrentPrincipal.IsInRole();
  2. assert System.Security.Permissions.PrincipalPermission demands;
  3. apply [PrincipalPermission] attributes to methods or classes;
  4. add <authorization /> elements to web.config.
Example 1 - coded tests:
if (user.IsInRole("Marketing"))
  DoSomeMarketing();
else
  AccessDenied();
Example 2 - security assertions in code:
// Throws a SecurityException if the assertion fails
new PrincipalPermission(null, "Marketing").Demand();
Example 3 - security assertions in attributes:
[PrincipalPermission(SecurityAction.Demand, Role = "Sales")]
[PrincipalPermission(SecurityAction.Demand, Role = "Marketing")]
private static void DoSomeSalesOrMarketing()
{
  // ...
}
Example 4 - <authorization /> elements in web.config:
<configuration>
   <system.web>
      <authorization>
         <allow roles="Sales,Marketing"/>
         <deny users="*"/>
      </authorization>
   </system.web>
</configuration>
Notice that options 1-3 above all have the disadvantage that the security model is hard coded throughout the source. Obviously, this can be very hard to maintain. Also in option 3, there is no simple, convenient and tidy way to hide these security assertions from the CLR, for example to run unit tests. These objections and many others have been addressed by the claims-based security authorization model introduced in .NET 4.5, which is the subject of the next article in this series.

Sunday, 3 February 2013

m b v





Plainly, everyone who is anyone is either talking or joking, or both, about the biggest music news of the year to date, not directly involving David Bowie.
Namely, the new

My Bloody Valentine

album, m b v, whose quiet release (escape?) softly echoes that of Sir David's latest song.
Not too many reviews yet though.
Let's see, I'm on to my fifth listen now, should be able to start collecting impressions.
Why not read along while you listen to it on their official YouTube channel:
http://www.youtube.com/watch?v=rBKjhgHGVZs&list=PLG9zGdKjNW2_S0nRfRmESBmYh3RR-3baU
(Oh incidentally, Robert's joke is that MBV are always being confused with Bridgend's finest metallurgists, Bullet For My Valentine.)

she found now

Solid Loveless territory.
I'm instantly reminded to turn up to 11 and blow my ears clear with a tin of Allsops Airduster for the full effect.
Ah yes, there ya go, hello old friends.

only tomorrow

Unremittingly shoegazing, with beautiful vocals, angelic in places.
Well, in one place really: the end of each verse.
And sporadically between verses.
Two places, then.
Nicely melodic guitar fuzzes in the breaks.

who sees you

A dissonance repeatedly reaching out, almost too slowly, too falteringly, and then only - just! - acquiring its goal on every turn.
We used to have to drill extra eccentric holes in our 45s to generate this kind of entertainment.
Like when you love chillies, and someone gives you picked jalapeños.
Not a home run, nor likely to grow on me.

is this and yes

Very pretty.
No surprises.

if i am

Good rhythm, shape and melody.
Getting the warp thing (pitch dip) better this time.
Some fine percussive effects shared across instruments.
Silly ending - well, anything's better than a fade.

new you

Possibly the most un-MBV thing they've done, erm, "recently".
Clear tracked volume-envelope rhythm guitar, keys, bass, drums, wtf?
Only thing making this cut recognizably theirs, is Belinda's singing.

in another way

Wow, some real originality going on in here.
Great guitar sounds, twisted drum loops.
Those strident slashing stabby guitar breaks have an occasionally Scottish flavour.

nothing is

Look out, here comes T-Bone Burnett on caffeine!
In an infinite ascending, crescendoing, percussive loop.
Mesmerising.

wonder 2

A mad drum loop phased into sounding like traversing high speed trains.
Two-way multiply-echo-tracked vocals.
Well that was different, maybe one of their best.

That's Yer Nine

What did you think of it?
Here's what I thought.
A worthy, if imperfect and untimely, sequel to its two decades senior Loveless sibling.
This is the band's Majora's Mask to their Ocarina Of Time.
Bottom line: it has earned its place in the top 60GB that resides permanently in my phone.

Verdict: 7.5 out of 10.

Come to Glasgow and catch them at Barrowlands on March 9th!

Thursday, 24 January 2013

Pioneer DEH-1400UB

CD RDS Tuner with WMA/MP3 Playback and Front USB

Update: Halfords upgraded my dodgy Pioneer to a superior - and 40% more expensive - Sony, free of charge! Nice customer service.

To: The Manager
Halfords

Dear Sir or Madam,

Last November my wife purchased a Pioneer car stereo, model number DEH-1400UB, from Halfords as a birthday present for me. It was later fitted, by Halfords personnel.

Fitting took a full two hours instead of one. One reason given for this was that the mechanic did not have the necessary tools to hand. When the job was eventually completed, my new car stereo appeared to work, electrically speaking; however, it seemed mechanically to be quite loosely fitted, as the right side of the unit did not appear to be fixed to the dashboard, but just flexed in and out quite freely.

The earliest opportunity we had to get this apparent fault inspected and fixed was during the Christmas holiday break, when another mechanic showed us that one of the two fixing bolts had apparently been cross-threaded and stripped - in fact he found the missing bolt within the dashboard cavity. He told us that we would have to go to our Honda dealer and order a replacement part for this. My new car stereo unit, its mounting hole having apparently been similarly stripped during the original fitting attempt, would also have to be replaced.

The replacement part arrived and we collected it from Hamilton. Still in December (I think) we returned to Halfords, brand new Honda mounting bolt in hand, to have the replacement stereo unit fitted. This time, after the requisite hour, the unit seemed to be firmly and correctly mounted.

However

We immediately noticed that the unit was prone to skipping and jumping when playing CDs. It would also cut out entirely while the car was not even moving, e.g., while parked or stopped at traffic lights. Then in January, while driving smoothly along a main road at about 10mph, i.e. no bumps, quite suddenly three of the speakers went silent, while the fourth (offside rear) jumped up in volume and became distorted. Also, the unit’s firmware appeared to have “crashed”, as none of the controls - volume up/down, band/channel change, signal source - had any effect. Fortunately the OFF function still worked.

Upon telephoning Halfords that afternoon, we were instructed to bring the car back on Monday at 2pm, to have the unit looked at.

Meanwhile, we continued to run the unit as a radio tuner with its volume turned down to zero, so that we could at least get the functionality of a dashboard clock out of it. Then on the morning of Sunday 20th I decided, while parked, to very cautiously turn up the volume. I discovered that all four speakers were working once again. However after only a few minutes of operation at this low volume, three of them packed in again, leaving only the offside rear working, with distortion, as before. This time however the unit’s firmware did not crash, and volume up/down etc. appeared still to work.

When we telephoned again at 1pm on the Monday to confirm our upcoming visit at 2pm, we were told that the shop was “fully booked” and that we would have to pick another day. The next day (Tuesday) unfortunately being unsuitable to us, we were forced to agree on 3pm, Thursday - one full week after reporting these latest faults.

Meanwhile

On Tuesday, while parked and listening to the FM radio, I noticed the station signal fade then disappear, leaving only a little faint radio noise. I nudged the frequency up then back down exactly one single notch, using the </> buttons, which caused the unit to retune correctly. This happened several times.

On Wednesday, again while parked and listening to music from my phone using the AUX input, I noticed the volume in the right side fall to zero, then return after a minute or so. This also happened at least three times.

This purchase is now two months old, and still we have been unable to get a single day of fault-free operation out of it. In fact while driving we have been forced to continue to keep its volume at zero, in case it decides spontaneously to jump up and distort again, a terrifying prospect which could easily cause a serious accident.

Having encountered such a bewildering array of faults, I am almost at a total loss to explain them - and I have a university degree in electronics! Perhaps the unit has a secret remote control, and someone is hiding in our rear seat pressing buttons at random? And I mean every single button. That might explain it...

I say “almost” because I do have a serious theory, namely: sloppy firmware programming, combined with poor power line noise suppression. But my theories are neither here nor there, and I guess you do have many other customers happily using this same model.

Just to Recap

Recent faults have included:
  • CD jumping (brand new shrinkwrapped CD, vehicle stationary)
  • Spontaneous power down (while playing brand new CD)
  • Triple speaker failure
  • Single speaker distortion
  • Complete loss of control of all functions (except power OFF)
  • Tuner jumping to a random frequency (vehicle stationary)
  • Right speakers fading (vehicle stationary)
We have completely lost all confidence in this particular manufacturer and model of car stereo.

Saturday, 29 December 2012

This is Addressed to Geoff Taylor

Of The BPI (British Recorded Music Industry)

Still in his job [sigh].

Saturday, 15 December 2012

JavaScript Programmers

I know you don't need it explained to you.

But they do.

Friday, 14 December 2012

The Speed of Jean Sibelius

At The Castle Gate

If you've watched The Sky At Night religiously since the mid 1960s, then you've seen all but a few dozen of Sir Patrick's 700+ episodes. Alas, the ones you missed will probably have to stay missing, their tapes having been wiped or thrown out, if indeed they ever existed (many episodes were simply broadcast live).

You've also heard the opening strains of Sibelius's Pelléas et Mélisande a corresponding number of times, in this recording of the Royal Philharmonic Orchestra conducted by Sir Thomas Beecham. Such long term exposure to that introduction has, you've almost certainly found, two noticeable side effects. One is perfect pitch: at the close of a hi-hat you can sing its opening chord, bell clear and literally pitch perfect, at any time of any day or night. Man, that's got to be the world's most unbelievably annoying earworm. The second effect, and the one exercising me here today, is a very strong and ingrained opinion concerning exactly what tempo the piece should be played at.

Sir Patrick's death last Sunday occurs as I'm completing the central corpus of a symphony collection, and turning to concentrate on other, equally non-vocal, classical musical forms. So naturally, I was prompted to add to the old Micro-SDXC card, this suite of incidental music written for Maurice Maeterlinck's 1892 drama of doomed infatuation. Turning to Amazon, I thought I'd spin the old amateur astronomer, virtuoso musician, composer and Krautbasher in his grave, by downloading this Deutsche Grammophon Masters recording of Berliner Philharmoniker, under the onetime Nazi maestro himself, the Austrian Herbert von Karajan.

Now, I've had plenty of speed issues with certain grand maestro composers before, most notably Herr Herbert here, but also Sir Georg Solti, Leonard Bernstein, and a few others (by contrast, I always find Daniel Barenboim perfectly to taste). But sweet mother of Adolf, nothing in the history of music could ever have prepared me ever for the glacial interminability of this treatment, ever. Whatever the merits of the rest of the suite, that first geologically grinding movement is bloody unlistenable.

What's the Frequency?

Clearly at this point I had to know which was "right", in the sense of being closer to the composer's original intention. Because, you know, that can change everything. If this impossibly, inhumanly lento melodrama corresponded more faithfully to the thoughts of Jean Sibelius, then I'd just have to learn to live without Beecham's much more familiar dancefloor aerobic workout. Luckily we can decide these things independently. On Sibelius's original score, there's a tempo command specifying
which is to say: serious and ... widely? ... expansively I guess, with 48 minims (half-notes) per minute. The time signature is 2:2, so there are two minims in a bar, and the piece comprises 60 bars in total, with no repeats. Oh wait, two of those bars are in 3:2 time - Jean, you crafty devil! - so we'll call it 61 equivalent bars of 2:2 to compensate. That's a grand total of 122 minims, which at a mean frequency of 48 per minute, should take just 2 minutes and 32½ seconds to play.

Run time of the Karajan recording: six minutes dead.

Conclusion

So that settles it then. Just as I'd suspected, Herbert von Karajan was a grandstanding, temporising, scene-stealing, attention-seeking hack of a drama queen. Yes, I have indeed wasted my money with this purchase. And yet...

The funny thing is, once I found the score and followed it along with the music, this interpretation really started to grow on me. And you know, even the canonical Beecham stretched it out to 3½ minutes.

Wednesday, 5 December 2012

SA1503: CurlyBracketsMustNotBeOmitted (Part 1)

Parenthetical Remarks

StyleCop rule SA1503 is designed to complain whenever
The opening and closing curly brackets for a C# statement have been omitted.
What does this mean, and is it a good rule?

Syntactic Structures

In C#, the bodies (or consequents) of certain flow control and looping constructs, such as if, while, and for statements, can syntactically be any single statement. For example, the underlined statements below are all single-statement bodies:
if (x == 1)
  y = 2;
else
  z = 3;

while (x < 10)
  x++;

for (var i = 0; i < 10; i++)
  x *= i;
Obviously there are times when you want the body of your construct to contain, rather than a single atomic statement, a sequence of two or more such statements. This is accommodated by the use a special type of single statement called a block, comprising just the required sequence of statements enclosed in curly braces, as shown below. Note that the entire contents of the curly braces, including the braces themselves, still comprise a single statement - which just happens to be of the block type:
if (x == 1)
{
  y = 2;
  z = 3;
}
These flow control and looping constructs can be nested within one another. A simple example of such nesting is this:
if (A())
  if (B())
    C();
  else
    D();
Since the rule in C# is that an else clause gets associated with the nearest available if statement, the else in this example has been indented to line up correctly with the second if statement, to which it properly belongs.

Problem?

Some people point out that the indentation can be applied incorrectly, and that the resultant statement
if (A())
  if (B())
    C();
else
  D();
can be ambiguous. Of course it's not ambiguous; after all, the compiler has absolutely no problem in applying the correct rules of precedence in a case like this, and coming up with the one correct result. However, it is true to say the above example is confusing, since it looks as though the else clause refers back to the first if statement rather than matching the second. The obvious remedy is to correct the indentation - and in fact to enforce consistent and correct indentation in future, so that such confusion cannot occur.

A Bad Fix

Sadly, those same people who insist on allowing badly formed indentation to pollute their code, often compound their error by suggesting a rather odd way of fixing it. Simply disallow any statement type except a block in these contexts! The result is a proliferation of brackets:
if (A())
{
  if (B())
  {
    C();
  }
  else
  {
    D();
  }
}
Although much harder to read, this version does at least have the virtue that its intention is quite clear. However, that clarity has not come about from the addition of braces. No, the alignment of the braces merely served to highlight the indentation error which was causing the confusion, and which incidentally has also been corrected in this latest version. Correct the indentation and we remove the confusion, braces or none. If anything, the braces are making it more difficult to follow the structure of nested statements like these, by making them twice as tall as they need be, and physically separating the components that you're trying to line up visually.

Another Example

In the above referenced documentation of rule SA1503, the following example is given:
if (true)
  this.value = 2;      
  return this.value;

Glancing at this code, it appears as if both the assignment statement and the return statement are children of the if-statement. In fact, this is not true. Only the assignment statement is a child of the if-statement, and the return statement will always execute regardless of the outcome of the if-statement.
Okay, so far I'm agreeing with you. But sadly we soon descend into nonsense:
StyleCop always requires the opening and closing curly brackets to be present, to prevent these kinds of errors:

if (true)
{
  this.value = 2;      
  return this.value;
}
Yeah, no. Now this so-called example lacks any credibility. Look, if that first fragment compiles, the one without the braces, then it must be sitting at the very end of its enclosing method - because it ends with an unconditional return, anything after which is unreachable code. Which of course you're already detecting, and in fact treating as an error, right? Right, so it's the last thing in the method. But this means that the second version can't compile at all, since there needs to be another unconditional return statement after it; the compiler will be justly livid about its absence (not all paths return a value, nag nag nag...).

Preliminary Conclusion

When I started looking into this issue, I was inclined to accept switching on rule SA1503. Anecdotal evidence seemed to support the idea that it could prevent bugs. And then, for me at least, there was this clincher: even Eric Lippert appeared to be suggesting that compulsory braces represented a solution to the classic dangling else problem, and one which he wished had been applied to C# from day one!

Then I realised that SA1503 wanted to do much more than just enforce braces in an if statement where an else clause was present. It wanted braces everywhere! That was when I began to pay closer attention to the arguments being offered, both for and against the measure.

The faulty examples above are typical of much I've encountered in researching what now appears to me a particularly misguided and ineffectual StyleCop rule. In seeking to mitigate against bad code layout by making wholesale changes to its syntactic structure, we not only miss our target entirely, but find ourselves instead lowering the code quality and readability. SA1503 therefore seems a bad rule from this perspective.

Next time: quick edits & legacy code.