all right so this is Apple's predicament NS predicate exploitation on Mac OS and iOS my name is Austin Emmett and I also go by alkali get into it so a little bit more information about me I'm currently a vulnerability researcher at vigilant labs though the research that I'm going to be presenting today was done while I worked at the Trellix Advanced Research Center I'm also the author of the radius to symbolic execution framework which uses regard to to easily quickly and easily perform symbolic execution and taint analysis on binaries for many different architectures check that out something you're interested in I'm now client sack on Twitter I mean X and I'm alkali info sexy info sec exchange on Macedon all right let's talk about where this all sort of began with the forced entry exploit um I've been obsessed with NS predicates since I read the second part of the project zeros blog post about the forced entry attack which was a exploit chain targeting iOS in 2001 2021. um the first post covered and I messaged exploit that sent a fake gif that was actually a PDF which exploited an integer overflow in the jbig2 image compression codec and it was this absolutely incredible exploit that used the operations on groups of pixels to create an entire virtual machine um oh shoot um the ultimate purpose of this virtual machine was to create and evaluate an NS predicate which sent another another NS predicate to an unsandboxed process while the iMessage exploit received most of the attention I was fascinated by the sandbox escape and these NS predicates these little strings that were capable of defeating all of iOS security so why was I so fascinated the answer is because iOS hacking is hard it's very hard iOS is a hard target because it has common mitigations like ASLR address space layout randomization though on iOS is a little bit limited we'll get to later but more importantly iOS also has other less common mitigations like strict code signing which prevent any dynamically generated code from being executed only code signed with an Apple approved certificate can be run on the device in its normal form of operation also every form of scripting has either been removed like Apple script or heavily sandboxed like the JavaScript engine additionally modern iPhones and Macs have PAC or pointer authentication codes and these are codes made up of the some of the most common mitigations that we've seen in iOS hacking and iOS security the previous the unused top bits of pointers and special instructions set and check them in order to prevent code reuse methods like rapper return return oriented programming so if a function pointer on like the stack or the heap is overwritten these bits will no longer match their expected values and an exception will be raised when it's called via one of those special branch instructions finally apps are in the sandbox with permissions restricted to only what the app needs to function access to sensitive content is often done through IPC with more privileged service processes so all this makes life very difficult for hackers who really want a way to reliably perform arbitrary operations dynamically ideally outside of any sandbox and it turns out that this is exactly what NS product gets get us so in order to understand a little bit more about the security of iOS we have to understand Objective C it's the language that most of the user space code is written in although a lot of new code is written in Swift there's still all these you know old frameworks that are written basically all in Objective C and it's a superset of C with object oriented programming concepts out in a way similar to small talk which is based on message passing where methods are invoked dynamically at runtime by name these names are called selectors and in the parlance of Objective C and methods can be added and removed at runtime as well as have their their types changed it's a very dynamic language at least the the object oriented part of it it's also possible to access properties and call methods without arguments using strings concatenate with periods these strings are called key paths and they're gonna be important in the context of NS predicates this is just like a basic hello world Objective C program it's got nearly all the elements that we're we're gonna care about though so we have this NS string which is the basic immutable string class in Objective C and we call string by appending string method on the string hello with the argument world to get the NS string hello world pretty stuff then we can use the key path string uppercase string utf-8 string to get a C string pointer which can we we can print with printf and the apps in front of the quotes are just like an easy way to create constant NS strings all right so we're nine slides in and I haven't talked about what the hell an NS predicate is yet so I get into that the Apple documentation says they are a definition of logical conditions for constraining a search for a fetch or for in-memory filtering this definition kind of sucks they're simply strings that are used to filter objects and arrays the majority of their use so if you have like a student object you might select students in array with predicates like grade equals 7 or first name like Juan and age less than 16 these strings are actually format strings so you can use a percent and percent escaped strings like like percent sign D to include a number that is passed to predicate with format in order to initialize the NS predicate like pretty tough you know the the NS project also implement NS coding and this means they can be serialized and that allows them to be sent via IPC to other processes or even remotely to other devices and the important thing thing about as predicates is that they're ubiquitous in iOS and Mac OS first-party and third-party code they're used absolutely everywhere they're intertwined with all the software on these devices so we know quick explainer of XPC so expand on that last point let's discuss XPC it's a common form of inter process communication or one process can call methods on a remote object in another process when XPC is used to call a remote method these arguments are passed by the sender they're serialized or archived is what the serialization process is called on iOS and Mac OS and sent to the target where they are deserialized and it's common to see and it's predicate arguments used to filter the results of these remote calls and that's in order to minimize the number of objects that need to be serialized on the sender end and deserialized on the receiver end you this is foreshadowing just in case it wasn't already abundantly clear it's going to become very important that NS predicates are being sent all around VXPC so here's an example of an AS predicate in action just a short little program here where we have an array containing some file names and we use the predicate path extension equals PI to filter it and the resulting array just contains that single entry script dot PI get a little bit deeper into the actual structure of an AS predicates that string is parsed by code generated with flex in the foundation framework into pieces called NS expressions and NS predicate operators so in this example from code colorist a predicate name equals Apple was parsed into three pieces the NS keypath expression name equals equals and s equality predicate operator and the NS constitutive area where WE어요 ね value containing the single constant string apple. And the keypath expression is also a function expression, which means it can be further broken down into an operand, which is self, showing that it acts on the objects being filtered, the selector, which is value for key, and that keypath specifier, which is just name. This is all a bit complicated, but it's not really necessary to understand this AST structure. More important for us is the question of what can an NS predicate do? And the answer to that question is anything, sort of. It used to be anything, but now there's a big asterisk, since Apple has taken many steps to make NS predicates much less powerful, less useful for exploitation. In fact, nearly all the techniques I'm going to talk about today no longer work as they're going to be presented, but we'll take a look at NS predicates as they were at this time. And at the limits of what could be done with them. So while at first glance NS predicates don't look very interesting, they're actually a powerful scripting language. As CodeColor has said in his blog post, See No Eval, NS predicates are essentially the eval function for Objective-C. And this scripting capability comes largely from the function keyword, which allows any method to be called on any object with any number of arbitrary arguments. CodeColor has also discovered that the cast keyword. It could be used with the class as the second argument in order to get a reference to any class essentially functioning like NS class from string. It's just a function, you know, if you've programmed much Objective-C. An interesting thing to note is that this functionality is both intended and very old. Function expressions were added in Mac OS 10.5 around the year 2007, and that means that they've been in iOS since the very beginning. This is official Apple documentation. Showing how to use function expressions. So they were never a secret. With the cast class trick, it was also possible to use these helpful classes like CN file services, which had the DLSIM method to get a path signed address to any exported function. This address could be called with NS invocation, which has a method invoke using imp, and that could be used to call the function with any number of arbitrary arguments as well. So effectively, both the object-oriented methods. Of Objective-C could be used, and also any exported simple C function could be called without restriction. That means that anything that could be done in a normal Objective-C program could be done completely dynamically within this NS predicate string. And this allows us to completely sidestep ASLR, code signing, and pack all those mitigations that I talked about in the beginning that makes iOS so secure. So this was beautiful. For hackers. Thank you. Not for people that want their devices secure. So the syntax of NS predicate. So until now, the only NS predicates we've seen have been like first name equals one. So it's understandable if you're confused about how NS predicates could be used as a scripting language. But they actually have a surprisingly rich syntax that's capable of representing all the concepts that we would want in a scripting language. And that includes variables and variable setting. Using these. The dollar sign strings. There's also function and keypath expressions that we've talked about a little bit. But there's also this important type of function expression, which is those that don't need to use the function keyword. Like now and some. And these are selectors on the NS predicate utilities class. And they provide these kind of useful auxiliary methods for within a predicate. But we'll see that it's possible to use any valid select. Or within the syntax. And that's going to be useful for both getting a reference to the NS predicate utilities class. And we'll see some other uses of it later too. Then there are NS aggregate expressions, which are meant to be used for arrays. But which we can also use to create series of expressions that will be evaluated sequentially. Which will effectively act as the lines of our script. Finally subquery and ternary expressions can be used to create loops and conditionals respectively. Respectively for a control flow. And additionally, all the normal arithmetic and bitwise math operators can be used in NS predicates. And we'll see that become super useful for calculating addresses. This is a PyObjectiveC script. So it's just ObjectiveC bindings for Python, or Python bindings for ObjectiveC. And it evaluates an NS predicate script. So this script makes two variables. Standard in. Standard out. And proc info, which is a file handle and the process information respectively. And these objects are instantiated using the cast class trick. It then uses a ternary expression as an if statement. So that if the process name is Python, it prints out it's Python to standard out. All these expressions are wrapped in brackets so that they form a single NS aggregate expression. And each line here is evaluated. So for a more complicated example, it's probably a little hard to see, but this is a brainfuck interpreter made entirely within the evaluation of a single NS expression. And it uses all the things that we've seen so far. It's just a little larger. It uses the cast class trick again to get those file handle references to standard in and out. It uses ternary expressions for control flow. It checks whether the program has ended or what the current operation is. And it evaluates itself recursively in order to perform unbounded loops. So instead of doing this recursive evaluation, I could have used a subquery expression. But then it would have been bounded. So it was easier to use recursive evaluation in this case to do the looping. So before forced entry, these NS predicate scripts were essentially unrestricted. With the exception of predicates that were sent over XPC. And these predicates were often limited using something called NS predicate visitors. Implementations of a protocol that has methods to check what the components of an untrusted NS predicate were and if they were safe to evaluate. These implementations use the expression type property to check what those expressions were. And if they were a function or a key path, then it would potentially only allow certain specific instances of those expressions. So a limited set of selectors or a limited set of key paths. However, without these restrictions, NS predicates were basically arbitrary code execution. And they were used as such in that forced entry sandbox escape. Now that we understand a little bit more about NS predicates and their capabilities, we can understand that forced entry sandbox escape. That crazy JBIG2 VM made a fake object in memory that when deallocated evaluated a series of NS function expressions. And these expressions cleaned up after the initial exploit by deleting that fake gif file. And they crafted another payload. Another array of objects that was sent to the unsandboxed comm center process. These objects were chosen such that when the target de-sealized them, they would immediately evaluate a new NS predicate, which collected a bunch of device information before downloading and evaluating another NS predicate payload. Thank you. Thank you. Thank you. Thank you. Thank you. Thank you. After forced entry and the increased visibility of CodeColor's earlier blog post, a few new restrictions were placed on NS predicate objects. Two denialists were added, which prevented the use of a number of inherently dangerous classes and methods with particular focus on methods, classes and methods that allowed performing arbitrary method invocations and initializing arbitrary objects. The cast class trick was forbidden. hidden, and calling class methods as opposed to instance methods of objects was prevented. However, it's important to note that most of these changes only affected first-party Apple apps and processes, and as predicates evaluated in third-party apps had a much smaller denialist of classes and methods, and were for the most part just as powerful as before. This difference was implemented through a flag value, a single flag value called predicate security flags that was set for Apple processes when the class NSPredicateUtilities was initialized. So here we can see some of that denialist. This is the denialist of classes. So all these classes were prevented from being used, and it includes things like NSBundle, which is used to load other shared libraries. And NSCoder, which prevents deserializing new arbitrary objects, again, trying to limit the number of the different objects that you could use within an NSPredicate. Additionally, Apple removed the CN file services DLSIM method that was used both in NSPredicate and slop exploits, so that's selector-oriented programming. It was just another type of exploitation technique on iOS. And this method improved. It proved to be very helpful for attackers, so it was unfortunate for us when it was removed. Relatedly, innocent vacation was hardened, and it was also included in that list of forbidden classes and made generally more difficult to use for exploits. However, as we shall see, the denialists were way, way, way too small. And the fact that security was enforced based on this single writable flag value made it incredibly vulnerable. It was incredibly fragile. The get value method of NSValue wasn't on the forbidden list and could be used to perform arbitrary writes, overwriting any address with any desired value. And this meant that the security flag could just be unset by simply calling get value on the number zero with the address of the security flag as the argument. Importantly, even though iOS has ASLR, libraries are all slid by the same amount in every process, with the slide being chosen at startup. And so if you already had code execution in one process, you knew all the addresses of everything. Additionally, there are many different ways to leak the address from within a predicate itself, so it's trivial to use an offset from a known address to find that flag 100% reliably. Similarly, the lengths of the denialists could just be set to zero. And that would remove any remaining forbidden elements, because they would check the list of forbidden classes and methods, the list would be zero length and say, oh, it's not on there. So all these techniques described in the previous slides can be seen in this predicate, which disables all the security mitigations that have been introduced to predicates. First we use the self.hash to get the address of the NSPredicateUtilities class. So that hashtag self parentheses, that gets referenced to NSPredicateUtilities, and then the .hash just converts it into an NSNumber for us. With this, we can use offsets from this address. To get the addresses of the security flags and the lengths of the denialists. And then once we have those addresses, we can simply use getValue to overwrite them, reverting NSPredicates to their previous fully unrestricted state. And here we can also see what I call the MVP of NSPredicate scripts, which is non-retained object value. So this is just a method that takes an NSNumber and treats it as a pointer to an object instead. It's kind of like dereferencing in the context of NSPredicate and can be used to access any class by reference. When the cast class trick is forbidden, it's just super useful. However, after a tweet of mine that might or might not have influenced Apple about how easily the previous mitigations were bypassed, Apple struck back and they added restrictions to the argument types in function expressions to exclude pointer types. Every objective C method has a signature, which is the string of characters denoting the types of arguments and the return value of the method. And in that signature, the caret and the question mark characters represent data and function pointers, respectively. And these were the types that were forbidden within function expressions. Additionally, the predicate security flags and denialist code were moved into the core foundation framework. And the predicate security flags were now placed on the heap where they could be harder to locate so that it wasn't quite as easy to overwrite them. And many new entries were added. Unfortunately, for me, Apple overlooked the asterisk type, which refers to C string pointers. This type really shouldn't exist and should just be denoted as caret C, but it worked out for me here that it does exist. And this means that we could simply achieve the same kind of arbitrary write using get C string instead of the get value method. And once again, NSPredakits could perform. Arbitrary operations. So this is the predicate that accomplishes the same thing as the previously one shown. However, it uses the function set debug predicate security scoping to unset the high security flag after setting the internal release type to three. And this is a trick that's necessary because as I said before, the predicate security flag was moved to the heap. But luckily, NSPredicate utilities just gave us this nice convenient method to unset it. So yeah. Cool. All right. So here is that set debug predicate security scoping method. And this is the one that unsets the high security flag that's on the heap. And so that flag is now stored in the third bit of the CF predicate policy data, plus OX 30 offset. But this method can only unset it if OS variant has internal content returns true. And this is what we accomplished before by setting that internal release type to three. All right. So that's what we did in the previous predicate. So that's what that internal value is there that's being set to three. So while I've demonstrated how to get around the limits that were placed on NSPredicate, I still haven't shown how arbitrary functions, arbitrary native C functions could be called now that the previous DLSim gadget has been removed. Luckily there's still at least one signed reference to DLSim that we could get using the DLSim func method of a class in the DVT Instruments Foundation framework. So that's what we've done. This address could be used with the apply function info method of rbstroke accumulator from the RenderBox framework to call DLSim and also to call all of the returned function pointers that are all signed with that zero context value for pack. So those function pointers, those signed function pointers could be called with apply function info with up to four arbitrary arguments. Four more. If it was okay that that fifth argument was not controlled you could control all the rest. So this effectively bypasses pack as even though it's not possible to sign arbitrary pointers as you would want for like a troop bypass, the combination of the scripting capabilities within the NSPredicate and the ability to use any exporter function was basically more than enough to accomplish any desired goal. Unfortunately Apple has been cracking down on all remaining references to DLSim that you could get in this manner. And this DLSim func method is no longer available in iOS 16.5 or later. So this is that apply function method. As we can see it uses the BRAAZ instruction to call the function pointer passed as that first argument. And this instruction authenticates and calls pointers signed with a zero context value which is exactly what we need in order to use that reference to DLSim and use all the function pointers that that method returns. Putting all the pieces together, this is an NSPredicate that calls nslog on iOS 16.3 after removing all the mitigations protecting Apple processes. It's probably too small to see but the point is that it's very complicated but it's still possible to do anything within an NSPredicate in this version. All it takes is some creativity, some knowledge of Objective C and some useful classes that are already defined in the shared libraries of iOS. And macOS. Now that we can do anything within an NSPredicate, similar to what was possible before forced entry, there's only one potential impediment to exploiting processes that evaluate untrusted NSPredicates. And that's the NSPredicate visitors that I covered before. And this is the most surprising thing about this research, is that I found that you can just say no to NSPredicate visitors. visitors. Each daemon implements their own version of this protocol in order to only allow those expressions that it expects to be in the NSPredicates that daemon receives. And it uses the expression type property to check what kind of expression each component of a predicate is, so that simple expressions like constant values can be allowed and more dangerous ones like function and keypath expressions could be forbidden or limited to a certain safe subset. However, the expression type was just an integer that was read directly from the serialized data sent by an untrusted process. And this meant that setting every expression type to zero in a malicious NSPredicate led the receiver to interpret it as only containing constant values and that bypassed all additional validation. So here's an example of an NSPredicate visitor implementation for the photo library queries. We can see that it uses the expression type to decide whether additional checks need to be made on the expression that it visits. So here it checks to see if it's a keypath expression and it gets the keypath and then it later checks it against a list of known good keypaths. And on the XML on the right here, this shows the serialized representation of the expression on the left. And we can see that the expression type is just an integer within this XML. And this is... XML is controlled entirely by the NSPredicate. And this is the XML that the NSPredicate is actually by the sender. So they can just set it to whatever they want. And this is the actual code of initWithCoder. It's probably like impossible to read. Yeah. But it's just reading out that NSExpressionType field and passing it to NSExpressionInitWithExpressionType. You're just going to have to trust me if you can't read it that that's how it works. So many different daemons could be exploited using this bypass. So it includes Cordo at D, ContextStore D, and they just aggregate information about user behavior on the device, as well as AppStore D, which can be used to install arbitrary apps. They still have to be signed, though. OS Log Service, which is accessible by any app and can access any logs potentially containing sensitive information. And on iPadOS Springboard, which is the home app that... It's kind of like explored IEXE on Windows. It's kind of like that background app. So using these vulnerabilities, malicious apps could gain access to app location and notification data, including message contents, and potentially even install arbitrary apps on the target device and on paired devices. It's pretty simple to find these XPC service clients that send predicates, like this one, which is CD Interaction Recorder by grepping the Objective-C headers. And that's the great thing about release. It that there's a lot of data in there that I don't want to send, I don't want to return it. I'd rather reversing Objective-C libraries and apps is that they have to contain this header information because that's how the dynamic dispatching of methods works. So here we can see many methods that take NSPredicate arguments, and these arguments are sent to the CoreDuetD service. And this is a free descript, which when attached to a process that has the entitlements to communicate with CoreDuetD, sends an NSPredicate that will cause a crash on access to OX4141As. It uses the method countContacts using predicateError, which takes a predicate argument and sends it to CoreDuetD. And by calling this method this function expression and having its expression type set to zero, we can bypass the NSPredicate visitor that CoreDuetD uses. On the iPad, any app can communicate with a Springboard XPC service that determines which app scene should be used for handling different types of events, and this is done using an NSPredicate provided by the app. This predicate is validated with UITargetContentIdentifierPredicateValidator, that's a mouthful, but like the others, this visitor will relies on the expression type value to determine whether expressions are safe and therefore it can be bypassed. By using a malicious predicate visitor, we can construct any NSPredicate and use the visitor to set all the, you know, its expression types to be zero, denoting constant values, so we can actually use our predicate visitor to defeat other predicate visitors. This is the actual predicate that we're going to use to exploit Springboard. So first it uses getCstring to perform the arbitrary writes needed to clear the denialists and set the internal release type to three, then it calls the setDebug predicate security scoping, which unsets that high security flag. Finally, it uses NSFileManager, which was previously on that forbidden class list, and it uses it to copy the contents of the user notifications directory to the crash report directory so that we can copy them off the device. In a real scenario, they would be, like, zipped up and sent over HTTP to an attacker-controlled server. There's lots of classes that'll help you do that. But just for our purposes here, it's simpler to just do this. The predicate then accepts our evil NSPredicate visitor, which sets all the expression types to zero. And finally, the predicate is assigned to the scene activation conditions, which is what sends it to Springboard to be evaluated when an event, like opening the app, is generated. Okay, so I think, like, this isn't gonna work. Or it is gonna work. No, not really. Hold on one second. Oh, there we go, cool. I think it's good, right? No. All right, so here is a demo of exploiting this Springboard vulnerability. So on the left, we have our script that's just waiting to receive the notifications from the malicious process. On our right, we saw that we're running iOS 16.0. And we can see that we have a notification that says, shh, this is a secret. And we're gonna open our malicious app, which has the helpful link, steal notifications. And then we will see that our notifications are stolen. They're on the left. It's kind of small. I should have made it bigger. But it stole the notifications. Cool. All right, come back. Hey, yeah. All right, so the conclusion. Luckily for the security of iOS and macOS devices, Apple has finally begun to limit NSPredicates in ways that are less easily bypassed. So now the return and argument types of function expressions must be objects, even in third-party apps. And there's no flag that can be overwritten to change this. Predicates could still be used by malicious apps to bypass any kind of meaningful app store review. So they're still very useful in a context where the attacker can control, you know, that environment. And I don't think that they are looking out for this type of evaluation of dynamic NSPredicates in app store review because it's actually something that Apple does within their own processes. Okay. So until Apple makes fundamental changes to both the behavior of function and keypath expressions, they're still going to be very useful to exploitation. So for the foreseeable future, they will still be dangerous. There'll still be landmines scattered everywhere within the code of iOS and macOS waiting to explode, destroying the effectiveness of all the amazing security mitigations on these devices. And they remain Apple's predicament. Thank you.