-
Notifications
You must be signed in to change notification settings - Fork 3
/
kextd_main.c
1103 lines (955 loc) · 40.1 KB
/
kextd_main.c
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2012 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFPriv.h> // for _CFRunLoopSetCurrent()
#include <IOKit/IOKitLib.h>
#include <IOKit/IOKitServer.h>
#include <IOKit/IOCFURLAccess.h>
#include <IOKit/IOCFUnserialize.h>
#include <IOKit/storage/RAID/AppleRAIDUserLib.h>
#include <IOKit/storage/CoreStorage/CoreStorageUserLib.h>
#include <IOKit/kext/OSKext.h>
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/mach_error.h>
#include <mach-o/arch.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <libc.h>
#include <servers/bootstrap.h>
#include <signal.h>
#include <sysexits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/resource.h>
#include <unistd.h>
#include <paths.h>
#include <IOKit/kext/OSKext.h>
#include <IOKit/kext/OSKextPrivate.h>
#include <IOKit/kext/kextmanager_types.h>
#include <bootfiles.h>
#include "kextd_main.h"
#include "kext_tools_util.h"
#include "kextd_globals.h"
#include "kextd_personalities.h"
#include "kextd_mig_server.h"
#include "kextd_request.h"
#include "kextd_usernotification.h"
#include "kextd_watchvol.h"
#include "bootcaches.h"
#include "pgo.h"
/*******************************************************************************
* Globals set from invocation arguments (xxx - could use fewer globals).
*******************************************************************************/
const char * progname = "(unknown)"; // don't free
/*******************************************************************************
*******************************************************************************/
struct option sOptInfo[] = {
{ kOptNameHelp, no_argument, NULL, kOptHelp },
{ kOptNameNoCaches, no_argument, NULL, kOptNoCaches },
{ kOptNameDebug, no_argument, NULL, kOptDebug },
{ kOptNameQuiet, required_argument, NULL, kOptQuiet },
{ kOptNameVerbose, optional_argument, NULL, kOptVerbose },
{ NULL, 0, NULL, 0 } // sentinel to terminate list
};
/*******************************************************************************
* Globals created at run time.
*******************************************************************************/
KextdArgs sToolArgs;
CFArrayRef gRepositoryURLs = NULL;
static CFArrayRef sAllKexts = NULL;
Boolean gKernelRequestsPending = false;
// all the following are released in setUpServer()
static CFRunLoopTimerRef sReleaseKextsTimer = NULL;
static CFRunLoopSourceRef sClientRequestRunLoopSource = NULL;
static CFMachPortRef sKextdSignalMachPort = NULL;
static mach_port_t sKextSignalMachPortMachPort = MACH_PORT_NULL;
static CFRunLoopSourceRef sSignalRunLoopSource = NULL;
const NXArchInfo * gKernelArchInfo = NULL; // do not free
ExitStatus sKextdExitStatus = kKextdExitOK;
/*******************************************************************************
* Static routines.
******************************************************************************/
static void NoLoadSigFailureKextCallback(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo );
static void InvalidSignedKextCallback(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo );
static void RevokedCertKextCallback(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo );
#if 0 // not yet
static void UnsignedKextCallback(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo );
#endif
static void ExcludedKextCallback(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo );
static void LoadedKextCallback(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo );
/*******************************************************************************
*******************************************************************************/
int main(int argc, char * const * argv)
{
char logSpecBuffer[16]; // enough for a 64-bit hex value
/*****
* Find out what my name is.
*/
progname = rindex(argv[0], '/');
if (progname) {
progname++; // go past the '/'
} else {
progname = (char *)argv[0];
}
OSKextSetLogOutputFunction(&tool_log);
/* Read command line and set a few other args that don't involve
* logging. (Syslog is opened up just below; we have to do that after
* parsing args, unfortunately.)
*/
sKextdExitStatus = readArgs(argc, argv, &sToolArgs);
if (sKextdExitStatus != EX_OK) {
goto finish;
}
/*****
* If not running in debug mode, then hook up to syslog.
*/
if (!sToolArgs.debugMode) {
tool_openlog("com.apple.kextd");
}
/*****
* Set an environment variable that children (such as kextcache)
* can use to alter behavior (logging to syslog etc.).
*/
setenv("KEXTD_SPAWNED", "", /* overwrite */ 1);
snprintf(logSpecBuffer, sizeof(logSpecBuffer), "0x%x",
OSKextGetLogFilter(/* kernel? */ true));
setenv("KEXT_LOG_FILTER_KERNEL", logSpecBuffer, /* overwrite */ 1);
snprintf(logSpecBuffer, sizeof(logSpecBuffer), "0x%x",
OSKextGetLogFilter(/* kernel? */ false));
setenv("KEXT_LOG_FILTER_USER", logSpecBuffer, /* overwrite */ 1);
gRepositoryURLs = OSKextGetSystemExtensionsFolderURLs();
if (!gRepositoryURLs) {
goto finish;
}
/* Get the running kernel arch for OSKext ops & cache creation.
*/
if (!gKernelArchInfo) {
gKernelArchInfo = OSKextGetRunningKernelArchitecture();
if (!gKernelArchInfo) {
goto finish;
}
}
/* Check kernel first for safe boot, -x/-safe-boot is only for debugging.
*/
if (OSKextGetActualSafeBoot()) {
sToolArgs.safeBootMode = true;
} else if (sToolArgs.safeBootMode) {
OSKextSetSimulatedSafeBoot(true);
}
OSKextSetUsesCaches(sToolArgs.useRepositoryCaches);
OSKextSetRecordsDiagnostics(kOSKextDiagnosticsFlagNone);
readExtensions();
sKextdExitStatus = setUpServer(&sToolArgs);
if (sKextdExitStatus != EX_OK) {
goto finish;
}
/* Tell the IOCatalogue that we are ready to service load requests.
*/
sendActiveToKernel();
/*****
* Send the kext personalities to the kernel to trigger matching.
* Now that we have UUID dependency checks, the kernel shouldn't
* be able to hurt itself if kexts are out of date somewhere.
*
* sAllKexts gets cleaned up on the run loop so it's okay to use it here.
*
* We shouldn't need to reset the IOCatalogue here as it's startup time.
*/
if (kOSReturnSuccess != sendSystemKextPersonalitiesToKernel(sAllKexts, /* reset? */ false)) {
sKextdExitStatus = EX_OSERR;
goto finish;
}
CFArrayRef propertyValues;
if (readSystemKextPropertyValues(CFSTR("PGO"), gKernelArchInfo,
/* forceUpdate? */ FALSE, &propertyValues)) {
if (pgo_scan_kexts(propertyValues))
{
/* give the pgo threads time to get into grab_pgo_data before the kernel
* starts unloading things. */
sleep(1);
}
CFRelease(propertyValues);
}
/* Note: We are not going to try to update the OSBunderHelpers cache
* this early as it isn't needed until login. It should normally be
* up to date anyhow so let's keep startup I/O to an absolute minimum.
*/
/* Let IOCatalogue drop the artificial busy count on the registry
* now that it has personalities (which are sure to have naturally
* bumped the busy count).
*/
sendFinishedToKernel();
// Start run loop
CFRunLoopRun();
// Runloop is done - for restart performance exit asap
_exit(sKextdExitStatus);
finish:
#ifndef NO_CFUserNotification
stopMonitoringConsoleUser();
#endif /* ifndef NO_CFUserNotification */
kextd_stop_volwatch(); // no-op if watch_volumes not called
if (sKextdExitStatus == kKextdExitHelp) {
sKextdExitStatus = kKextdExitOK;
}
exit(sKextdExitStatus);
return sKextdExitStatus;
}
#pragma mark Major Subroutines
/*******************************************************************************
* Major Subroutines
*******************************************************************************/
ExitStatus
readArgs(
int argc,
char * const * argv,
KextdArgs * toolArgs)
{
ExitStatus result = EX_USAGE;
ExitStatus scratchResult = EX_USAGE;
struct stat stat_buf;
int optchar;
int longindex;
CFStringRef scratchString = NULL; // must release
CFNumberRef scratchNumber = NULL; // must release
CFURLRef scratchURL = NULL; // must release
/* Kextd is not interested in log messages from the kernel, since
* kextd itself prints to the system log and this would duplicate
* things coming from the kernel. If you want more kernel kext
* logging, use the kextlog boot arg.
*/
OSKextSetLogFilter(kDefaultServiceLogFilter, /* kernel? */ false);
OSKextSetLogFilter(kOSKextLogSilentFilter, /* kernel? */ true);
bzero(toolArgs, sizeof(*toolArgs));
toolArgs->debugMode = false;
toolArgs->useRepositoryCaches = true;
if (stat(kAppleSetupDonePath, &stat_buf) == -1 && errno == ENOENT) {
toolArgs->firstBoot = true;
} else {
toolArgs->firstBoot = false;
}
while ((optchar = getopt_long_only(argc, (char * const *)argv,
kOptChars, sOptInfo, &longindex)) != -1) {
SAFE_RELEASE_NULL(scratchString);
SAFE_RELEASE_NULL(scratchNumber);
SAFE_RELEASE_NULL(scratchURL);
switch (optchar) {
case kOptHelp:
usage(kUsageLevelFull);
result = kKextdExitHelp;
goto finish;
break;
case kOptNoCaches:
toolArgs->useRepositoryCaches = false;
break;
case kOptDebug:
toolArgs->debugMode = true;
break;
case kOptQuiet:
beQuiet();
break;
case kOptVerbose:
/* Set the log flags by the command line, but then turn off
* the kernel bridge again.
*/
scratchResult = setLogFilterForOpt(argc, argv, /* forceOnFlags */ 0);
if (scratchResult != EX_OK) {
result = scratchResult;
goto finish;
}
OSKextSetLogFilter(kOSKextLogSilentFilter, /* kernel? */ true);
break;
case kOptSafeBoot:
toolArgs->safeBootMode = true;
toolArgs->useRepositoryCaches = false; // -x implies -c
break;
default:
/* getopt_long_only() prints an error message for us. */
goto finish;
break;
} /* switch (optchar) */
} /* while (optchar = getopt_long_only(...) */
argc -= optind;
argv += optind;
if (argc) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Extra input on command line; %s....", argv[0]);
goto finish;
}
result = EX_OK;
finish:
SAFE_RELEASE(scratchString);
SAFE_RELEASE(scratchNumber);
SAFE_RELEASE(scratchURL);
if (result == EX_USAGE) {
usage(kUsageLevelBrief);
}
return result;
}
/*******************************************************************************
*******************************************************************************/
Boolean isNetboot(void)
{
Boolean result = false;
int netboot_mib_name[] = { CTL_KERN, KERN_NETBOOT };
int netboot = 0;
size_t netboot_len = sizeof(netboot);
if (sysctl(netboot_mib_name, sizeof(netboot_mib_name) / sizeof(int),
&netboot, &netboot_len, NULL, 0) != 0) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to detect netboot - %s.", strerror(errno));
goto finish;
}
result = netboot ? true : false;
finish:
return result;
}
/*******************************************************************************
* Tell the IOCatalogue that kextd is ready to service kernel requests.
*******************************************************************************/
void sendActiveToKernel(void)
{
kern_return_t kernelResult;
kernelResult = IOCatalogueSendData(kIOMasterPortDefault,
kIOCatalogKextdActive, 0, 0);
if (kernelResult != KERN_SUCCESS) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to notify kernel that kextd is active - %s.",
safe_mach_error_string(kernelResult));
}
return;
}
/*******************************************************************************
* sendFinishedToKernel()
*
* Tell the IOCatalogue that kextd is about to enter its run loop to service
* requests just generated by sending down all the personalities.
* The IOCatalogue then drops its artificial busy count on the registry.
*******************************************************************************/
void sendFinishedToKernel(void)
{
kern_return_t kernelResult;
kernelResult = IOCatalogueSendData(kIOMasterPortDefault,
kIOCatalogKextdFinishedLaunching, 0, 0);
if (kernelResult != KERN_SUCCESS) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to notify kernel that kextd is finished launching - %s.",
safe_mach_error_string(kernelResult));
}
return;
}
/*******************************************************************************
* setUpServer()
*******************************************************************************/
ExitStatus setUpServer(KextdArgs * toolArgs)
{
ExitStatus result = EX_OSERR;
kern_return_t kernelResult = KERN_SUCCESS;
unsigned int sourcePriority = 1;
CFMachPortRef kextdMachPort = NULL; // must release
mach_port_limits_t limits; // queue limit for signal-handler port
mach_port_t servicePort;
/* Check in with the bootstrap services.
*/
kernelResult = bootstrap_check_in(bootstrap_port,
KEXTD_SERVER_NAME, &servicePort);
if (kernelResult != BOOTSTRAP_SUCCESS) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag | kOSKextLogIPCFlag,
"Failed server check-in - %s", bootstrap_strerror(kernelResult));
exit(EX_OSERR);
}
/* Initialize the run loop so we can start adding sources.
*/
if (!CFRunLoopGetCurrent()) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to create run loop.");
goto finish;
}
/*****
* Add the runloop sources in decreasing priority (increasing "order").
* Signals are handled first, followed by kernel requests, and then by
* client requests. It's important that each source have a distinct
* priority; sharing them causes unpredictable behavior with the runloop.
* Note: CFRunLoop.h, however, says 'order' should generally be 0 for all.
*/
kextdMachPort = CFMachPortCreateWithPort(kCFAllocatorDefault,
servicePort, kextd_mach_port_callback, /* CFMachPortContext */ NULL,
/* shouldFreeInfo? */ NULL);
sClientRequestRunLoopSource = CFMachPortCreateRunLoopSource(
kCFAllocatorDefault, kextdMachPort, sourcePriority++);
if (!sClientRequestRunLoopSource) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to create client request run loop source.");
goto finish;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), sClientRequestRunLoopSource,
kCFRunLoopDefaultMode);
// 5519500: kextd_watch_volumes now holds off on updates on its own
if (kextd_watch_volumes(sourcePriority++)) {
goto finish;
}
sKextdSignalMachPort = CFMachPortCreate(kCFAllocatorDefault,
handleSignalInRunloop, NULL, NULL);
if (!sKextdSignalMachPort) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to create signal-handling Mach port.");
goto finish;
}
sKextSignalMachPortMachPort = CFMachPortGetPort(sKextdSignalMachPort);
limits.mpl_qlimit = 1;
kernelResult = mach_port_set_attributes(mach_task_self(),
sKextSignalMachPortMachPort,
MACH_PORT_LIMITS_INFO,
(mach_port_info_t)&limits,
MACH_PORT_LIMITS_INFO_COUNT);
if (kernelResult != KERN_SUCCESS) {
OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to set signal-handling port limits.");
}
sSignalRunLoopSource = CFMachPortCreateRunLoopSource(
kCFAllocatorDefault, sKextdSignalMachPort, sourcePriority++);
if (!sSignalRunLoopSource) {
OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to create signal-handling run loop source.");
goto finish;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), sSignalRunLoopSource,
kCFRunLoopDefaultMode);
/* Watch for RAID changes so we can forcibly update their boot partitions.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
NULL, // const void *observer
updateRAIDSet,
CFSTR(kAppleRAIDNotificationSetChanged),
NULL, // const void *object
CFNotificationSuspensionBehaviorHold);
kernelResult = AppleRAIDEnableNotifications();
if (kernelResult != KERN_SUCCESS) {
OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to register for RAID notifications.");
}
/* Watch for CoreStorage changes so we can update their boot partitions.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
NULL, // const void *observer
updateCoreStorageVolume,
CFSTR(kCoreStorageNotificationLVGChanged),
NULL, // const void *object
CFNotificationSuspensionBehaviorHold);
CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(),
NULL, // const void *observer
updateCoreStorageVolume,
CFSTR(kCoreStorageNotificationVolumeChanged),
NULL, // const void *object
CFNotificationSuspensionBehaviorHold);
kernelResult = CoreStorageEnableNotifications();
if (kernelResult != KERN_SUCCESS) {
OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to register for CoreStorage Volume notifications.");
}
/* Sign up to receive notifications when nonsigned kexts are found. We
* currently get messages from kextcache, kextload and kextutil.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
NoLoadSigFailureKextCallback,
CFSTR("No Load Kext Notification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
/* Sign up to receive notifications when invalid signed kexts are found. We
* currently get messages from kextcache, kextload and kextutil.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
InvalidSignedKextCallback,
CFSTR("Invalid Signature Kext Notification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
/* Sign up to receive notifications when kexts are found on the exclude
* list. We currently get messages from kextcache, kextload and kextutil.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
ExcludedKextCallback,
CFSTR("Excluded Kext Notification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
/* Sign up to receive notifications when kexts with revoked certs are
* found. We currently get messages from kextcache, kextload and kextutil.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
RevokedCertKextCallback,
CFSTR("Revoked Cert Kext Notification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
#if 0 // not yet
/* Sign up to receive notifications when unisgned kexts are found. We
* currently get messages from kextcache, kextload and kextutil.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
UnsignedKextCallback,
CFSTR("Unsigned Kext Notification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
#endif
/* Sign up to receive notifications when kexts are loaded.
* We currently get messages from kextcache, kextload and kextutil.
*/
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
LoadedKextCallback,
CFSTR("Loaded Kext Notification"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
#ifndef NO_CFUserNotification
result = startMonitoringConsoleUser(toolArgs, &sourcePriority);
if (result != EX_OK) {
goto finish;
}
#endif /* ifndef NO_CFUserNotification */
signal(SIGHUP, handleSignal);
signal(SIGTERM, handleSignal);
signal(SIGCHLD, handleSignal);
result = EX_OK;
finish:
SAFE_RELEASE(sClientRequestRunLoopSource);
SAFE_RELEASE(sKextdSignalMachPort);
SAFE_RELEASE(sSignalRunLoopSource);
SAFE_RELEASE(kextdMachPort);
return result;
}
#include "security.h"
/******************************************************************************
* NoLoadSigFailureKextCallback() CFNotificationCenter posts from kextcache,
* kextload and kextutil enter here.
******************************************************************************/
void NoLoadSigFailureKextCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if (userInfo) {
/* synchronize access to our plist file */
CFRetain(userInfo);
dispatch_async(dispatch_get_main_queue(), ^ {
writeKextAlertPlist(userInfo, NO_LOAD_KEXT_ALERT);
});
}
return;
}
/******************************************************************************
* RevokedCertKextCallback() CFNotificationCenter posts from kextcache,
* kextload and kextutil enter here.
******************************************************************************/
void RevokedCertKextCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if (userInfo) {
/* synchronize access to our plist file */
CFRetain(userInfo);
dispatch_async(dispatch_get_main_queue(), ^ {
sendRevokedCertAlert(userInfo);
});
}
return;
}
#if 0 // not yet
/******************************************************************************
* UnsignedKextCallback() CFNotificationCenter posts from kextcache,
* kextload and kextutil enter here.
******************************************************************************/
void UnsignedKextCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if (userInfo) {
/* synchronize access to our plist file */
CFRetain(userInfo);
dispatch_async(dispatch_get_main_queue(), ^ {
writeKextAlertPlist(userInfo, UNSIGNED_KEXT_ALERT);
});
}
return;
}
#endif
/******************************************************************************
* InvalidSignedKextCallback() CFNotificationCenter posts from kextcache,
* kextload and kextutil enter here.
******************************************************************************/
void InvalidSignedKextCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if (userInfo) {
/* synchronize access to our plist file */
CFRetain(userInfo);
dispatch_async(dispatch_get_main_queue(), ^ {
writeKextAlertPlist(userInfo, INVALID_SIGNATURE_KEXT_ALERT);
});
}
return;
}
/******************************************************************************
* ExcludedKextCallback() CFNotificationCenter posts from kextcache, kextload
* and kextutil enter here.
******************************************************************************/
void ExcludedKextCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if (userInfo) {
/* synchronize access to our plist file */
CFRetain(userInfo);
dispatch_async(dispatch_get_main_queue(), ^ {
writeKextAlertPlist(userInfo, EXCLUDED_KEXT_ALERT);
});
}
return;
}
/******************************************************************************
* LoadedKextCallback() CFNotificationCenter posts from kextcache, kextload
* and kextutil enter here. Used for message tracing of kext loads.
******************************************************************************/
void LoadedKextCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if (userInfo) {
CFArrayRef myValue;
myValue = CFDictionaryGetValue(userInfo, CFSTR("KextArrayKey"));
if (myValue && CFGetTypeID(myValue) == CFArrayGetTypeID()) {
/* synchronize access to our plist file */
CFRetain(myValue);
dispatch_async(dispatch_get_main_queue(), ^ {
writeKextLoadPlist(myValue);
});
}
}
return;
}
/******************************************************************************
* isBootRootActive() checks for the booter hint
******************************************************************************/
bool isBootRootActive(void)
{
int result = false;
io_service_t chosen = 0; // must IOObjectRelease()
CFTypeRef bootrootProp = 0; // must CFRelease()
chosen = IORegistryEntryFromPath(kIOMasterPortDefault,
"IODeviceTree:/chosen");
if (!chosen) {
goto finish;
}
bootrootProp = IORegistryEntryCreateCFProperty(
chosen, CFSTR(kBootRootActiveKey), kCFAllocatorDefault,
0 /* options */);
/* Mere presence of the property indicates that we are
* boot!=root, type and value are irrelevant.
*/
if (bootrootProp) {
result = true;
}
finish:
if (chosen) IOObjectRelease(chosen);
SAFE_RELEASE(bootrootProp);
return result;
}
/*******************************************************************************
* On receiving a SIGHUP or SIGTERM, the daemon sends a Mach message to the
* signal port, causing the run loop handler function rescanExtensions() to be
* called on the main thread.
*
* IMPORTANT: This is a UNIX signal handler, so no allocating or any other unsafe
* calls. Sending a hand-rolled Mach message off the stack is okay.
*******************************************************************************/
void handleSignal(int signum)
{
kextd_mach_msg_signal_t msg;
msg.signum = signum;
msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
msg.header.msgh_size = sizeof(msg.header);
msg.header.msgh_remote_port = sKextSignalMachPortMachPort;
msg.header.msgh_local_port = MACH_PORT_NULL;
msg.header.msgh_id = 0;
(void) mach_msg(
&msg.header, /* msg */
MACH_SEND_MSG | MACH_SEND_TIMEOUT, /* options */
sizeof(msg), /* send_size */
0, /* rcv_size */
MACH_PORT_NULL, /* rcv_name */
0, /* timeout */
MACH_PORT_NULL); /* notify */
return;
}
/*******************************************************************************
*******************************************************************************/
void handleSignalInRunloop(
CFMachPortRef port,
void * msg,
CFIndex size,
void * info)
{
kextd_mach_msg_signal_t * signal_msg = (kextd_mach_msg_signal_t *)msg;
int signum = signal_msg->signum;
if (signum == SIGHUP) {
rescanExtensions();
} else if (signum == SIGTERM) {
CFRunLoopStop(CFRunLoopGetCurrent());
sKextdExitStatus = kKextdExitSigterm;
} else if (signum == SIGCHLD) {
pid_t child_pid = -1;
int child_status = 0;
/* Reap all spawned child processes that have exited.
*/
do {
child_pid = waitpid(-1 /* any child */, &child_status, WNOHANG);
if (child_pid == -1) {
if (errno != ECHILD) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Error %s waiting on child processes.",
strerror(errno));
}
} else if (child_pid > 0) {
OSKextLogSpec logSpec;
// EX_SOFTWARE generally means kextcache called
// _kextmanager_unlock_volume which logs the error
if (WEXITSTATUS(child_status)==0 || child_status==EX_SOFTWARE) {
logSpec = kOSKextLogDetailLevel;
} else {
logSpec = kOSKextLogErrorLevel;
}
OSKextLog(/* kext */ NULL, logSpec,
"async child pid %d exited with status %d",
child_pid, WEXITSTATUS(child_status));
}
} while (child_pid > 0);
}
return;
}
/*******************************************************************************
* This function reads the extensions if necessary. Note support for multiple
* extensions directories.
*
* This function does not update personalities in the kernel or update any
* caches other than those the OSKext library updates in the course of reading
* the extensions. We have a notify thread on the extensions folders that does
* that, with a slight delay.
*******************************************************************************/
void readExtensions(void)
{
static struct timeval lastModTime = {0,0};
static struct timeval lastAccessTime = {0,0};
struct timeval tempTimes[2];
ExitStatus result = EX_SOFTWARE;
/* If getLatestTimesFromCFURLArray fails for any of the extensions
* directories we will force reading in all the kexts. Otherwise we only
* read in all the kexts if any of the extensions directories have been
* modified. The first time we're called we will save off the latest mod
* time and reread (which is fine since we have not read in any kexts yet).
*/
result = getLatestTimesFromCFURLArray(gRepositoryURLs,
tempTimes);
if (result != EX_OK) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Failed to stat extensions folders (%s); rereading.",
strerror(errno));
/* force reading all extensions */
releaseExtensions(/* timer */ NULL, /* context */ NULL);
}
if (result == EX_OK && timercmp(&lastModTime, &tempTimes[1], !=)) {
lastAccessTime.tv_sec = tempTimes[0].tv_sec;
lastAccessTime.tv_usec = tempTimes[0].tv_usec;
lastModTime.tv_sec = tempTimes[1].tv_sec;
lastModTime.tv_usec = tempTimes[1].tv_usec;
releaseExtensions(/* timer */ NULL, /* context */ NULL);
}
if (!sAllKexts && gRepositoryURLs) {
OSKextLog(/* kext */ NULL,
kOSKextLogProgressLevel | kOSKextLogGeneralFlag,
"Reading extensions.");
sAllKexts = OSKextCreateKextsFromURLs(kCFAllocatorDefault,
gRepositoryURLs);
}
scheduleReleaseExtensions();
return;
}
/*******************************************************************************
*******************************************************************************/
void scheduleReleaseExtensions(void)
{
OSKextLog(/* kext */ NULL,
kOSKextLogProgressLevel | kOSKextLogGeneralFlag,
"%scheduling release of all kexts.", sReleaseKextsTimer ? "Res" : "S");
if (sReleaseKextsTimer) {
CFRunLoopTimerInvalidate(sReleaseKextsTimer);
SAFE_RELEASE_NULL(sReleaseKextsTimer);
}
sReleaseKextsTimer = CFRunLoopTimerCreate(kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent() + kReleaseKextsDelay, /* interval */ 0,
/* flags */ 0, /* order */ 0, &releaseExtensions, /* context */ NULL);