/
iokit.cpp
339 lines (294 loc) · 10.6 KB
/
iokit.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <osquery/logger.h>
#include <osquery/tables.h>
#include <IOKit/IOMessage.h>
#include "osquery/core/conversions.h"
#include "osquery/events/darwin/iokit.h"
namespace osquery {
const std::string kIOUSBDeviceClassName_ = "IOUSBDevice";
const std::string kIOPCIDeviceClassName_ = "IOPCIDevice";
const std::string kIOPlatformExpertDeviceClassName_ = "IOPlatformExpertDevice";
const std::string kIOACPIPlatformDeviceClassName_ = "IOACPIPlatformDevice";
const std::string kIOPlatformDeviceClassname_ = "IOPlatformDevice";
REGISTER(IOKitEventPublisher, "event_publisher", "iokit");
struct DeviceTracker : private boost::noncopyable {
public:
explicit DeviceTracker(IOKitEventPublisher* p) : publisher(p) {}
public:
IOKitEventPublisher* publisher{nullptr};
io_object_t notification{0};
};
IOKitPCIProperties::IOKitPCIProperties(const std::string& compatible) {
auto properties = osquery::split(compatible, " ");
if (properties.size() < 2) {
return;
}
size_t prop_index = 0;
if (properties[1].find("pci") == 0 && properties[1].find("pciclass") != 0) {
// There are two sets of PCI definitions.
prop_index = 1;
} else if (properties[0].find("pci") != 0) {
return;
}
auto vendor = osquery::split(properties[prop_index++], ",");
vendor_id = vendor[0].substr(3);
model_id = (vendor[1].size() == 3) ? "0" + vendor[1] : vendor[1];
if (properties[prop_index].find("pciclass") == 0) {
// There is a class definition.
pci_class = properties[prop_index++].substr(9);
}
if (properties.size() > prop_index) {
// There is a driver/ID.
driver = properties[prop_index];
}
}
std::string getIOKitProperty(const CFMutableDictionaryRef& details,
const std::string& key) {
std::string value;
// Get a property from the device.
auto cfkey = CFStringCreateWithCString(
kCFAllocatorDefault, key.c_str(), kCFStringEncodingUTF8);
auto property = CFDictionaryGetValue(details, cfkey);
CFRelease(cfkey);
// Several supported ways of parsing IOKit-encoded data.
if (property) {
if (CFGetTypeID(property) == CFNumberGetTypeID()) {
value = stringFromCFNumber((CFDataRef)property);
} else if (CFGetTypeID(property) == CFStringGetTypeID()) {
value = stringFromCFString((CFStringRef)property);
} else if (CFGetTypeID(property) == CFDataGetTypeID()) {
value = stringFromCFData((CFDataRef)property);
} else if (CFGetTypeID(property) == CFBooleanGetTypeID()) {
value = (CFBooleanGetValue((CFBooleanRef)property)) ? "1" : "0";
}
}
return value;
}
long long int getNumIOKitProperty(const CFMutableDictionaryRef& details,
const std::string& key) {
// Get a property from the device.
auto cfkey = CFStringCreateWithCString(
kCFAllocatorDefault, key.c_str(), kCFStringEncodingUTF8);
auto property = CFDictionaryGetValue(details, cfkey);
CFRelease(cfkey);
// Several supported ways of parsing IOKit-encoded data.
if (property && CFGetTypeID(property) == CFNumberGetTypeID()) {
CFNumberType type = CFNumberGetType((CFNumberRef)property);
long long int value;
CFNumberGetValue((CFNumberRef)property, type, &value);
return value;
}
return 0;
}
void IOKitEventPublisher::restart() {
static std::vector<const std::string*> device_classes = {
&kIOUSBDeviceClassName_,
&kIOPCIDeviceClassName_,
&kIOPlatformExpertDeviceClassName_,
&kIOACPIPlatformDeviceClassName_,
&kIOPlatformDeviceClassname_,
};
if (run_loop_ == nullptr) {
return;
}
// Remove any existing stream.
stop();
{
WriteLock lock(mutex_);
port_ = IONotificationPortCreate(kIOMasterPortDefault);
// Get a run loop source from the created IOKit notification port.
auto run_loop_source = IONotificationPortGetRunLoopSource(port_);
CFRunLoopAddSource(run_loop_, run_loop_source, kCFRunLoopDefaultMode);
}
publisher_started_ = false;
for (const auto& class_name : device_classes) {
// Service matching is USB for now, must find a way to get more!
// Can provide a "IOPCIDevice" here too.
auto matches = IOServiceMatching(class_name->c_str());
// Register attach/detaches (could use kIOPublishNotification).
// Notification types are defined in IOKitKeys.
IOReturn result = kIOReturnSuccess + 1;
{
WriteLock lock(mutex_);
result = IOServiceAddMatchingNotification(
port_,
kIOFirstMatchNotification,
matches,
(IOServiceMatchingCallback)deviceAttach,
this,
&iterator_);
}
if (result == kIOReturnSuccess) {
deviceAttach(this, iterator_);
}
}
publisher_started_ = true;
}
void IOKitEventPublisher::newEvent(const io_service_t& device,
IOKitEventContext::Action action) {
auto ec = createEventContext();
ec->action = action;
{
// The IORegistry name is not needed.
io_name_t class_name = {0};
if (IOObjectGetClass(device, class_name) != kIOReturnSuccess) {
return;
}
ec->type = std::string(class_name);
}
// Get the device details
CFMutableDictionaryRef details;
IORegistryEntryCreateCFProperties(
device, &details, kCFAllocatorDefault, kNilOptions);
if (ec->type == kIOUSBDeviceClassName_) {
ec->path = getIOKitProperty(details, "USB Address") + ":";
ec->path += getIOKitProperty(details, "PortNum");
ec->model = getIOKitProperty(details, "USB Product Name");
ec->model_id = getIOKitProperty(details, "idProduct");
ec->vendor = getIOKitProperty(details, "USB Vendor Name");
ec->vendor_id = getIOKitProperty(details, "idVendor");
idToHex(ec->vendor_id);
idToHex(ec->model_id);
ec->serial = getIOKitProperty(details, "USB Serial Number");
if (ec->serial.size() == 0) {
ec->serial = getIOKitProperty(details, "iSerialNumber");
}
ec->version = "";
ec->driver = getIOKitProperty(details, "IOUserClientClass");
} else if (ec->type == kIOPCIDeviceClassName_) {
auto compatible = getIOKitProperty(details, "compatible");
auto properties = IOKitPCIProperties(compatible);
ec->model_id = properties.model_id;
ec->vendor_id = properties.vendor_id;
ec->driver = properties.driver;
if (ec->driver.empty()) {
ec->driver = getIOKitProperty(details, "IOName");
}
ec->path = getIOKitProperty(details, "pcidebug");
ec->version = getIOKitProperty(details, "revision-id");
ec->model = getIOKitProperty(details, "model");
} else {
// Get the name as the model.
io_name_t name = {0};
IORegistryEntryGetName(device, name);
if (name[0] != 0) {
ec->model = std::string(name);
}
}
CFRelease(details);
fire(ec);
}
void IOKitEventPublisher::deviceAttach(void* refcon, io_iterator_t iterator) {
auto self = (IOKitEventPublisher*)refcon;
io_service_t device;
// The iterator may also have become invalid due to a change in the registry.
// It is possible to reiterate devices, but that will cause duplicate events.
while ((device = IOIteratorNext(iterator))) {
// Create a notification tracker.
{
WriteLock lock(self->mutex_);
auto tracker = std::make_shared<struct DeviceTracker>(self);
self->devices_.push_back(tracker);
IOServiceAddInterestNotification(self->port_,
device,
kIOGeneralInterest,
(IOServiceInterestCallback)deviceDetach,
tracker.get(),
&(tracker->notification));
}
if (self->publisher_started_) {
self->newEvent(device, IOKitEventContext::Action::DEVICE_ATTACH);
}
IOObjectRelease(device);
}
}
void IOKitEventPublisher::deviceDetach(void* refcon,
io_service_t device,
natural_t message_type,
void*) {
if (message_type != kIOMessageServiceIsTerminated) {
// This is an unexpected notification.
return;
}
auto* tracker = (struct DeviceTracker*)refcon;
auto* self = tracker->publisher;
// The device tracker allows us to emit using the publisher and release the
// notification created for this device.
self->newEvent(device, IOKitEventContext::Action::DEVICE_DETACH);
IOObjectRelease(device);
{
WriteLock lock(self->mutex_);
// Remove the device tracker.
IOObjectRelease(tracker->notification);
auto it = self->devices_.begin();
while (it != self->devices_.end()) {
if ((*it)->notification == tracker->notification) {
IOObjectRelease((*it)->notification);
self->devices_.erase(it);
break;
}
it++;
}
}
}
Status IOKitEventPublisher::run() {
// The run entrypoint executes in a dedicated thread.
if (run_loop_ == nullptr) {
run_loop_ = CFRunLoopGetCurrent();
// Restart the stream creation.
restart();
}
// Start the run loop, it may be removed with a tearDown.
CFRunLoopRun();
return Status(0, "OK");
}
bool IOKitEventPublisher::shouldFire(const IOKitSubscriptionContextRef& sc,
const IOKitEventContextRef& ec) const {
if (!sc->type.empty() && sc->type != ec->type) {
return false;
} else if (!sc->model_id.empty() && sc->model_id != ec->model_id) {
return false;
} else if (!sc->vendor_id.empty() && sc->vendor_id != ec->vendor_id) {
return false;
}
return true;
}
void IOKitEventPublisher::stop() {
if (run_loop_ == nullptr) {
// If there is no run loop then the publisher thread has not started.
return;
}
// Stop the run loop.
WriteLock lock(mutex_);
CFRunLoopStop(run_loop_);
// Stop the run loop before operating on containers.
// Destroy the IOPort.
if (port_ != nullptr) {
auto source = IONotificationPortGetRunLoopSource(port_);
if (CFRunLoopContainsSource(run_loop_, source, kCFRunLoopDefaultMode)) {
CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode);
}
// And destroy the port.
IONotificationPortDestroy(port_);
port_ = nullptr;
}
// Clear all devices and their notifications.
for (const auto& device : devices_) {
IOObjectRelease(device->notification);
}
devices_.clear();
}
void IOKitEventPublisher::tearDown() {
stop();
// Do not keep a reference to the run loop.
run_loop_ = nullptr;
}
}