How to solve security problem when using NSException format, use non-literal literal

I use mailcore2 , which is blocky. Usually they define such an operation

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

So, what I wanted to do was just to simply throw an NSException every time an error occurs .. 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 I would like to handle errors as a rule:

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

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

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

but I always get this compiler warning when I do this:

 format string is not a string literal (potentially insecure) 

how do i get around this?

+2
source share
1 answer

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

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

will not issue a warning. For more information, check out Apple Docs to format string objects .

For more information about why having an unprofitable string as a format is unsafe, see Uncontrolled format string on Wikipedia

Please note that Apple does not recommend using Exclusions for flow control:

From Cocoa Core Competencies :

Although in many programming environments, exceptions are used to control the programming flow or to indicate 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 the error object.

From Work with error :

If you came from other platforms and languages, you can use to work with exceptions for most of the error handling. When you write code using Objective-C, exceptions are used exclusively for programmer errors, such as accessing an array outside the bounds or invalid method arguments. These are the problems that you must find and fix during testing before submitting your application.

+4
source

Source: https://habr.com/ru/post/1495636/


All Articles