Next CocoaHeads Swindon meet!

So for those of you who didn’t manage to enjoy the glories to be found in the town that was the inspiration for one of Legion’s more colourful adventures,[] next Monday, the 3rd of August, offers yet another once-in-a-monthtime opportunity! As ever, the location is in (or just outside) the Glue Pot, a strong man’s stone’s throw from the Swindon train station. This month’s meeting is a recap on QTKit, to allow those who weren’t there last time due to the reschedule to catch up on integrating QuickTime into their Cocoa apps.

[] What am I doing knowing quotes like that? Well, the clue is in the user name. When I was a student my UNIX username was leeg, clearly based on my real name. In short order, I was introduced as "He is Leeg, for he are many" and thus iamleeg.

Posted in whatevs | Leave a comment

NSConference videos

Scotty and the gang have been getting the NSConference videos out to the public lately, and now sessions 7-9 are available including my own session on security. The videos are really high quality, I’m impressed by the postproduction that’s gone in and of course each of the sessions I watched at the conference has some great information and has been well-presented. All of the videos are available here.

I’ve also put the slides for my presentation up over on slideshare.

Posted in cocoa, conference, macdevnet, security, Talk | Leave a comment

Coming very shortly…

This website will be the new home for information on Cocoa and Mac OS X security. But not yet! Please check back soon; in the mean time take a look at my homepage.

Graham.

Posted in Uncategorized | Comments Off on Coming very shortly…

Refactor your code from the command-line

While the refactoring support in Xcode 3 has been something of a headline feature for the development environment, in fact there’s been a tool for doing Objective-C code refactoring in Mac OS X for a long time. Longer than it’s been called Mac OS X.

tops of the form

My knowledge of the early days is very sketchy, but I believe that tops was first introduced around the time of OPENSTEP (so 1994). Certainly its first headline use was in converting code which used the old NextStep APIs into the new, shiny OpenStep APIs. Not that this was as straightforward as replacing NX with NS in the class names. The original APIs hadn’t had much in the way of foundation classes (the Foundation Kit was part of OpenStep, but had been available on NeXTSTEP for use with EOF), so took char * strings rather than NSStrings, id[]s rather than NSArrays and so on. Also much rationalision and learning-from-mistakes was done in the Application Kit, parts of which were also pushed down into the Foundation Kit.

All of this meant that a simple search-and-replace tool was not going to cut the mustard. Instead, tops needed to be syntax aware, so that individual tokens in the source could be replaced without any (well, alright, without too much) worry that any of the surrounding expressions would be broken, without too much inappropriate substitution, and without needing to pre-empt every developer’s layout conventions.

before we continue – a warning

tops performs in-place substitution on your source code. So if you don’t like what it did and want to go back to the original… erm, tough. If you’re using SCM, there’s no problem – you can always revert its changes. If you’re not using SCM, then the first thing you absolutely need to do before attempting to try out tops on your real code is to adopt SCM. Xcode project snapshots also work.

replacing deprecated methods

Let’s imagine that, for some perverted reason, I’ve written the following tool. No, scrub that. Let’s say that I find myself having to maintain the following tool :-).

#import <Foundation/Foundation.h>

int main(int argc, char **argv, char **envp)
{
NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];
NSString *firstArg = [NSString stringWithCString: argv[1]];
NSLog(@"Argument was %s", [firstArg cString]);
[arp release];
return 0;
}

Pleasant, non? Actually non. What happens when I compile it?

heimdall:Documents leeg$ cc -o printarg printarg.m -framework Foundation
printarg.m: In function ‘main’:
printarg.m:6: warning: ‘stringWithCString:’ is deprecated (declared at /System/Library/Frameworks/Foundation.framework/Headers/NSString.h:386)
printarg.m:7: warning: ‘cString’ is deprecated (declared at /System/Library/Frameworks/Foundation.framework/Headers/NSString.h:367)

OK so we obviously need to do something about this use of ancient NSString API. For no particular reason, let’s start with -cString:

heimdall:Documents leeg$ tops replacemethod cString with UTF8String printarg.m

So what do we have now?

#import <Foundation/Foundation.h>

int main(int argc, char **argv, char **envp)
{
NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];
NSString *firstArg = [NSString stringWithCString: argv[1]];
NSLog@"Argument was %s", [firstArg UTF8String], length);
[arp release];
return 0;
}

Looking good. But we still need to fix the -stringWithCString:. That could be just as easy, replacemethod stringWithCString: with stringWithUTF8String: would do the trick. However let’s be a little
different here. Why don’t we use -stringWithCString:encoding:? If we do that, then we’re going to need to take a guess at the second argument, because we’ve got no idea what the encoding should be (that’s why -stringWithCString: is deprecated, after all. However if we’re happy to assume UTF8 is fine for the output, let’s do that for the input. We’d better let everyone know that’s what happened, though.

So this rule is starting to look quite complex. It says “replace -stringWithCString: with -stringWithCString:encoding:, keeping the C string argument but adding another argument, which should be NSUTF8StringEncoding. While you’re at it, warn the developer that you’ve had to make that assumption”. We also (presumably) want to combine it with the previous rule, so that if we see the original file we’ll catch both of the problems. Luckily tops lets us write scripts, which comprise of one or more rule descriptions. Here’s a script which encapsulates both our cString rules:

replacemethod "cString" with "UTF8String"
replacemethod "stringWithCString:<cString>" with "stringWithCString:<cString>encoding:<encoding>" {
replace "<encoding_arg>" with "NSUTF8StringEncoding"
} warning "Assumed input encoding is UTF8"

So why does the <encoding> token become <encoding_arg> in the sub-rule? Well that means “the thing which is passed as the encoding argument”. This avoids confusion with <encoding_param>, the parameter as declared in the class interface (yes, you can run tops on headers as well as implementations).

Now if we save this script as cStringNoMore.tops, we can run it against our source file:

heimdall:Documents leeg$ tops -scriptfile cStringNoMore.tops printarg.m

Which results in the following source:

#import <Foundation/Foundation.h>

int main(int argc, char **argv, char **envp)
{
NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];
#warning Assumed input encoding is UTF8
NSString *firstArg = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
NSLog(@"Argument was %s", [firstArg UTF8String]);
[arp release];
return 0;
}

Now, when we compile it, we no longer get told about deprecated API. Cool! But it looks like I need to verify that the use of UTF8 is acceptable:

heimdall:Documents leeg$ cc -o printarg printarg.m -framework Foundation
printarg.m:6:2: warning: #warning Assumed input encoding is UTF8

exercises for the reader, and caveats

There’s plenty more to tops than I’ve managed to cover here. You could (and indeed Apple do) use it to 64-bit-cleanify your sources. Performing security audits is another great use – particularly using constructs such as:

replace strcpy with same error "WTF do you think you're doing?!?"

However, notice that tops is a blunter instrument than the Xcode refactoring capability. Its smallest unit of operation is the source file; refactoring only within particular methods is not quite easily achieved. Also, as I said before, remember to check your source into SCM before running a script! There is a -dont option to make tops output its proposed changes without applying them, too.

Finally tops shouldn’t be used fully automated. Always assume that you need to inspect the output carefully, don’t just Build and Go.

Posted in cocoa, nextstep, objc, openstep, xcode | 3 Comments

CocoaHeads Swindon tonight!

For those of you who’ve never explored the delights that the fine city of the Hill of Pigs has to offer, tonight offers an unparalleled opportunity. Come and sit in (or outside, weather permitting) a pub only a short distance from the railway station, and listen to Mike Abdullah speaking about WebKit. As always there’ll also be general NSDiscussion, and the occasional pint of beer. Maps etc. at our cocoaheads.org page.

Posted in cocoa, cocoaheads, webkit | Leave a comment

Just because Brucie says it…

Bruce Schneier claims that shoulder-surfing isn’t much of a problem these days.

Plenty of people discovered “my password” at NSConference, so I disagree :-) (photo courtesy of stuff mc).

Posted in security, usability | 1 Comment

KVO and +initialize

Got caught by a really hard-to-diagnose issue today, so I decided to write it down in part so that you don’t get bitten by it, and partly so that next time I come across the issue, I’ll remember what it was.

I had a nasty bug in trying to add support for the AppleScript duplicate command to one of my objects. Now duplicate should, in principle, be simple: just conform to NSCopying and implement -copyWithZone:. The default implementation of NSCloneCommand should deal with everything else. But what I found was that there’s a class variable (OK, there isn’t, there’s a static in the class implementation file with accessors) with which the instances must compare some properties. And this was empty by the time the AppleScript ran. Well, that’s odd, thought I, it’s only being emptied once, and that’s when it’s created in +[MyClass initialize]. So what’s going on?

Having set a watchpoint on the static, I now know the answer: the +initialize method was being called twice. Erm, OK…why? It’s only called whenever a class is first used. It turns out that there were two classes with the same IMP for that method. The first was MyClass, and the second? NSKVONotifying_MyClass. Ah, great, Apple are adding a subclass of one of my classes for me!

It turns out that TFM has a solution:


+ (void)initialize
{
if (self == [MyClass class])
{
//real code
}
}

and I could use that solution here to fix my problem. But finding out that is the problem was a complete pig.

Posted in applescript, cocoa, objc | 1 Comment

Going indie!

This is sort of a message from the past. I wrote it yesterday, but had people I needed to talk to before I could hit the big old publish button. (Including this bit, so I really wrote it “today”, but the earliest you can read it means that “today” will be “yesterday”. This is one of those uses of the past-perfect-nevertense that blows up lesser recording equipment.)

Today (the real today that this thing was posted), I handed in my notice at Sophos. Six weeks from now, I will be officially an unemployed starving artist. I’m working on lining up a project to take up most of my time for the first few months of the new era, which really looks like it will work out, and of course need to solve the “marketing presence” problem. Although the fact that you’re reading this probably means you already know who I am, and something about what I do. If you want a Cocoa or UNIX developer for a contract – especially one with experience in the worlds of security and scientific computing – then please see my LinkedIn profile to find out a bit more of what I’ve been up to, and drop me a line – here, at @iamleeg or to iamleeg at gmail dot com. I know there are a load of interesting people out there working on a load of interesting projects, one of the great things about WWDC every year is meeting you all and sharing in the excitement. Well hopefully I’ll get to work with you on some of that cool software, too!

So, like many people who go self-employed, I’ve got little idea of what will happen next :-). I’ve got some ideas for apps which I’ll be working on in the (probably too copious) spare time I’ll have. But I’m going to focus on contracting and consulting in the short term. This is going to be an exciting time, if somewhat daunting…but you’ll be able to check on my daunt levels right here, dear readers.

I promised at the turn of the year that there would be lots of blog posts on various tech things during the first half of the year. Unsurprisingly that didn’t quite pan out, and I’m hoping to rectify that over the next couple of months now that I have fewer (perceived) content restrictions on the blog. And this first project I have lined up should certainly be producing some good’uns, assuming it all works out. I’ll be the first to admit that if it doesn’t, I’m heading for trouble very shortly. Which is why I know that it, or something very like it, will work out :-).

To fellow Sophists who are hearing about this for the first time here, I’m very sorry. I tried to let people know today but there are hundreds of you, one of me and lots of loose ends to tie by mid-August. But don’t worry, there will be beer.

Posted in whatevs | 8 Comments

Reverse-engineering stringed instruments

Despite being able to play some instruments, I probably couldn’t do a good job of making any of them. I don’t have the patience required to boil a horse for long enough to stick a fiddle together, for instance. Luthiers would probably get incredibly bored by the following post but for fellow apart-takers, it’ll hopefully be quite interesting.

I once made a stringed synthesiser, when I was at college. The basic principle is that of an electric guitar running in reverse. A metal string is stretched between two bridges, and sits inside a horseshoe magnet. Now rather than plucking the string and letting the magnetic pickup detect the vibrations, we pass an alternating current through the string and use the magnetic field to cause the string to vibrate. Mount the whole shooting match on a soundbox roughly the shape of an appalachian dulcimer, so it makes a decent amount of noise. And there you go!

Well, there bits of you go, anyway. While you can drive the string at any frequency you like, it’ll be really quiet on any note which isn’t a natural harmonic – it’s being forced at one frequency, and trying to vibrate at a bunch of other frequencies, so can’t really resonate. Assuming that the materials of the string aren’t up for grabs, it’s the length and tension which choose the fundamental frequency. What you currently have is capable of playing bugle tunes. Put a few different bugles together and you can play chromatic scales, so putting a few different strings together increases the likelihood that our synthesiser has the ability to play some notes in the tune we want.

In fact, it’s still going to have a fairly nasty volume characteristic, because most of the noise doesn’t come from the string, it comes from the soundbox. In that regard, violins and pipe organs have quite a lot in common. But they differ in that pipe organs have one soundbox per note – the pipe itself – and violins have a single box. So it’d better be possible to get it to resonate at a whole bunch of interesting frequencies, which is one of the reasons for making them (and acoustic guitars) the shapes that they are. Now what the real acoustic characteristics of a fiddle body are, I’m not entirely sure. But what I do know is that a violin is surprisingly small – the “concert pitch” A pipe in an organ is a little under 40cm and the lowest note a violin usually has (a ninth lower) will therefore be almost a metre long. Even though an enclosed box like a violin needs to be half the length of an organ pipe playing the same note, it will still naturally accentuate the higher frequencies that the strings have on offer because it isn’t big enough to do much else. And it’s that which gives the instruments their sound. My synth’s soundbox was cuboid-ish, so had two characteristic “loud” notes and their harmonics. The z-axis wouldn’t have resonated much as the box was on a table which absorbed the momentum.

The remaining interesting point is that the violin is forced to extract the sound from a rubbish part of the string. The bridge is both responsible for translating the motion of the string into the wood and for stopping the string from moving. The string moves most somewhere out toward the middle (it’s mainly vibrating at its natural wavelength, which is twice the length of the string) and not at all near the ends. That’s why pickups on electric guitars sound “warmer” further away form the bridge. There they pick up more of the lower harmonics, but the nearest pickup (and the bridge) get proportionally more of the higher harmonics.

Posted in whatevs | Leave a comment

Beer improves perception of security

…at least, it provides for a nice analogy to use when discussing basic security concepts. I don’t think people necessarily choose better passwords after a skinful, nor do they usually make improved choices of what information to share on social networking sites when returning from the pub. That’s probably why Mail Goggles exists.

So, the attendee beer bash at WWDC. There is beer. There is also the regulatory framework of the state of California, which mandates that minors under 21 years of age may not be supplied with beer. There are also student scholarship places to the WWDC, and no theoretical minimum attendee age. There are also loads of people in the vague area of Yerba Buena Gardens who are not attending the WWDC. But only attendees may visit the bash, and only attendees over 21 may drink beer.

PassportI went to the registration desk at Moscone West on the day before Phil Schiller’s keynote, and identified myself as Graham Lee. “Hi, my name’s Graham Lee” I said to the lady behind the desk. It turns out that’s not sufficient. While I did indeed give the name of someone who was indeed registered to attend the conference, there’s no reason for the lady to believe the identification I gave her. She wants to be able to authenticate my claim, and chooses to rely on a trusted third party to do so. That third party is the British government (insert your own jokes here), and she is happy to accept my passport as confirmation of my identity.

WWDC attendee passNow I am given my attendee badge, a token which demonstrates that I have authenticated as Graham Lee, an attendee at WWDC. When I move around the conference centre to get to the sessions and the labs, the security staff merely need to look for the presence of this token. They don’t need to go through the business of checking my passport again, because the fact that I have my token satisfies them that I have previously had my identity authenticated to the required level.

WWDC beer braceletThe access token would be sufficient to get me in to the attendee beer bash, as it proves that I have authenticated as an attendee. But it does not demonstrate that I am authorised to drink beer. So on the day of the bash I go back to the registration desk and show a different lady my passport again, which indicates that I am over 21 and can therefore be given the authority to drink beer at the bash. I am given the subtle green wristband pictures, which again acts as a token; this time not an identification token but an authorisation token. The bar staff do not care which of the 5200 attendees I am. In fact they do not care about my identity at all, because they know that the security staff have already verified my attendee status at the entrance to the event – therefore they don’t need to see my attendee pass. They only care about whether I’m in the group of people permitted to drink beer, and the wristband shows that I am in that group. It shows that I have demonstrated the credentials needed to gain that particular authority.

So, there we have it. A quick beer of an evening with a few thousand colleagues can indeed turn into a fun discussion of the distinction between authentication and authorisation, and how these two tasks can be carried out independently.

Posted in whatevs | 1 Comment