Objective-C secure coding¶
Objective-C applications mix Foundation objects with native APIs and runtime features. That makes boundaries around formatting, selectors, WebViews and deserialization particularly useful review points. This guide uses Foundation on macOS or iOS to show a format-string mistake that can appear even in otherwise memory-managed code.
Separate the format from the text¶
Assume userText is a non-null NSString that came from an untrusted source. The application wants to create a display string containing exactly that text.
Unsafe: interpret the input as formatting instructions.
NSString *display = [NSString stringWithFormat:userText];
Safer: use a constant format and pass the input as a value.
NSString *display = [NSString stringWithFormat:@"%@", userText];
The format specifier belongs to the developer-owned string. Any percent characters inside userText stay inside the argument rather than becoming additional format directives. When no formatting is necessary, using the original string or an appropriate copy is simpler still. Apple describes format arguments in Formatting String Objects.
The same review applies to logging and C formatting APIs. Avoid logging credentials, personal information or complete request bodies even when formatting is safe. A formatting fix does not escape HTML: if the result goes into a WebView, apply the policy appropriate to that HTML or JavaScript context.
Check the fix¶
Run only the safer implementation with the harmless input Demo %@ label. Assert that the resulting string equals the input exactly. Repeat with an ordinary name, an empty string and Unicode characters. Do not execute the unsafe version with formatting tokens simply to demonstrate a crash; the constant-format regression check is enough to preserve the intended behavior.
Review composite format strings, WebView XSS, insecure deserialization and TLS certificate validation. Pay particular attention when user input selects a class, selector or file path dynamically.
These examples explain source-review concerns. A deprecated API or suspicious call is a reason to inspect context; it is not automatic proof of exploitability, and language support does not guarantee every native code path was analyzed.