Wednesday, 5 September 2012

Simple Regex #6: Lazy Quantifiers

Dedicated Listener

I've decided to listen to 129 classical symphonies and rate them against each other, to try to understand this musical format a little better. The project has two immediate side effects of a technical nature. I've had to:
  1. Replace the 32GB SDHC card on my phone MP3 player, a venerable Sony Ericsson Xperia X10 Mini, with the bleeding edge Sandisk 64GB SDXC, to make room for a shedload of symphonies; and
  2. Brush up on greedy quantifiers, and their lazier, more reluctant counterparts.
The former was a pleasant surprise. The phone manufacturer's specifications have always claimed microSDHC compatibility "up to 16GB", but I'd been using a 32GB card ever since the X10 Mini got shunted out of my wife's handbag by the arrival of a bouncing new baby Galaxy. Still, the jump to purchase the XC card was a bit of a leap of faith, since nobody else online appeared to have tried this particular combo. Sadly, it worked! Yes sadly, because otherwise, I'd have had a great case for a new phone...

The latter side effect occurs because I've arrived at my list of 129 symphonies under test by combining the main table of 120 listed at Digital Dream Door,
http://www.digitaldreamdoor.com/pages/best-classic-symp.html
with a further 9 also-rans suggested by that forum's moderator, and compiler of the main list, whom we shall call Brian (for that is his name). Having screen scraped his raw data, converting all its en–dashes and “directional quotes” to hy-phens and "neutrals", I was left with the task of parsing these results. Here's a small sample:
 1. Symphony No. 9 in D minor "Choral" - Ludwig Van Beethoven
 2. Symphony No. 5 in C minor - Ludwig Van Beethoven
11. Symphonie Fantastique - Hector Berlioz
63. Symphony No. 3 "The Camp Meeting" - Charles Ives
For analysis, I need to extract certain data from these entries. The first, dot-terminated field is Brian's initial rank. This is followed by the full title of the symphony, which usually includes its performance key, and sometimes a popular alternate title or nickname. Finally, a hyphen sets off the composer name.

Now, it would have been easy to take multiple passes at this task, first removing any optional (key and nickname) fields present, then splitting the remaining text into the mandatory rank, root title and composer name fields. Too easy, in fact. Why do that, when we could just use a single Regex pattern to simultaneously extract the full compliment of fields, mandatory and optional?

Too Greedy

The difficulty is that the pattern capturing the symphony title could also gobble up any key and/or nickname information that might be present. Let's say for simplicity that the key field can be identified by the word in, while the nickname is delimited by double quotation marks. That gives us two optional groups:
(?: in (.+?))?
(".+")?
where we've nested the capturing key group (underlined) in a non-capturing group (?: )? in order to exclude the in keyword itself from the captured data. Let's try dropping these into our first attempt at a mandatory field template:
(\d+)\. (.+)(?: in (.+?))?(".+")? - (.+)
This succeeds in extracting the leftmost rank and rightmost composer name fields correctly. However, there's no key or nickname information parsed out; all of that remains resolutely embedded in the title field. We say that the + quantifier in the title group (.+) is greedy. It gobbles up as many input characters as possible, backtracking only when necessary to find an overall pattern match. If it can devour the key and nickname information without breaking the match, as here it can because those groups are optional, then it will.

Dieting

Quantifiers like ?, *, + and {m,n} can be made less greedy by following them with a question mark. For example, the ? quantifier on its own matches zero or one occurrence(s) of the preceding expression, but with a preference for one. That's to say, it will gobble up input characters whenever it can. ?? also matches zero or one occurrence(s) of the expression immediately before it, but with a preference for zero. In general, these so-called lazy quantifiers consume as few input characters as possible, while still letting the overall pattern match succeed. Which turns out to be exactly what's needed in our case:
(\d+)\. (.+?)(?: in (.+?))?(".+")? - (.+)
Now the title group (.+?) consumes the minimum possible number of characters, meaning that if there are key or nickname fields present, the associated groups will now have a higher priority in extracting those from the input stream. Similarly, the identical key group (.+?) has itself been put on a diet, to stop it gobbling up any present nickname.

The final pattern that I used contained many further refinements, including named groups for readability, generalisation of white space, trimming of field contents, and stricter key field matching with a more specific group pattern,
[A-G](?: sharp| flat)?(?: major| minor)?
which actually removes the need for the second lazy quantifier above. Incidentally this also allows the word in to appear in the symphony's title in a non-key, non-nickname context - as for example in Igor Stravinsky's Symphony in Three Movements, which happens to be number 76 on Brian's list.

Further Reading, Listening

Greedy and lazy Regex quantifiers are explained in more detail at MSDN:
http://msdn.microsoft.com/en-us/library/3206d374.aspx
A good online tool for testing regular expressions containing multiple groups is Derek Slager's AJAX offering, A Better .NET Regular Expression Tester, which can be found here:
http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
As for the listening exercise, a quick survey of my dusty old Classic FM CDs reveals that I already have good recordings of 43 56 symphonies on Brian's list, including all of his top 20 25 (and quite a few duplicates; who authorised that?). So cost wise, I'm exactly one third almost half complete. Although to be honest, I've never really liked Solti's limp wristed walkthrough of Mozart's Jupiter...

Monday, 27 August 2012

Two-Factor Authentication Example: Dropbox

Update: LifeHacker has a list of places where two-factor authentication is currently available as an option.

I'd Go for the App

Generally less accurately referred to as Two-Step Authentication, the principle of Two Factor Authentication demands the production of two or more out of a set of three authentication factor categories:
  1. A knowledge factor - something you know;
  2. A possession factor - something you have; and
  3. An inherence factor - something you are.
Inherence being problematic - as can be appreciated from consideration of the archetypal examples of fingerprints, voice prints, and iris scans, and in particular their potential vulnerability to replay attacks - it has become common for two-factor systems to employ the ubiquitous mobile phone as the thing the user has, in combination with various little bits of secret information that the user knows.

One of the first two-factor systems to gain popularity was Google's Authenticator app (an open source project) on these platforms:
  • Android 2.1 or later;
  • iPhone iOS 3.1.3 or later; and
  • BlackBerry OS 4.5 - 6.0.
Primarily covering GMail, this system now extends to all other Google Apps, and can be enabled in any third party app using the PAM Module. The first factor comprises your traditional combination of user name and password. Then, the mobile Authenticator application prompts you for an auto-generated verification code.

Now On Dropbox

Anyway, not to bury the lede, Dropbox - perhaps in response to last month's spammage, enabled by a Dropbox employee who had re-used his or her password at another, previously hacked site, resulting in the exposure of many users' email addresses - now offers such a system. Look under the Security tab, in the section labelled Account sign in, for the so-called Two-step verification setting.

Two options are provided for acquiring the new verification code. The first is a simple text message to your mobile phone. This is the easier of the two, but it also introduces a new potential vulnerability. Attackers can use social engineering against your phone provider to have your messages forwarded to another account. This exploit has in fact been documented several times against Google's two-factor system, e.g. at CloudFlare in May of this year.

So yeah, I'd definitely go for option 2, which is to use one of the following mobile apps to generate a unique time-sensitive security code with the help of the standard Time-based One-Time Password (TOTP) algorithm:
You may select either to scan a displayed bar code / QR Code, where supported, or to enter your secret key manually. Note that most apps will still generate the required security codes even when the cellular network or other data service is unavailable, such as when travelling or where coverage is unreliable.

Hat tip: Brian Krebs, as is so often the case!

Wednesday, 22 August 2012

Security (Link) Clearance - August 2012

Another small selection of interesting stories from recent security blogs.


Why passwords have never been weaker - and crackers have never been stronger.

Over at Ars Technica, Dan Goodin explains why, thanks to real-world data, the keys to your digital kingdom are under assault:

http://arstechnica.com/security/2012/08/passwords-under-assault/


The iPhone Has Passed a Key Security Threshold

So thinks Technology Review contributing editor Simson L. Garfinkel:

Does society really want extremely private mobile devices if they make life easier for criminals? Apple's newly toughened standards sharpen the focus on that question.

http://www.technologyreview.com/news/428477/the-iphone-has-passed-a-key-security-threshold/


Is iPhone Security Really this Good?

Meanwhile, Bruce Schneier has his own perspective on that assertion:

Yes, I believe that full-disk encryption -- whether Apple's FileVault or Microsoft's BitLocker (I don't know what the iOS system is called) -- is good; but its security is only as good as the user is at choosing a good password.

http://www.schneier.com/blog/archives/2012/08/is_iphone_secur.html


Triple DDoS vs. KrebsOnSecurity

With the best security blog of them all, it's unsurprising that Brian Krebs continues to attract the ire and DDoS arrows of the spambot kings:

According to Prolexic, the one used against KrebsOnSecurity.com was Attack Type 4, a.k.a “Max Flood”; this method carries a fairly unique signature of issuing POST requests against a server that are over a million bytes in length.

http://krebsonsecurity.com/2012/08/triple-ddos-vs-krebsonsecurity/


There ya go.

Thursday, 9 August 2012

Eliot Reads Prufrock

I Come In Value Packs Of Ten

The Love Song of J Alfred Prufrock, by Thomas Stearns Eliot, is my favourite poem. Not that I've read them all, I mean all the poems in the world, before arriving at this objective decision; that is not what I meant at all. There are far too many poems in existence to have done that, seriously, there's literally dozens out there. But of the five or six that I have read, Prufrock is quite definitely the best.

So I quite enjoy listening to the poet's own recitation, and ever since playing the old vinyl record at a friend's house in about 1980, have always been within a lodger's lunge of such a recording. Today, deciding to legalise our relationship, this poem and me, I grabbed a few spoken word MP3s from Amazon: The Waste Land, a scratchy old clipping suite encoded at an average of 62¼ kbps (and extravagant at that if you ask me); Prufrock itself; and one other, The Triumphal March From Coriolan.

Immediately, the 20 minute duration of the Prufrock file caught my attention. You see, Prufrock is my party piece. Well, it's either that or a Pogues-informed The Band Played Waltzing Matilda, Eric Bogle's despairing Gallipoli dirge, which nevertheless does have the advantage of being an actual song. No, I don't get invited to a lot of parties... you knew? You are not blind! How keen you are! On second thoughts it might be more accurate to describe Prufrock as: the piece I would recite on the night bus home from George Square, in order to ensure my evening ended with a good, sound beating up. Playing relentless Status Quo on your ghetto blaster works almost as well.

But I divest. I knew that, even after ten pints of Stella Artois, there's no way to stammer, slur, stretch and deform a recitation of Prufrock over more than about 10 of those 20 minutes. So what was going on? Firing up foobar2000, I discovered that both of the higher bit rate files contained multiple works.

I Call That A Bargain

01 - The Love Song of J Alfred Prufrock.mp3 actually includes the first three poems (which belong together anyway) from Prufrock and Other Observations, and finishes with Mr. Eliot's Sunday Morning Service. Here's the cue sheet:

00:00 - The Love Song of J Alfred Prufrock
08:20 - Portrait of a Lady
15:35 - Preludes
18:20 - Mr. Eliot's Sunday Morning Service
20:00 - [end]

02 - The Triumphal March From Coriolan.mp3 contains the following:

00:00 - Ash Wednesday
13:45 - A Song for Simeon
16:15 - Marina
18:33 - Triumphal March From Coriolan
21:45 - O Light Invisible (from The Rock)
24:20 - Chorus from Murder in the Cathedral
26:30 - Chorus from The Family Reunion
28:20 - [end]

I guess someone read the original LP's bipartite title, T S Eliot reads The Love Song of J Alfred Prufrock & Triumphal March From Coriolan (link goes to a March 1959 Gramophone review), and decided just to rip and label sides A and B accordingly and respectively. So there you have it: get 'em while they're hot, eight and three-halves poems for the price of two. As for The Waste Land, well those files didn't contain any Easter Eggs. Incidentally if you'd like to hear that latter masterpiece in full, the Harper Audio is rebroadcast in various formats (though not MP3) by the Internet Multicasting Service here, and of course less legally throughout YouTube.

Sunday, 29 July 2012

Happy Birthday (3) To Me

This Little Blog is Three

Three years behind the masthead. Macro blogging is officially dead, social media in the ascendancy, and still I won't roll down the shutters and scarper. What the hell is wrong with me!

Targets

I can only think it must be love. So then, how's my blogging frequency been holding up? At the 2009 outset, declared goals were:
  • two posts per week, on average;
  • half of those technical, half not;
  • half of the technical posts to be security related.
Once again, the answer is: not bad, could do a little better. Having just escaped Facebook on the second attempt, I can look back and see how some of minor comments I've made there, for example last year's broken links to toasted cheese or mismatched shoes, might otherwise have grown into short blog posts. So the Zuckster must accept at least part of the blame for those.

Unpopularity Analytic

About 1,500 page views per month, last time I checked. Low enough to avoid most comment spammers, but just high enough to retain my interest.

As for the blog's original motivation, namely the introduction of security related software development, that's been superseded by the formation of something called a SCARB group in our (new, extended, all-inclusive and thoroughly democratic) Development Department. When the Security subcommittee (that's me and my pals, the "S" of the group moniker) enters a less dormant phase, this little blog will be one of the first to know.

Previously:
Happy Birthday To Me
Happy Birthday (2) To Me
Birthday candles courtesy of Wikipedia.

Thursday, 26 July 2012

RIP Free Cellular Web Access

And A Mystery Solved Thanks To XKCD

My original Amazon Kindle, with its free global access to 3G networks and its experimental browser, was a Christmas gift from my wife, having been inspired by my apparent inability to organise my dead tree storage. This browser uses the same connection that all 3G-equipped Kindles use to download books via Amazon's Whispernet, and until recently, it offered access to as much of the world wide web as you could take. Usually, that wasn't much. The browser renders like treacle, while pages don't look terrific on the monochrome, electronic ink display.

But it was functional, and quite useful on continental holidays and other occasions when we found ourselves temporarily without WiFi access. Just as recently as, well, earlier this very month, I had cause to be grateful for Linda's decisions (-; in both cases, against my better judgement ;-) to buy me (a) a Kindle, (b) with 3G connectivity. Sitting in the garden outside our French gîte, I reached the end of my chosen holiday read (a pulpwood edition of The Hunger Games) and wanted immediately to download its sequels, whilst simultaneously checking out a few blog updates.

That was then. Today, as I read on El Reg, Amazon have started exercising their reserved, small-print right, to throttle this free 3G access at just 50MB per month. Obviously having learned from both the Sony experience and their own previous missteps, they are following this course in preference to just switching off free 3G access altogether.

However...

There still remains a mystery in the detail. This post on the MobileRead forum reports the cutoff message, followed by another:
I got a second message saying that I'd have 24 hours of grace to continue to use 3G for Web browsing, but that after that I could use 3G only for visiting Amazon.com, Wikipedia, and the Kindle Store.
Certainly, retaining free access to both Amazon and the Kindle Store makes commercial sense. But why should Wikipedia be particularly exempted?

That's when I remembered the above XKCD cartoon, from 3½ years ago. Click through for the full version. Although the answer isn't in the printed cartoon itself, it's in Randall Munroe's floating text that appears when you hover over it:
I'm happy with my Kindle 2 so far, but if they cut off the free Wikipedia browsing, I plan to show up drunk on Jeff Bezos's lawn and refuse to leave.

Wednesday, 25 July 2012

Book Review: Liars & Outliers

Enabling the Trust that Society Needs to Thrive

A favourite blog was noticeably subdued of late, while the inestimable Bruce Schneier put his finishing touches to his latest tome. No sooner was he done, however, than all of my favourite blogs burst out with news, reviews, and other expositions about it. Resolved to buy a copy, maybe on Kindle, I nevertheless put in a book request to my manager, and was in due course pleasantly surprised by the hardback landing on my desk.

Surprised? Well, I was unsure whether it would qualify for purchase. It's not a technical book, although it does cover many technical issues we have to deal with in daily business. It's not about programming, or not exclusively so. What it is, is a thorough investigation into the nature of trust within society. Or in other words, into the nature of of civilisation: how it works, and why it doesn't. How indispensable and deeply reaching is trust. How, why, when and where we depend upon it. How our essential systems can be designed to guarantee it. As ever, Bruce's approach to each little corner of the subject matter is almost rigorously scientific, being relatively free from hand waving and equivocation, and as evidence-based as he can diligently achieve.

After an overview, declaring the primary aims of the book, and containing an excellent diagram of the formal terms used (societal dilemma being a central one) and their relationships, the remainder of the book consists of four main sections.

Part I: The Science of Trust

This deals with the various research fields comprising the "background" sciences of the book: experimental and evolutionary psychology, biology, neuroscience, economics, the mathematics of game theory, computer security, and so on. Chapter three will be particularly familiar territory if you've ever studied evolutionary perspectives on behaviour, such as sociobiology. This is followed by a historical view of sociology and societal scaling, then by a return to game theory for an examination of societal dilemmas and the nature of conflict.

Part II: A Model of Trust

This is the most intensely argued and analytically comprehensive section of the book, and it might take more than one reading here and there to follow the workings of the "Model" presented. Clearly this is an exposition of the central concept that inspired the whole work. Various pressures are considered both in isolation and in concert: moral and institutional stresses, considerations of reputation, and the limits imposed by security systems. Schneier's goal is to get you to hold all of these simultaneously in your conception, tracing the interconnections and interplay between them.

In chapter 9, Institutional Pressures, Schneier examines the threats facing modern society. Acknowledging that one of the biggest perceived threats is terrorism, he astutely reminds us we can never ensure perfect security against this. Arguing that America's TSA budget should be measured in the millions, not billions of dollars, he observes that talk of terrorism as an "existential threat" to society is complete rubbish. While terrorism remains sufficiently rare, which it is; and while the vast majority of people survive, which they do; society itself will continue to survive. Yet while this observation remains unarguable, politically it is impossible for our leaders to speak it.

Part III: The Real World

In the second half of the book Schneier describes real world Organisations, Corporations and Institutions, illustrating how the competing interests of these bodies lead to evolution and resolution in certain real world situations. A recurring theme is fishing, which at all levels has rules and quotas adhered to by the majority, but offering considerable profits and a low risk of getting caught to the minority of cheats.

Part IV: Conclusions

To be frank, you could say that there are very few actual conclusions in the book itself. In the chapter on Technology, Schneier proposes a set of design principles for effective societal pressures, one of the key points of the book. But more often, he provides us rather with information, with the background to understand and make sense of that information, and with the grounding in a refreshing number of academic and scientific disciplines that we can exploit to build confidence in our own conclusions, which we are encouraged to reach independently.

In so doing, you're certain find the scope of input presented here quite breathtaking.

Bruce Schneier
Liars and Outliers: Enabling the Trust That Society Needs to Thrive
John Wiley & Sons
17 Feb 2012
ISBN-10: 1118143302
ISBN-13: 978-1118143308