Out of Hanwell

October 17, 2007

Don’t Steal My Parameters

Filed under: Humor/Mental Leisure, JavaScript — Matthias Miller @ 1:33 pm

I was perusing the source code for Dean Edwards’ base2 library when I discovered that functions can access the parameters of other functions in the call stack. My mind immediately started spinning, imagining the convoluted code this would allow.

Here’s one to get you started:

function checkArgTypes(/*expected types*/) {
    var callerArgs = arguments.callee.caller;
    if (callerArgs.length !== arguments.length) {
        throw new Error('checkArgTypes does not have enough arguments.');
    }

    for (var i = 0; i < arguments.length; i++) {
        if (typeof callerArgs[i] !== arguments[i]) {
            throw new Error('Argument ' + (i+1) + ' is of type ' + typeof callerArgs[i] + ' but should be of type ' + arguments[i] + '.');
        }
    }
}

function run(str, num, bool) {
    checkArgTypes('string', 'number', 'boolean');
}

You might want to try it out in jconsole.

And, of course, you can’t ignore the obligatory security implications:

function validateUser(username, password) {
    /* accidentally call trojan function */
    trojan();
}

function trojan() {
    alert('Your password is ' + validateUser[1] + '.');
}

validateUser('user', 'secret');

Ahh, well. I’d best get back to writing real code.

NOTE: Edited to fix WordPress source code formatting problem.

Update: Fixed a typo in my “for” loop. (Thanks Philippe!)

About these ads

3 Comments »

  1. Hi Matthias

    Thank you for sharing this.

    Though, I realize you make one more loop with the <= comparison in your for loop.

    Cheers!

    Comment by Philippe Rathe — December 13, 2007 @ 6:48 pm

  2. in second snippet:
    shouldn’t it be validateUser.arguments[1] ?!

    regards

    Comment by Friedemann Altrock — February 28, 2008 @ 10:55 pm

  3. If you have trojan Javascript replacing functions called by your validateUser function you’re already screwed, since trojan code can just as easily replace validateUser itself. So there isn’t really a security issue here.

    Comment by Mr. Shiny & New — August 19, 2008 @ 7:01 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: