how to address the security concern of having an N

2019-07-20 19:42发布

问题:

I'm using mailcore2 which is all block based. Typically they define an operation like so

SomeMailCoreOp *op = [session getOp];
[op start:^(NSError* error, id result) {
    if (error) {
        // handle error code            
    }    
}];

So what I wanted to do is basically simply throw an NSException every time an error is encountered.. so that I can catch it somewhere else in my code base.. So I created a category for NSError:

@implementation NSError (Addons)

-(NSString *)description {
    return [NSString stringWithFormat:@"%@ - %@",
            [self localizedDescription], [self localizedFailureReason]];        
}
@end

and this is how I would like to typically handle errors:

SomeMailCoreOp *op = [session getOp];
[op start:^(NSError* error, id result) {
    if (error) {
        [NSException raise:@"failure" format:[error description]];            
    }    
}];

I thought this makes sense since in the documentation for NSException they got this for format:

format, A human-readable message string (that is, the exception reason) with conversion specifications for the variable arguments that follow.

yet I always get this compiler warning when I do the above:

format string is not a string literal (potentially insecure)

how do I get around this?

回答1:

format is a format string, like in NSLog() or [NSString stringWithFormat:]. In your case

[NSException raise:@"failure" format:@"%@", [error description]];

will not produce the warning. Have a look at the Apple Docs for formatting string objects for more information.

For more information why having a non-literal string as the format is insecure, see Uncontrolled format string on Wikipedia

Note that Apple discourages the use of Exceptions for flow-control:

From Cocoa Core Competencies:

Although exceptions are commonly used in many programming environments to control programming flow or to signify errors, do not use exceptions in this way in Cocoa and Cocoa Touch applications. Instead, you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object.

From Dealing with Error:

If you’re coming from other platforms and languages, you may be used to working with exceptions for the majority of error handling. When you’re writing code with Objective-C, exceptions are used solely for programmer errors, like out-of-bounds array access or invalid method arguments. These are the problems that you should find and fix during testing before you ship your app.