Using memset to clear out Swift String

I have a security requirement to zero out certain segments of memory and one of those are Strings under certain circumstances.


Grabbing the UnsafeMutablePointer<Void> of a String struct, one could invoke memset. The issue then becomes, once you 0 out the value you have random crashes due to the header being zero'd out.


Larger issues are due to the fact String is completely overengineered. Grabbing the root _StringCore could have lended itself to doing this - but alas it's memory addresses are "0x0"


Are there means to do this?

Replies

I have a security requirement to zero out … Strings under certain circumstances.

It’s basically impossible to meet this requirement. By using low-level code you can guarantee to zero out your copy of a string, but if you ever pass that string to (or get that string from) any framework code then it’s likely that the framework will make a copy and there’s no way for you to zero out those copies. Most security-critical APIs on our platforms (Security framework, Foundation networking, secure text input, and so on) are built on top of {NS,CF}String, and thus are subject to this limitation.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Yeah, sadly this was possible with just Objective C. I guess this is more a question for evaluators of the security. We've been able to play around with a few things to avoid having keys/password data in long term memory, but having an easy "clean" method for String variables seems impossible.

The platform implementation of these things isn't a concern as evaluators are evaluating the platform specific technologies. It just comes to "our code."


Thanks.

Yeah, sadly this was possible with just Objective C

It was? How?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Well, you can with CoreFoundation. You can create a CFStringRef with your own memory allocator and deallocator. Your deallocator implements a callback when the string is dealloced. Then you are able to zero out the string when it is dealloced. However, the same limitation you mentioned applies. If you hand it to a framework that you didn't write, there's no control over whether or not it makes a copy.

You can create a

CFStringRef
with your own memory allocator and deallocator.

Right. But what’s the point having a

CFString
/
NSString
/ Swift
String
if you’re not using them with system frameworks? If all the code that touches your string is under your control, you don’t need Apple’s string abstractions at all.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"