eyebrowsoffire
eyebrowsoffire

Reputation: 947

NSClassFromString() security concerns

I'm trying to create a factory class structure where my abstract base class, PDObject, instantiates an instance the proper subclass based on information passed to it in an NSDictionary. Here's my init method for PDObject:

- (id)initWithDictionary:(NSDictionary *)dictionary inEnvironment:(PDEnvironment *)environment {
    NSString *className = [dictionary objectForKey:@"objectType"];
    if (className) {
        Class objectClass = NSClassFromString(className);
        if ([objectClass isSubclassOfClass:[PDObject class]]) {
            self = [[objectClass alloc] initWithDictionary:dictionary inEnvironment:environment];
        } else {
            NSLog(@"tried to instantiate an object of the wrong object type");
            self = nil;
        }
    } else {
        NSLog(@"tried to instantiate an object without an object type");
    }
    return self;
}

I'm wondering if anyone knows of any security concerns with this pattern. I'm worried that something malicious could be passed in in the dictionary and instantiate something unexpected. I have a check to make sure that it is a proper subclass of PDObject. Is there anything I should be concerned about here, or am I just being paranoid?

Upvotes: 1

Views: 221

Answers (2)

user529758
user529758

Reputation:

Dynamism is good and I don't see anything particularly risky here. If you want to avoid crashes, you can check for the particular object a. not being nil (just in case) and b. responding to any selector you want to send it. Also note that whichever kind of protection you use, who wants to mock with your app will always be able to do so using library interposition (meet the infamous DYLD_INSERT_LIBRARIES environment variable) and the Objective-C runtime.

Upvotes: 2

bbum
bbum

Reputation: 162712

It is unlikely to be a security hole, but passing potentially random strings to runtime functions isn't really something the runtime is hardened against. The risk isn't instantiating random classes, but causing the app to potentially crash or execute random code.

In general, I wouldn't go beyond minimal effort. To that ends, I would suggest using NSScanner to scan the class name to see if it has any characters that are obviously out of bounds. I would think scanning for alphanumericCharacterSet would be sufficient.

Upvotes: 2

Related Questions