Skip to content

Commit 72e32c2

Browse files
carlospolopgitbook-bot
authored andcommitted
GITBOOK-4346: No subject
1 parent a241844 commit 72e32c2

File tree

3 files changed

+205
-2
lines changed

3 files changed

+205
-2
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138

139139
* [macOS Security & Privilege Escalation](macos-hardening/macos-security-and-privilege-escalation/README.md)
140140
* [macOS Apps - Inspecting, debugging and Fuzzing](macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/README.md)
141+
* [Objects in memory](macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/objects-in-memory.md)
141142
* [Introduction to x64](macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/introduction-to-x64.md)
142143
* [Introduction to ARM64v8](macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md)
143144
* [macOS AppleFS](macos-hardening/macos-security-and-privilege-escalation/macos-applefs.md)

macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,8 @@ Parameters ([more info in the docs](https://developer.apple.com/documentation/ob
377377

378378
So, if you put breakpoint before the branch to this function, you can easily find what is invoked in lldb with (in this example the object calls an object from `NSConcreteTask` that will run a command):
379379

380-
```
380+
```bash
381+
# Right in the line were objc_msgSend will be called
381382
(lldb) po $x0
382383
<NSConcreteTask: 0x1052308e0>
383384

@@ -395,9 +396,29 @@ whoami
395396
```
396397

397398
{% hint style="success" %}
398-
Setting the env variable `NSObjCMessageLoggingEnabled=1` it's possible to log when this function is called in a file like `/tmp/msgSends-pid`.
399+
Setting the env variable **`NSObjCMessageLoggingEnabled=1`** it's possible to log when this function is called in a file like `/tmp/msgSends-pid`.
400+
401+
Moreover, setting **`OBJC_HELP=1`** and calling any binary you can see other environment variables you could use to **log** when certain Objc-C actions occurs.
399402
{% endhint %}
400403

404+
When this function is called, it's needed to find the called method of the indicated instance, for this different searches are made:
405+
406+
* Perform optimistic cache lookup:
407+
* If successful, done
408+
* Acquire runtimeLock (read)
409+
* If (realize && !cls->realized) realize class
410+
* If (initialize && !cls->initialized) initialize class
411+
* Try class own cache:
412+
* If successful, done
413+
* Try class method list:
414+
* If found, fill cache and done
415+
* Try superclass cache:
416+
* If successful, done
417+
* Try superclass method list:
418+
* If found, fill cache and done
419+
* If (resolver) try method resolver, and repeat from class lookup
420+
* If still here (= all else has failed) try forwarder
421+
401422
### Shellcodes
402423

403424
To compile:
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
# Objects in memory
2+
3+
<details>
4+
5+
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
6+
7+
Other ways to support HackTricks:
8+
9+
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
10+
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
11+
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
12+
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
13+
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
14+
15+
</details>
16+
17+
## CFRuntimeClass
18+
19+
CF\* objects come from CoreFOundation, which provides more than 50 classes of objects like `CFString`, `CFNumber` or `CFAllocatior`.
20+
21+
All these clases are instances of the class `CFRuntimeClass`, which when called it returns an index to the `__CFRuntimeClassTable`. The CFRuntimeClass is defined in [**CFRuntime.h**](https://opensource.apple.com/source/CF/CF-1153.18/CFRuntime.h.auto.html):
22+
23+
```objectivec
24+
// Some comments were added to the original code
25+
26+
enum { // Version field constants
27+
_kCFRuntimeScannedObject = (1UL << 0),
28+
_kCFRuntimeResourcefulObject = (1UL << 2), // tells CFRuntime to make use of the reclaim field
29+
_kCFRuntimeCustomRefCount = (1UL << 3), // tells CFRuntime to make use of the refcount field
30+
_kCFRuntimeRequiresAlignment = (1UL << 4), // tells CFRuntime to make use of the requiredAlignment field
31+
};
32+
33+
typedef struct __CFRuntimeClass {
34+
CFIndex version; // This is made a bitwise OR with the relevant previous flags
35+
36+
const char *className; // must be a pure ASCII string, nul-terminated
37+
void (*init)(CFTypeRef cf); // Initializer function
38+
CFTypeRef (*copy)(CFAllocatorRef allocator, CFTypeRef cf); // Copy function, taking CFAllocatorRef and CFTypeRef to copy
39+
void (*finalize)(CFTypeRef cf); // Finalizer function
40+
Boolean (*equal)(CFTypeRef cf1, CFTypeRef cf2); // Function to be called by CFEqual()
41+
CFHashCode (*hash)(CFTypeRef cf); // Function to be called by CFHash()
42+
CFStringRef (*copyFormattingDesc)(CFTypeRef cf, CFDictionaryRef formatOptions); // Provides a CFStringRef with a textual description of the object// return str with retain
43+
CFStringRef (*copyDebugDesc)(CFTypeRef cf); // CFStringRed with textual description of the object for CFCopyDescription
44+
45+
#define CF_RECLAIM_AVAILABLE 1
46+
void (*reclaim)(CFTypeRef cf); // Or in _kCFRuntimeResourcefulObject in the .version to indicate this field should be used
47+
// It not null, it's called when the last reference to the object is released
48+
49+
#define CF_REFCOUNT_AVAILABLE 1
50+
// If not null, the following is called when incrementing or decrementing reference count
51+
uint32_t (*refcount)(intptr_t op, CFTypeRef cf); // Or in _kCFRuntimeCustomRefCount in the .version to indicate this field should be used
52+
// this field must be non-NULL when _kCFRuntimeCustomRefCount is in the .version field
53+
// - if the callback is passed 1 in 'op' it should increment the 'cf's reference count and return 0
54+
// - if the callback is passed 0 in 'op' it should return the 'cf's reference count, up to 32 bits
55+
// - if the callback is passed -1 in 'op' it should decrement the 'cf's reference count; if it is now zero, 'cf' should be cleaned up and deallocated (the finalize callback above will NOT be called unless the process is running under GC, and CF does not deallocate the memory for you; if running under GC, finalize should do the object tear-down and free the object memory); then return 0
56+
// remember to use saturation arithmetic logic and stop incrementing and decrementing when the ref count hits UINT32_MAX, or you will have a security bug
57+
// remember that reference count incrementing/decrementing must be done thread-safely/atomically
58+
// objects should be created/initialized with a custom ref-count of 1 by the class creation functions
59+
// do not attempt to use any bits within the CFRuntimeBase for your reference count; store that in some additional field in your CF object
60+
61+
#pragma GCC diagnostic push
62+
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
63+
#define CF_REQUIRED_ALIGNMENT_AVAILABLE 1
64+
// If not 0, allocation of object must be on this boundary
65+
uintptr_t requiredAlignment; // Or in _kCFRuntimeRequiresAlignment in the .version field to indicate this field should be used; the allocator to _CFRuntimeCreateInstance() will be ignored in this case; if this is less than the minimum alignment the system supports, you'll get higher alignment; if this is not an alignment the system supports (e.g., most systems will only support powers of two, or if it is too high), the result (consequences) will be up to CF or the system to decide
66+
67+
} CFRuntimeClass;
68+
```
69+
70+
## Objective-C
71+
72+
### Memory sections used
73+
74+
Most of the data used by ObjectiveC runtime will change during the execution, therefore it uses some sections from the **\_\_DATA** segment in memory:
75+
76+
* **`__objc_msgrefs`** (`message_ref_t`): Message references
77+
* **`__objc_ivar`** (`ivar`): Instance variables
78+
* **`__objc_data`** (`...`): Mutable data
79+
* **`__objc_classrefs`** (`Class`): Class references
80+
* **`__objc_superrefs`** (`Class`): Superclass references
81+
* **`__objc_protorefs`** (`protocol_t *`): Protocol references
82+
* **`__objc_selrefs`** (`SEL`): Selector references
83+
* **`__objc_const`** (`...`): Class `r/o` data and other (hopefully) constant data
84+
* **`__objc_imageinfo`** (`version, flags`): Used during image load: Version currently `0`; Flags specify preoptimized GC support, etc.
85+
* **`__objc_protolist`** (`protocol_t *`): Protocol list
86+
* **`__objc_nlcatlist`** (`category_t`): Pointer to Non-Lazy Categories defined in this binary
87+
* **`__objc_catlist`** (`category_t`): Pointer to Categories defined in this binary
88+
* **`__objc_nlclslist`** (`classref_t`): Pointer to Non-Lazy Objective-C classes defined in this binary
89+
* **`__objc_classlist`** (`classref_t`): Pointers to all Objective-C classes defined in this binary
90+
91+
It also uses a few sections in the **`__TEXT`** segment to store constan values of it's not possible to write in this section:
92+
93+
* **`__objc_methname`** (C-String): Method names
94+
* **`__objc_classname`** (C-String): Class names
95+
* **`__objc_methtype`** (C-String): Method types
96+
97+
### Type Encoding
98+
99+
Objective-c uses some mangling to encode selector and variable types of simple and complex types:
100+
101+
* Primitive types use their first letter of the type `i` for `int`, `c` for `char`, `l` for `long`... and uses the capital letter in case it's unsigned (`L` for `unsigned Long`).
102+
* Other data types whose letters are used or are special, use other letters or symbols like `q` for `long long`, `b` for `bitfields`, `B` for `booleans`, `#` for `classes`, `@` for `id`, `*` for `char pointers` , `^` for generic `pointers` and `?` for `undefined`.
103+
* Arrays, structures and unions use `[`, `{` and `(`
104+
105+
#### Example Method Declaration
106+
107+
{% code overflow="wrap" %}
108+
```objectivec
109+
- (NSString *)processString:(id)input withOptions:(char *)options andError:(id)error;
110+
```
111+
{% endcode %}
112+
113+
The selector would be `processString:withOptions:andError:`
114+
115+
#### Type Encoding
116+
117+
* `id` is encoded as `@`
118+
* `char *` is encoded as `*`
119+
120+
The complete type encoding for the method is:
121+
122+
```less
123+
@24@0:8@16*20^@24
124+
```
125+
126+
#### Detailed Breakdown
127+
128+
1. **Return Type (`NSString *`)**: Encoded as `@` with length 24
129+
2. **`self` (object instance)**: Encoded as `@`, at offset 0
130+
3. **`_cmd` (selector)**: Encoded as `:`, at offset 8
131+
4. **First argument (`char * input`)**: Encoded as `*`, at offset 16
132+
5. **Second argument (`NSDictionary * options`)**: Encoded as `@`, at offset 20
133+
6. **Third argument (`NSError ** error`)**: Encoded as `^@`, at offset 24
134+
135+
**With the selector + the encoding you can reconstruct the method.**
136+
137+
### **Classes**
138+
139+
Clases in Objective-C is a struct with properties, method pointers... It's possible to find the struct `objc_class` in the [**source code**](https://opensource.apple.com/source/objc4/objc4-756.2/runtime/objc-runtime-new.h.auto.html):
140+
141+
```objectivec
142+
struct objc_class : objc_object {
143+
// Class ISA;
144+
Class superclass;
145+
cache_t cache; // formerly cache pointer and vtable
146+
class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
147+
148+
class_rw_t *data() {
149+
return bits.data();
150+
}
151+
void setData(class_rw_t *newData) {
152+
bits.setData(newData);
153+
}
154+
155+
void setInfo(uint32_t set) {
156+
assert(isFuture() || isRealized());
157+
data()->setFlags(set);
158+
}
159+
[...]
160+
```
161+
162+
This class use some bits of the isa field to indicate some information about the class.
163+
164+
Then, the struct has a pointer to the struct `class_ro_t` stored on disk which contains attributes of the class like its name, base methods, properties and instance variables.\
165+
During runtime and additional structure `class_rw_t` is used containing pointers which can be altered such as methods, protocols, properties...
166+
167+
168+
169+
<details>
170+
171+
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
172+
173+
Other ways to support HackTricks:
174+
175+
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
176+
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
177+
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
178+
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
179+
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
180+
181+
</details>

0 commit comments

Comments
 (0)