Apple’s Secure Coding Guide documentation provides guidance on:
- format string attacks
- buffer overflows
What is not clear (to me, anyway) is how to prevent format string attacks and buffer overruns when using NSString.
How do I go about defending against such attacks?
Are there any categories I can apply to protect against this?
Is there a “secure” NSString equivalent I can use?
Buffer overruns are generally not a problem when you are putting data into an
NSString(or anNSMutableString), because when you create anNSString, you have to tell it how much data you are giving it, and it automatically allocates enough private storage to hold what you give it. Just stick to the published APIs and don’t try any shenanigans like casting awayconstfrom a pointer returned byUTF8Stringand writing through the pointer.Note that
NSMutableData, unlikeNSMutableString, provides themutableBytesmessage, which returns a pointer to memory that you are allowed to write to. So if you’re using that API, you do have to be careful about buffer overruns.For format strings, you just have to follow the advice in that document. For example, never pass data from an untrusted source as the format argument, or even as part of the format argument. Generally your format strings should either be string literals or they should be returned from
NSLocalizedString.There’s no “secure” version of
NSString.