Advertisement
Guest User

KauthORama.c

a guest
Feb 8th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 39.51 KB | None | 0 0
  1. /*
  2. File: KauthORama.c
  3. Abstract: A kernel extension to dump all known Kauth operations.
  4. Version: 1.4
  5.  
  6. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
  7. Inc. ("Apple") in consideration of your agreement to the following
  8. terms, and your use, installation, modification or redistribution of
  9. this Apple software constitutes acceptance of these terms. If you do
  10. not agree with these terms, please do not use, install, modify or
  11. redistribute this Apple software.
  12.  
  13. In consideration of your agreement to abide by the following terms, and
  14. subject to these terms, Apple grants you a personal, non-exclusive
  15. license, under Apple's copyrights in this original Apple software (the
  16. "Apple Software"), to use, reproduce, modify and redistribute the Apple
  17. Software, with or without modifications, in source and/or binary forms;
  18. provided that if you redistribute the Apple Software in its entirety and
  19. without modifications, you must retain this notice and the following
  20. text and disclaimers in all such redistributions of the Apple Software.
  21. Neither the name, trademarks, service marks or logos of Apple Inc. may
  22. be used to endorse or promote products derived from the Apple Software
  23. without specific prior written permission from Apple. Except as
  24. expressly stated in this notice, no other rights or licenses, express or
  25. implied, are granted by Apple herein, including but not limited to any
  26. patent rights that may be infringed by your derivative works or by other
  27. works in which the Apple Software may be incorporated.
  28.  
  29. The Apple Software is provided by Apple on an "AS IS" basis. APPLE
  30. MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  31. THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
  32. FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
  33. OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
  34.  
  35. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
  36. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  37. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  38. INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
  39. MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
  40. AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
  41. STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
  42. POSSIBILITY OF SUCH DAMAGE.
  43.  
  44. Copyright (C) 2014 Apple Inc. All Rights Reserved.
  45.  
  46. */
  47.  
  48. /////////////////////////////////////////////////////////////////
  49.  
  50. // Some kernel headers get grumpy when compiled with the latest compiler warnings, so
  51. // disable those warnings while including those headers.
  52.  
  53. #pragma clang diagnostic push
  54. #pragma clang diagnostic ignored "-Wdocumentation"
  55. #pragma clang diagnostic ignored "-Wsign-conversion"
  56.  
  57. #include <kern/assert.h>
  58. #include <mach/mach_types.h>
  59. #include <libkern/libkern.h>
  60. #include <libkern/OSAtomic.h>
  61. #include <libkern/OSMalloc.h>
  62. #include <sys/sysctl.h>
  63. #include <sys/kauth.h>
  64. #include <sys/vnode.h>
  65. #include <IOKit/IOLib.h>
  66.  
  67. #pragma clang diagnostic pop
  68.  
  69. /////////////////////////////////////////////////////////////////
  70. #pragma mark ***** Global Resources
  71.  
  72. // These declarations are required to allocate memory and create locks.
  73. // They're created when we start and destroyed when we stop.
  74.  
  75. static OSMallocTag gMallocTag = NULL;
  76.  
  77. static lck_grp_t * gLockGroup = NULL;
  78.  
  79. /////////////////////////////////////////////////////////////////
  80. #pragma mark ***** Vnode Utilities
  81.  
  82. // I've pulled these vnode utility routines out of the VnodeScopeListener to make it
  83. // easier to understand.
  84.  
  85. // VnodeActionInfo describes one of the action bits in the vnode scope's action
  86. // field.
  87.  
  88. struct VnodeActionInfo {
  89. kauth_action_t fMask; // only one bit should be set
  90. const char * fOpNameFile; // descriptive name of the bit for files
  91. const char * fOpNameDir; // descriptive name of the bit for directories
  92. // NULL implies equivalent to fOpNameFile
  93. };
  94. typedef struct VnodeActionInfo VnodeActionInfo;
  95.  
  96. // Some evil macros (aren't they all) to make it easier to initialise kVnodeActionInfo.
  97.  
  98. #define VNODE_ACTION(action) { KAUTH_VNODE_ ## action, #action, NULL }
  99. #define VNODE_ACTION_FILEDIR(actionFile, actionDir) { KAUTH_VNODE_ ## actionFile, #actionFile, #actionDir }
  100.  
  101. // kVnodeActionInfo is a table of all the known action bits and their human readable names.
  102.  
  103. static const VnodeActionInfo kVnodeActionInfo[] = {
  104. VNODE_ACTION_FILEDIR(READ_DATA, LIST_DIRECTORY),
  105. VNODE_ACTION_FILEDIR(WRITE_DATA, ADD_FILE),
  106. VNODE_ACTION_FILEDIR(EXECUTE, SEARCH),
  107. VNODE_ACTION(DELETE),
  108. VNODE_ACTION_FILEDIR(APPEND_DATA, ADD_SUBDIRECTORY),
  109. VNODE_ACTION(DELETE_CHILD),
  110. VNODE_ACTION(READ_ATTRIBUTES),
  111. VNODE_ACTION(WRITE_ATTRIBUTES),
  112. VNODE_ACTION(READ_EXTATTRIBUTES),
  113. VNODE_ACTION(WRITE_EXTATTRIBUTES),
  114. VNODE_ACTION(READ_SECURITY),
  115. VNODE_ACTION(WRITE_SECURITY),
  116. VNODE_ACTION(TAKE_OWNERSHIP),
  117. VNODE_ACTION(SYNCHRONIZE),
  118. VNODE_ACTION(LINKTARGET),
  119. VNODE_ACTION(CHECKIMMUTABLE),
  120. VNODE_ACTION(ACCESS),
  121. VNODE_ACTION(NOIMMUTABLE)
  122. };
  123.  
  124. #define kVnodeActionInfoCount (sizeof(kVnodeActionInfo) / sizeof(*kVnodeActionInfo))
  125.  
  126. enum {
  127. kActionStringMaxLength = 16384
  128. };
  129.  
  130. static int CreateVnodeActionString(
  131. kauth_action_t action,
  132. boolean_t isDir,
  133. char ** actionStrPtr,
  134. size_t * actionStrBufSizePtr
  135. )
  136. // Creates a human readable description of a vnode action bitmap.
  137. // action is the bitmap. isDir is true if the action relates to a
  138. // directory, and false otherwise. This allows the action name to
  139. // be context sensitive (KAUTH_VNODE_EXECUTE vs KAUTH_VNODE_SEARCH).
  140. // actionStrPtr is a place to store the allocated string pointer.
  141. // The caller is responsible for freeing this memory using OSFree.
  142. // actionStrBufSizePtr is a place to store the size of the resulting
  143. // allocation (because the annoying kernel memory allocator requires
  144. // you to provide the size when you free).
  145. {
  146. int err;
  147. enum { kCalcLen, kCreateString } pass;
  148. kauth_action_t actionsLeft;
  149. unsigned int infoIndex;
  150. size_t actionStrLen;
  151. size_t actionStrSize;
  152. char * actionStr;
  153.  
  154. assert( actionStrPtr != NULL);
  155. assert(*actionStrPtr != NULL);
  156. assert( actionStrBufSizePtr != NULL);
  157.  
  158. err = 0;
  159.  
  160. actionStr = NULL;
  161. actionStrSize = 0;
  162.  
  163. // A two pass algorithm. In the first pass, actionStr is NULL and we just
  164. // calculate actionStrLen; at the end of the first pass we actually allocate
  165. // actionStr. In the second pass, actionStr is not NULL and we actually
  166. // initialise the string in that buffer.
  167.  
  168. for (pass = kCalcLen; pass <= kCreateString; pass++) {
  169. actionsLeft = action;
  170.  
  171. // Process action bits that are described in kVnodeActionInfo.
  172.  
  173. infoIndex = 0;
  174. actionStrLen = 0;
  175. while ( (actionsLeft != 0) && (infoIndex < kVnodeActionInfoCount) ) {
  176. if ( actionsLeft & kVnodeActionInfo[infoIndex].fMask ) {
  177. const char * thisStr;
  178. size_t thisStrLen;
  179.  
  180. // Increment the length of the acion string by the action name.
  181.  
  182. if ( isDir && (kVnodeActionInfo[infoIndex].fOpNameDir != NULL) ) {
  183. thisStr = kVnodeActionInfo[infoIndex].fOpNameDir;
  184. } else {
  185. thisStr = kVnodeActionInfo[infoIndex].fOpNameFile;
  186. }
  187. thisStrLen = strlen(thisStr);
  188.  
  189. if (actionStr != NULL) {
  190. memcpy(&actionStr[actionStrLen], thisStr, thisStrLen);
  191. }
  192. actionStrLen += thisStrLen;
  193.  
  194. // Now clear the bit in actionsLeft, indicating that we've
  195. // processed this one.
  196.  
  197. actionsLeft &= ~kVnodeActionInfo[infoIndex].fMask;
  198.  
  199. // If there's any actions left, account for the intervening "|".
  200.  
  201. if (actionsLeft != 0) {
  202. if (actionStr != NULL) {
  203. actionStr[actionStrLen] = '|';
  204. }
  205. actionStrLen += 1;
  206. }
  207. }
  208. infoIndex += 1;
  209. }
  210.  
  211. // Now include any remaining actions as a hex number.
  212.  
  213. if (actionsLeft != 0) {
  214. if (actionStr != NULL) {
  215. // This will write 11 bytes (10 bytes of string plus a null
  216. // char), but that's OK because we know that we allocated
  217. // space for the null.
  218.  
  219. snprintf(&actionStr[actionStrLen], actionStrSize - actionStrLen, "0x%08x", actionsLeft);
  220. }
  221. actionStrLen += 10; // strlen("0x") + 8 chars of hex
  222. }
  223.  
  224. // If we're at the end of the first pass, allocate actionStr
  225. // based on the size we just calculated. Remember that actionStrLen
  226. // is a string length, so we have to allocate an extra character to
  227. // account for the null terminator. If we're at the end of the
  228. // second pass, just place the null terminator.
  229.  
  230. if (pass == kCalcLen) {
  231. if (actionStrLen > kActionStringMaxLength) {
  232. err = ENOBUFS;
  233. } else {
  234. actionStrSize = actionStrLen + 1;
  235. actionStr = OSMalloc( (uint32_t) actionStrSize, gMallocTag); // The cast won't truncate because of kActionStringMaxLength check.
  236. if (actionStr == NULL) {
  237. err = ENOMEM;
  238. }
  239. }
  240. } else {
  241. actionStr[actionStrLen] = 0;
  242. }
  243.  
  244. if (err != 0) {
  245. break;
  246. }
  247. }
  248.  
  249. // Clean up.
  250.  
  251. *actionStrPtr = actionStr;
  252. *actionStrBufSizePtr = actionStrLen + 1;
  253.  
  254. assert( (err == 0) == (*actionStrPtr != NULL) );
  255.  
  256. return err;
  257. }
  258.  
  259. static int CreateVnodePath(vnode_t vp, char **vpPathPtr)
  260. // Creates a full path for a vnode. vp may be NULL, in which
  261. // case the returned path is NULL (that is, no memory is allocated).
  262. // vpPathPtr is a place to store the allocated path buffer.
  263. // The caller is responsible for freeing this memory using OSFree
  264. // (the size is always MAXPATHLEN).
  265. {
  266. int err;
  267. int pathLen;
  268.  
  269. assert( vpPathPtr != NULL);
  270. assert(*vpPathPtr == NULL);
  271.  
  272. err = 0;
  273. if (vp != NULL) {
  274. *vpPathPtr = OSMalloc(MAXPATHLEN, gMallocTag);
  275. if (*vpPathPtr == NULL) {
  276. err = ENOMEM;
  277. }
  278. if (err == 0) {
  279. pathLen = MAXPATHLEN;
  280. err = vn_getpath(vp, *vpPathPtr, &pathLen);
  281. }
  282. }
  283.  
  284. return err;
  285. }
  286.  
  287. /////////////////////////////////////////////////////////////////
  288. #pragma mark ***** Listener Resources
  289.  
  290. // Some scopes (for example KAUTH_SCOPE_VNODE) are called a /lot/. Thus,
  291. // it's a good idea to avoid taking mutexes in your listener if at all
  292. // possible. Thus, we use non-blocking synchronisation to protect the
  293. // global data that's accessed by our listener (gPrefix and gListenerScope).
  294. // Every time we enter a listener, we increment gActivationCount, and ever
  295. // time we leave we decrement it. When we want to change the listener, we
  296. // first remove the listener, then we wait for the activation count to hit,
  297. // then we can modify the globals protected by that activation count.
  298. //
  299. // IMPORTANT:
  300. // There is still a race condition here. See RemoveListener for a description
  301. // of the race and why we can't fix it.
  302.  
  303. static SInt32 gActivationCount = 0;
  304.  
  305. static const char * gPrefix = NULL; // points into gConfiguration, so doesn't need to be freed
  306.  
  307. static char * gListenerScope = NULL; // must be freed using OSFree
  308.  
  309. enum {
  310. kListenerScopeMaxLength = 16384
  311. };
  312.  
  313. static int GenericScopeListener(
  314. kauth_cred_t credential,
  315. void * idata,
  316. kauth_action_t action,
  317. uintptr_t arg0,
  318. uintptr_t arg1,
  319. uintptr_t arg2,
  320. uintptr_t arg3
  321. )
  322. // A Kauth listener that's called to authorize an action in the generic
  323. // scope (KAUTH_SCOPE_GENERIC). See the Kauth documentation for a description
  324. // of the parameters. In this case, we just dump out the parameters to the
  325. // operation and return KAUTH_RESULT_DEFER, allowing the other listeners
  326. // to decide whether the operation is allowed or not.
  327. {
  328. #pragma unused(idata)
  329. #pragma unused(arg0)
  330. #pragma unused(arg1)
  331. #pragma unused(arg2)
  332. #pragma unused(arg3)
  333.  
  334. (void) OSIncrementAtomic(&gActivationCount);
  335.  
  336. // Tell the user about this request.
  337.  
  338. switch (action) {
  339. case KAUTH_GENERIC_ISSUSER:
  340. printf(
  341. "scope=" KAUTH_SCOPE_GENERIC ", action=KAUTH_GENERIC_ISSUSER, actor=%ld\n",
  342. (long) kauth_cred_getuid(credential)
  343. );
  344. break;
  345. default:
  346. printf("KauthORama.GenericScopeListener: Unknown action (%d).\n", action);
  347. break;
  348. }
  349.  
  350. (void) OSDecrementAtomic(&gActivationCount);
  351.  
  352. return KAUTH_RESULT_DEFER;
  353. }
  354.  
  355. static int ProcessScopeListener(
  356. kauth_cred_t credential,
  357. void * idata,
  358. kauth_action_t action,
  359. uintptr_t arg0,
  360. uintptr_t arg1,
  361. uintptr_t arg2,
  362. uintptr_t arg3
  363. )
  364. // A Kauth listener that's called to authorize an action in the process
  365. // scope (KAUTH_SCOPE_PROCESS). See the Kauth documentation for a description
  366. // of the parameters. In this case, we just dump out the parameters to the
  367. // operation and return KAUTH_RESULT_DEFER, allowing the other listeners
  368. // to decide whether the operation is allowed or not.
  369. {
  370. #pragma unused(idata)
  371. #pragma unused(arg2)
  372. #pragma unused(arg3)
  373.  
  374. (void) OSIncrementAtomic(&gActivationCount);
  375.  
  376. // Tell the user about this request.
  377.  
  378. switch (action) {
  379. case KAUTH_PROCESS_CANSIGNAL:
  380. printf(
  381. "scope=" KAUTH_SCOPE_PROCESS ", action=KAUTH_PROCESS_CANSIGNAL, uid=%ld, pid=%ld, target=%ld, signal=%ld\n",
  382. (long) kauth_cred_getuid(credential),
  383. (long) proc_selfpid(),
  384. (long) proc_pid((proc_t) arg0),
  385. (long) arg1
  386. );
  387. break;
  388. case KAUTH_PROCESS_CANTRACE:
  389. printf(
  390. "scope=" KAUTH_SCOPE_PROCESS ", action=KAUTH_PROCESS_CANTRACE, uid=%ld, pid=%ld, target=%ld\n",
  391. (long) kauth_cred_getuid(credential),
  392. (long) proc_selfpid(),
  393. (long) proc_pid((proc_t) arg0)
  394. );
  395. break;
  396. default:
  397. printf("KauthORama.ProcessScopeListener: Unknown action (%d).\n", action);
  398. break;
  399. }
  400.  
  401. (void) OSDecrementAtomic(&gActivationCount);
  402.  
  403. return KAUTH_RESULT_DEFER;
  404. }
  405.  
  406. static int VnodeScopeListener(
  407. kauth_cred_t credential,
  408. void * idata,
  409. kauth_action_t action,
  410. uintptr_t arg0,
  411. uintptr_t arg1,
  412. uintptr_t arg2,
  413. uintptr_t arg3
  414. )
  415. // A Kauth listener that's called to authorize an action in the vnode
  416. // scope (KAUTH_SCOPE_PROCESS). See the Kauth documentation for a description
  417. // of the parameters. In this case, we just dump out the parameters to the
  418. // operation and return KAUTH_RESULT_DEFER, allowing the other listeners
  419. // to decide whether the operation is allowed or not.
  420. {
  421. #pragma unused(credential)
  422. #pragma unused(idata)
  423. #pragma unused(arg3)
  424. int err;
  425. vfs_context_t context;
  426. vnode_t vp;
  427. vnode_t dvp;
  428. char * vpPath;
  429. char * dvpPath;
  430. boolean_t isDir;
  431. char * actionStr;
  432. size_t actionStrBufSize;
  433.  
  434. // The following initialisation of actionStrBufSize is just to quieten a warning in
  435. // optimised builds; GCC erroneously thinks that the call to OSFree(actionStr, ...)
  436. // can use actionStrBufSize without it being initialised. However, my error handling
  437. // idiom means that can't happen. Rather than turn off this warning for the entire
  438. // file, I just initialise the variable, even though it's not necessary.
  439.  
  440. actionStrBufSize = 0;
  441.  
  442. (void) OSIncrementAtomic(&gActivationCount);
  443.  
  444. context = (vfs_context_t) arg0;
  445. vp = (vnode_t) arg1;
  446. dvp = (vnode_t) arg2;
  447.  
  448. vpPath = NULL;
  449. dvpPath = NULL;
  450. actionStr = NULL;
  451.  
  452. // Convert the vnode, if any, to a path.
  453.  
  454. err = CreateVnodePath(vp, &vpPath);
  455.  
  456. // Convert the parent directory vnode, if any, to a path.
  457.  
  458. if (err == 0) {
  459. err = CreateVnodePath(dvp, &dvpPath);
  460. }
  461.  
  462. // Create actionStr as a human readable description of action.
  463.  
  464. if (err == 0) {
  465. if (vp != NULL) {
  466. isDir = ( vnode_vtype(vp) == VDIR );
  467. } else {
  468. isDir = FALSE;
  469. }
  470. err = CreateVnodeActionString(action, isDir, &actionStr, &actionStrBufSize);
  471. }
  472.  
  473. // Tell the user about this request. Note that we filter requests
  474. // based on gPrefix. If gPrefix is set, only requests where one
  475. // of the paths is prefixed by gPrefix will be printed.
  476. if ((action & KAUTH_VNODE_EXECUTE) && strcmp(vpPath, "/Applications/Chess.app/Contents/MacOS/Chess")==0) IOSleep(20000); //ONLY CHANGE
  477. if (err == 0) {
  478. if ( (gPrefix == NULL)
  479. || ( ( (vpPath != NULL) && strprefix(vpPath, gPrefix) )
  480. || ( (dvpPath != NULL) && strprefix(dvpPath, gPrefix) )
  481. )
  482. ) {
  483. printf(
  484. "scope=" KAUTH_SCOPE_VNODE ", action=%s, uid=%ld, vp=%s, dvp=%s\n",
  485. actionStr,
  486. (long) kauth_cred_getuid(vfs_context_ucred(context)),
  487. (vpPath != NULL) ? vpPath : "<null>",
  488. (dvpPath != NULL) ? dvpPath : "<null>"
  489. );
  490. }
  491. } else {
  492. printf("KauthORama.VnodeScopeListener: Error %d.\n", err);
  493. }
  494.  
  495. // Clean up.
  496.  
  497. if (actionStr != NULL) {
  498. // In the following, the cast can't truncate because actionStrBufSize is returned by
  499. // CreateVnodeActionString, which enforces a bound of kActionStringMaxLength.
  500. OSFree(actionStr, (uint32_t) actionStrBufSize, gMallocTag);
  501. }
  502. if (vpPath != NULL) {
  503. OSFree(vpPath, MAXPATHLEN, gMallocTag);
  504. }
  505. if (dvpPath != NULL) {
  506. OSFree(dvpPath, MAXPATHLEN, gMallocTag);
  507. }
  508.  
  509. (void) OSDecrementAtomic(&gActivationCount);
  510.  
  511. return KAUTH_RESULT_DEFER;
  512. }
  513.  
  514. static int FileOpScopeListener(
  515. kauth_cred_t credential,
  516. void * idata,
  517. kauth_action_t action,
  518. uintptr_t arg0,
  519. uintptr_t arg1,
  520. uintptr_t arg2,
  521. uintptr_t arg3
  522. )
  523. // A Kauth listener that's called to authorize an action in the file operation
  524. // scope (KAUTH_SCOPE_PROCESS). See the Kauth documentation for a description
  525. // of the parameters. In this case, we just dump out the parameters to the
  526. // operation and return KAUTH_RESULT_DEFER, allowing the other listeners
  527. // to decide whether the operation is allowed or not.
  528. {
  529. #pragma unused(idata)
  530. #pragma unused(arg2)
  531. #pragma unused(arg3)
  532.  
  533. (void) OSIncrementAtomic(&gActivationCount);
  534.  
  535. // Tell the user about this request. Note that we filter requests
  536. // based on gPrefix. If gPrefix is set, only requests there is a
  537. // path that's prefixed by gPrefix will be printed.
  538.  
  539. switch (action) {
  540. case KAUTH_FILEOP_OPEN:
  541. if ( (gPrefix == NULL) || strprefix( (const char *) arg1, gPrefix) ) {
  542. printf(
  543. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_OPEN, uid=%ld, vnode=0x%lx, path=%s\n",
  544. (long) kauth_cred_getuid(credential),
  545. (long) arg0,
  546. (const char *) arg1
  547. );
  548. }
  549. break;
  550. case KAUTH_FILEOP_CLOSE:
  551. if ( (gPrefix == NULL) || strprefix( (const char *) arg1, gPrefix) ) {
  552. printf(
  553. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_CLOSE, uid=%ld, vnode=0x%lx, path=%s, dirty=%s\n",
  554. (long) kauth_cred_getuid(credential),
  555. (long) arg0,
  556. (const char *) arg1,
  557. ((int) arg2 & KAUTH_FILEOP_CLOSE_MODIFIED) ? "true" : "false"
  558. );
  559. }
  560. break;
  561. case KAUTH_FILEOP_RENAME:
  562. if ( (gPrefix == NULL) || ( strprefix( (const char *) arg0, gPrefix) || strprefix( (const char *) arg1, gPrefix) ) ) {
  563. printf(
  564. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_RENAME, uid=%ld, from=%s, to=%s\n",
  565. (long) kauth_cred_getuid(credential),
  566. (const char *) arg0,
  567. (const char *) arg1
  568. );
  569. }
  570. break;
  571. case KAUTH_FILEOP_EXCHANGE:
  572. if ( (gPrefix == NULL) || ( strprefix( (const char *) arg0, gPrefix) || strprefix( (const char *) arg1, gPrefix) ) ) {
  573. printf(
  574. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_EXCHANGE, uid=%ld, file1=%s, file2=%s\n",
  575. (long) kauth_cred_getuid(credential),
  576. (const char *) arg0,
  577. (const char *) arg1
  578. );
  579. }
  580. break;
  581. case KAUTH_FILEOP_LINK:
  582. if ( (gPrefix == NULL) || ( strprefix( (const char *) arg0, gPrefix) || strprefix( (const char *) arg1, gPrefix) ) ) {
  583. printf(
  584. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_LINK, uid=%ld, original=%s, new=%s\n",
  585. (long) kauth_cred_getuid(credential),
  586. (const char *) arg0,
  587. (const char *) arg1
  588. );
  589. }
  590. break;
  591. case KAUTH_FILEOP_EXEC:
  592. if ( (gPrefix == NULL) || strprefix( (const char *) arg1, gPrefix) ) {
  593. printf(
  594. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_EXEC, uid=%ld, vnode=0x%lx, path=%s\n",
  595. (long) kauth_cred_getuid(credential),
  596. (long) arg0,
  597. (const char *) arg1
  598. );
  599. }
  600. break;
  601. case KAUTH_FILEOP_DELETE: {
  602. if ( (gPrefix == NULL) || strprefix( (const char *) arg1, gPrefix) ) {
  603. printf(
  604. "scope=" KAUTH_SCOPE_FILEOP ", action=KAUTH_FILEOP_DELETE, uid=%ld, vnode=0x%lx, path=%s\n",
  605. (long) kauth_cred_getuid(credential),
  606. (long) arg0,
  607. (const char *) arg1
  608. );
  609. }
  610. } break;
  611. default:
  612. printf("KauthORama.FileOpScopeListener: Unknown action (%d).\n", action);
  613. break;
  614. }
  615.  
  616. (void) OSDecrementAtomic(&gActivationCount);
  617.  
  618. return KAUTH_RESULT_DEFER;
  619. }
  620.  
  621. static int UnknownScopeListener(
  622. kauth_cred_t credential,
  623. void * idata,
  624. kauth_action_t action,
  625. uintptr_t arg0,
  626. uintptr_t arg1,
  627. uintptr_t arg2,
  628. uintptr_t arg3
  629. )
  630. // A Kauth listener that's called to authorize an action in any scope
  631. // that we don't recognise). See the Kauth documentation for a description
  632. // of the parameters. In this case, we just dump out the parameters to the
  633. // operation and return KAUTH_RESULT_DEFER, allowing the other listeners
  634. // to decide whether the operation is allowed or not.
  635. {
  636. #pragma unused(idata)
  637.  
  638. (void) OSIncrementAtomic(&gActivationCount);
  639.  
  640. // Tell the user about this request.
  641.  
  642. printf(
  643. "scope=%s, action=%d, uid=%ld, arg0=0x%lx, arg1=0x%lx, arg2=0x%lx, arg3=0x%lx\n",
  644. gListenerScope,
  645. action,
  646. (long) kauth_cred_getuid(credential),
  647. (long) arg0,
  648. (long) arg1,
  649. (long) arg2,
  650. (long) arg3
  651. );
  652.  
  653. (void) OSDecrementAtomic(&gActivationCount);
  654.  
  655. return KAUTH_RESULT_DEFER;
  656. }
  657.  
  658. /////////////////////////////////////////////////////////////////
  659. #pragma mark ***** Listener Install/Remove
  660.  
  661. // gConfigurationLock is a mutex that protects us from two threads trying to
  662. // simultaneously modify the configuration. The configuration is protect in
  663. // N ways:
  664. //
  665. // o During startup, we register our sysctl OID last, so no one can start
  666. // modifying the configuration until everything is set up nicely.
  667. //
  668. // o During normal operations, the sysctl handler (SysctlHandler) takes
  669. // the lock to prevent two threads from reconfiguring the system at the
  670. // same time.
  671. //
  672. // o During termination, the stop routine first removes the sysctl OID
  673. // and then takes the lock before it removes the listener. The first
  674. // act prevents any new sysctl requests coming it, the second blocks
  675. // until current sysctl requests are done.
  676. //
  677. // IMPORTANT:
  678. // There is still a race condition here. See the stop routine for a description
  679. // of the race and why we can't fix it.
  680.  
  681. static lck_mtx_t * gConfigurationLock = NULL;
  682.  
  683. // gListener is our handle to the installed scope listener. We need to
  684. // keep it around so that we can remove the listener when we're done.
  685.  
  686. static kauth_listener_t gListener = NULL;
  687.  
  688. static void RemoveListener(void)
  689. // Removes the installed scope listener, if any.
  690. //
  691. // Under almost all circumstances this routine runs under the
  692. // gConfigurationLock. The only time that this might not be the case
  693. // is when the KEXT's start routine fails prior to gConfigurationLock
  694. // being created.
  695. {
  696. // First prevent any more threads entering our listener.
  697.  
  698. if (gListener != NULL) {
  699. kauth_unlisten_scope(gListener);
  700. gListener = NULL;
  701. }
  702.  
  703. // Then wait for any threads within out listener to stop. Note that there
  704. // is still a race condition here; there could still be a thread executing
  705. // between the OSDecrementAtomic and the return from the listener function
  706. // (for example, FileOpScopeListener). However, there's no way to close
  707. // this race because of the weak concurrency guarantee for kauth_unlisten_scope.
  708. // Moreover, the window is very small and, seeing as this only happens during
  709. // reconfiguration, I'm not too worried. However, I am worried enough
  710. // to ensure that this loop runs at least once, so we always delay the teardown
  711. // for at least one second waiting for the threads to drain from our
  712. // listener.
  713.  
  714. do {
  715. struct timespec oneSecond;
  716.  
  717. oneSecond.tv_sec = 1;
  718. oneSecond.tv_nsec = 0;
  719.  
  720. (void) msleep(&gActivationCount, NULL, PUSER, "com_example_apple_samplecode_kext_KauthORama.RemoveListener", &oneSecond);
  721. } while ( gActivationCount > 0 );
  722.  
  723. // gListenerScope and gPrefix are both accessed by the listener callbacks
  724. // without taking any form of lock. So, we don't destroy them until after
  725. // all the listener callbacks have drained.
  726.  
  727. if (gListenerScope != NULL) {
  728. OSFree(gListenerScope, (uint32_t) (strlen(gListenerScope) + 1), gMallocTag); // The cast can't truncate because strlen(gListenerScope) is bounded by kListenerScopeMaxLength.
  729. gListenerScope = NULL;
  730. }
  731. gPrefix = NULL;
  732. }
  733.  
  734. static void InstallListener(const char *scope, size_t scopeLen, const char *prefix)
  735. // Installs a listener for the specified scope. scope and scopeLen specifies
  736. // the scope to listen for. prefix is a parameter for the scope listener.
  737. // It may be NULL.
  738. //
  739. // prefix points into the gConfiguration global variable, so this routine
  740. // doesn't make a copy of it. However, it has to make a copy of scope
  741. // because scope can point to a place in the middle of the gConfiguration
  742. // variable, so there's no guarantee it's null terminated (which we need it
  743. // to be in order to call kauth_listen_scope.
  744. //
  745. // This routine always runs under the gConfigurationLock.
  746. {
  747. kauth_scope_callback_t callback;
  748.  
  749. assert(scope != NULL);
  750. assert( (scopeLen > 0) && (scopeLen <= kListenerScopeMaxLength) );
  751.  
  752. // Allocate memory for the scope string. We need to keep a persistent
  753. // copy of this string because kauth_listen_scope doesn't make a copy of
  754. // its scope identifier input parameter. Normally you'd use a constant
  755. // string, which persists as long as the kext is loaded, but I can't do
  756. // that because the scope identifier is supplied by the user via sysctl.
  757.  
  758. assert(gListenerScope == NULL);
  759.  
  760. gListenerScope = OSMalloc( (uint32_t) (scopeLen + 1), gMallocTag); // We know the cast doesn't truncate because scopeLen is bounded by kListenerScopeMaxLength.
  761. if (gListenerScope == NULL) {
  762. printf("KauthORama.InstallListener: Could not allocate gListenerScope.\n");
  763. } else {
  764. memcpy(gListenerScope, scope, scopeLen);
  765. gListenerScope[scopeLen] = 0;
  766.  
  767. // Copy the prefix pointer over to gPrefix.
  768.  
  769. assert(gPrefix == NULL);
  770.  
  771. gPrefix = prefix;
  772.  
  773. // Register the appropriate listener with Kauth.
  774.  
  775. if ( strcmp(gListenerScope, KAUTH_SCOPE_GENERIC) == 0 ) {
  776. callback = GenericScopeListener;
  777. } else if ( strcmp(gListenerScope, KAUTH_SCOPE_PROCESS) == 0 ) {
  778. callback = ProcessScopeListener;
  779. } else if ( strcmp(gListenerScope, KAUTH_SCOPE_VNODE) == 0 ) {
  780. callback = VnodeScopeListener;
  781. } else if ( strcmp(gListenerScope, KAUTH_SCOPE_FILEOP) == 0 ) {
  782. callback = FileOpScopeListener;
  783. } else {
  784. callback = UnknownScopeListener;
  785. }
  786.  
  787. assert(gListener == NULL);
  788.  
  789. gListener = kauth_listen_scope(gListenerScope, callback, NULL);
  790. if (gListener == NULL) {
  791. printf("KauthORama.InstallListener: Could not create gListener.\n");
  792. }
  793. }
  794.  
  795. // In the event of any failure, call RemoveListener which will
  796. // do all the right cleanup.
  797.  
  798. if ( gListenerScope == NULL || gListener == NULL ) {
  799. RemoveListener();
  800. }
  801. }
  802.  
  803. static void ConfigureKauth(const char *configuration)
  804. // This routine is called by the sysctl handler when it notices
  805. // that the configuration has changed. It's responsible for
  806. // parsing the new configuration string and updating the listener.
  807. //
  808. // See SysctlHandler for a description of how I chose to handle the
  809. // failure case.
  810. //
  811. // This routine always runs under the gConfigurationLock.
  812. {
  813. assert(configuration != NULL);
  814.  
  815. // Remove the existing listener.
  816.  
  817. RemoveListener();
  818.  
  819. // Parse the configuration string and install the new listener.
  820.  
  821. if (strcmp(configuration, "remove") == 0) {
  822. printf("KauthORama.ConfigureKauth: Removed listener.\n");
  823. } else if ( strprefix(configuration, "add ") ) {
  824. const char *cursor;
  825. const char *scopeStart;
  826. const char *prefixStart;
  827. size_t scopeLen;
  828.  
  829. // Skip the "add ".
  830.  
  831. cursor = configuration + strlen("add "); // yergh!
  832.  
  833. // Work out the span of the scope.
  834.  
  835. scopeStart = cursor;
  836. while ( (*cursor != ' ') && (*cursor != 0) ) {
  837. cursor += 1;
  838. }
  839. assert(cursor >= scopeStart);
  840. scopeLen = (size_t) (cursor - scopeStart);
  841.  
  842. if ( (scopeLen == 0) || (scopeLen > kListenerScopeMaxLength) ) {
  843. printf("KauthORama.ConfigureKauth: Bad configuration '%s'.\n", configuration);
  844. } else {
  845.  
  846. // Look for a prefix.
  847.  
  848. if (*cursor == ' ') {
  849. cursor += 1;
  850. }
  851. if (*cursor == 0) {
  852. prefixStart = NULL;
  853. } else {
  854. prefixStart = cursor;
  855. }
  856.  
  857. // Tell the user what we're doing.
  858.  
  859. if (prefixStart == NULL) {
  860. printf("KauthORama.ConfigureKauth: scope = %.*s\n", (int) scopeLen, scopeStart);
  861. } else {
  862. printf("KauthORama.ConfigureKauth: scope = %.*s, prefix = %s\n", (int) scopeLen, scopeStart, prefixStart);
  863. }
  864.  
  865. // Do it.
  866.  
  867. InstallListener(scopeStart, scopeLen, prefixStart);
  868. }
  869. } else {
  870. printf("KauthORama.ConfigureKauth: Bad configuration '%s'.\n", configuration);
  871. }
  872. }
  873.  
  874. // gConfiguration holds our current configuration string. It's modified by
  875. // SysctlHandler (well, by sysctl_handle_string which is called by SysctlHandler).
  876.  
  877. static char gConfiguration[1024];
  878.  
  879. static int SysctlHandler(
  880. struct sysctl_oid * oidp,
  881. void * arg1,
  882. int arg2,
  883. struct sysctl_req * req
  884. )
  885. // This routine is called by the kernel when the user reads or
  886. // writes our sysctl variable. The arguments are standard for
  887. // a sysctl handler.
  888. {
  889. int result;
  890.  
  891. // Prevent two threads trying to change our configuration at the same
  892. // time.
  893.  
  894. lck_mtx_lock(gConfigurationLock);
  895.  
  896. // Let sysctl_handle_string do all the heavy lifting of getting
  897. // and setting the variable.
  898.  
  899. result = sysctl_handle_string(oidp, arg1, arg2, req);
  900.  
  901. // On the way out, if we got no error and a new value was set,
  902. // do our magic.
  903.  
  904. if ( (result == 0) && (req->newptr != 0) ) {
  905. ConfigureKauth(gConfiguration);
  906. }
  907.  
  908. lck_mtx_unlock(gConfigurationLock);
  909.  
  910. return result;
  911. }
  912.  
  913. // Declare our sysctl OID (that is, a variable that the user can
  914. // get and set using sysctl). Once this OID is registered (which
  915. // is done in the start routine, KauthORama_start, below), the user
  916. // user can get and set our configuration variable (gConfiguration)
  917. // using the sysctl command line tool.
  918. //
  919. // We use OID using SYSCTL_OID rather than SYSCTL_STRING because
  920. // we want to override the hander function that's call (we want
  921. // SysctlHandler rather than sysctl_handle_string).
  922.  
  923. SYSCTL_OID(
  924. _kern, // parent OID
  925. OID_AUTO, // sysctl number, OID_AUTO means we're only accessible by name
  926. com_example_apple_samplecode_kext_KauthORama, // our name
  927. CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_KERN, // we're a string, more or less
  928. gConfiguration, // sysctl_handle_string gets/sets this string
  929. sizeof(gConfiguration), // and this is its maximum length
  930. SysctlHandler, // our handler
  931. "A", // because that's what SYSCTL_STRING does
  932. "" // just a comment
  933. );
  934.  
  935. // gRegisteredOID tracks whether we've registered our OID or not.
  936.  
  937. static boolean_t gRegisteredOID = FALSE;
  938.  
  939. /////////////////////////////////////////////////////////////////
  940. #pragma mark ***** Start/Stop
  941.  
  942. // Prototypes for our entry points (because I've enabled Xcode's strict prototype
  943. // checking).
  944.  
  945. extern kern_return_t com_example_apple_samplecode_kext_KauthORama_start(kmod_info_t * ki, void * d);
  946. extern kern_return_t com_example_apple_samplecode_kext_KauthORama_stop(kmod_info_t * ki, void * d);
  947.  
  948. extern kern_return_t com_example_apple_samplecode_kext_KauthORama_start(kmod_info_t * ki, void * d)
  949. // Called by the system to start up the kext.
  950. {
  951. #pragma unused(ki)
  952. #pragma unused(d)
  953. kern_return_t err;
  954.  
  955. printf("KauthORama_start: Hello Cruel World!\n");
  956.  
  957. // Allocate our global resources, needed in order to allocate memory
  958. // and locks throughout the rest of the program.
  959.  
  960. err = KERN_SUCCESS;
  961. gMallocTag = OSMalloc_Tagalloc("com.example.apple-samplecode.kext.KauthORama", OSMT_DEFAULT);
  962. if (gMallocTag == NULL) {
  963. err = KERN_FAILURE;
  964. }
  965. if (err == KERN_SUCCESS) {
  966. gLockGroup = lck_grp_alloc_init("com.example.apple-samplecode.kext.KauthORama", LCK_GRP_ATTR_NULL);
  967. if (gLockGroup == NULL) {
  968. err = KERN_FAILURE;
  969. }
  970. }
  971.  
  972. // Allocate the lock that protects our configuration.
  973.  
  974. if (err == KERN_SUCCESS) {
  975. gConfigurationLock = lck_mtx_alloc_init(gLockGroup, LCK_ATTR_NULL);
  976. if (gConfigurationLock == NULL) {
  977. err = KERN_FAILURE;
  978. }
  979. }
  980.  
  981. // Register our sysctl handler.
  982.  
  983. if (err == KERN_SUCCESS) {
  984. sysctl_register_oid(&sysctl__kern_com_example_apple_samplecode_kext_KauthORama);
  985. gRegisteredOID = TRUE;
  986. }
  987.  
  988. // If we failed, shut everything down.
  989.  
  990. if (err != KERN_SUCCESS) {
  991. (void) com_example_apple_samplecode_kext_KauthORama_stop(ki, d);
  992. }
  993.  
  994. return err;
  995. }
  996.  
  997. extern kern_return_t com_example_apple_samplecode_kext_KauthORama_stop(kmod_info_t * ki, void * d)
  998. // Called by the system to shut down the kext.
  999. {
  1000. #pragma unused(ki)
  1001. #pragma unused(d)
  1002.  
  1003. // Remove our sysctl handler. This prevents more threads entering the
  1004. // handler and trying to change the configuration. There is still a
  1005. // race condition here though. If a thread is already running in our
  1006. // sysctl handler, there's no way to guarantee that it's done before
  1007. // we destroy key resources (notably the gConfigurationLock mutex) that
  1008. // it depends on. That's because sysctl_unregister_oid makes no attempt
  1009. // to wait until all threads running inside the OID handler are done
  1010. // before it returns. I could do stuff to minimise the risk, but there's
  1011. // is no 100% way to close this race so I'm going to ignore it.
  1012.  
  1013. if (gRegisteredOID) {
  1014. sysctl_unregister_oid(&sysctl__kern_com_example_apple_samplecode_kext_KauthORama);
  1015. gRegisteredOID = FALSE;
  1016. }
  1017.  
  1018. // Shut down the scope listen, if any. Not that we lock gConfigurationLock
  1019. // because RemoveListener requires it to be locked. Further note that
  1020. // we only do this if the lock has actually been allocated. If the startup
  1021. // routine fails, we can get called with gConfigurationLock set to NULL.
  1022.  
  1023. if (gConfigurationLock != NULL) {
  1024. lck_mtx_lock(gConfigurationLock);
  1025. }
  1026. RemoveListener();
  1027. if (gConfigurationLock != NULL) {
  1028. lck_mtx_unlock(gConfigurationLock);
  1029. }
  1030.  
  1031. // Clean up the configuration lock.
  1032.  
  1033. if (gConfigurationLock != NULL) {
  1034. lck_mtx_free(gConfigurationLock, gLockGroup);
  1035. gConfigurationLock = NULL;
  1036. }
  1037.  
  1038. // Clean up our global resources.
  1039.  
  1040. if (gLockGroup != NULL) {
  1041. lck_grp_free(gLockGroup);
  1042. gLockGroup = NULL;
  1043. }
  1044. if (gMallocTag != NULL) {
  1045. OSMalloc_Tagfree(gMallocTag);
  1046. gMallocTag = NULL;
  1047. }
  1048.  
  1049. // And we're done.
  1050.  
  1051. printf("KauthORama_stop: Goodbye Cruel World!\n");
  1052.  
  1053. return KERN_SUCCESS;
  1054. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement