Skip to main content

Introduction

macOS Penetration Testing Basics

macOS Specific Extensions

macOS uses several specific file extensions which are not completely Unix based. Below is a brief list of them:

  • .dmg : Apple Disk Image files are very frequent for installers.

  • .kext : Kernel Extension. It must follow a specific structure and it's the macOS version of a driver.

  • .plist : Also known as property list stores information in XML or binary format.

    • For most situations, the following tools will open these files regardless of their format. However, if needed, plist files can be converted between binary and XML formats:

      # Display a plist file:
      /usr/bin/defaults read <filename>.plist
      /usr/libexec/PlistBuddy -c print <filename>.plist
      /usr/bin/plutil -p <filename>.plist
      # Check the format of a plist file:
      file <filename>.plist
      <filename>.plist: Apple binary property list

      # Convert a binary plist to an XML plist:
      /usr/bin/plutil -convert xml1 <filename>.plist

      # Check the format after conversion:
      file <filename>.plist
      <filename>.plist: XML 1.0 document text, ASCII text
  • .app : Apple applications that follows directory structure. These appear as a file in the Finder. You can open them as a directory by right-clicking and selecting Show Package Contents.

  • .dylib : Dynamic libraries (similar to Windows DLL files)

  • .pkg : Are the same as xar (eXtensible Archive format). The installer command can be use to install the contents of these files.

    /usr/sbin/installer -pkg <pathToPackage>

File hierarchy layout

  • /Applications: The installed apps should be here. All the users will be able to access them.

  • /bin: Command line binaries

  • /cores: If exists, it's used to store core dumps

  • /dev: Everything is treated as a file so you may see hardware devices stored here.

  • /etc: Configuration files

  • /Library: A lot of subdirectories and files related to preferences, caches and logs can be found here. A Library folder exists in root and on each user's directory.

  • /private: Undocumented but a lot of the mentioned folders are symbolic links to the private directory.

  • /sbin: Essential system binaries (related to administration)

  • /System: File for making macOS run. You should find mostly only Apple specific files here (not third party).

  • /tmp: Files are deleted after 3 days (it's a soft link to /private/tmp)

  • /Users: Home directory for users.

  • /usr: Config and system binaries

  • /var: Log files

  • /Volumes: The mounted drives will apear here.

Special macOS files and folders

  • .DS_Store : This file is on each directory, it saves the attributes and customisations of the directory.

  • .Spotlight-V100 : This folder appears on the root directory of every volume on the system.

  • .metadata_never_index : If this file is at the root of a volume Spotlight won't index that volume.

  • name.noindex : Files and folder with this extension won't be indexed by Spotlight.

  • $HOME/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2: Contains information about downloaded files, like the URL from where they were downloaded.

  • /var/log/system.log : Main log of macOS systems. com.apple.syslogd.plist is responsible for the execution of syslogging (you can check if it's disabled looking for "com.apple.syslogd" in launchctl list.

  • /private/var/log/asl/*.asl : These are the Apple System Logs which may contain interesting information.

  • $HOME/Library/Preferences/com.apple.recentitems.plist : Stores recently accessed files and applications through "Finder".

  • $HOME/Library/Preferences/com.apple.loginitems.plsit : Stores items to launch upon system startup

  • $HOME/Library/Logs/DiskUtility.log : Log file for thee DiskUtility App (info about drives, including USBs)

  • /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist : Data about wireless access points.

  • /private/var/db/launchd.db/com.apple.launchd/overrides.plist : List of daemons deactivated.

  • /private/etc/kcpassword : If autologin is enabled this file will contain the users login password XORed with a key.

User Privileges

Standard User: The most basic of users. This user needs permissions granted from an admin user when attempting to install software into /Applications or performing other advanced tasks. A standard user may create an ~/Applications folder in their ${HOME} directory. They would then be able to install some applications there. Applications that require elevated privileges to perform tasks may fail in this case though.

Admin User: A user who operates most of the time as a standard user but is also allowed to perform root actions such as install software and other administrative tasks. All users belonging to the admin group are given access to root via the sudoers file.

Root: Root is a user allowed to perform almost any action (there are limitations imposed by protections like System Integrity Protection).


macOS Security Mechanisms

Gatekeeper

Gatekeeper is designed to ensure that, by default, only trusted software runs on a user’s Mac. Gatekeeper is used when a user downloads and opens an app, a plug-in or an installer package from outside the App Store. Gatekeeper verifies that the software is signed by an identified developer, is notarised by Apple to be free of known malicious content, and hasn’t been altered. Gatekeeper also requests user approval before opening downloaded software for the first time to make sure the user hasn’t been tricked into running executable code they believed to simply be a data file.

Notarizing

In order for an app to be notarised by Apple, the developer needs to send the app for review. Notarization is not App Review. The Apple notary service is an automated system that scans your software for malicious content, checks for code-signing issues, and returns the results to you quickly. If there are no issues, the notary service generates a ticket for you to staple to your software; the notary service also publishes that ticket online where Gatekeeper can find it.

When the user first installs or runs your software, the presence of a ticket (either online or attached to the executable) tells Gatekeeper that Apple notarized the software. Gatekeeper then places descriptive information in the initial launch dialog indicating that Apple has already checked for malicious content.

File Quarantine

Gatekeeper builds upon File Quarantine. Upon download of an application, a particular extended file attribute ("quarantine flag") can be added to the downloaded file. This attribute is added by the application that downloads the file, such as a web browser or email client, but is not usually added by others like common BitTorrent client software.

When a user executes a "quarentined" file, Gatekeeper is the one that performs the mentioned actions to allow the execution of the file.

It's possible to check it's status and enable/disable (root required) with:

spctl --status
assessments enabled

sudo spctl --enable
sudo spctl --disable

You can also find if a file has the quarantine extended attribute with:

xattr filename.png
com.apple.macl
com.apple.quarantine

Check the value of the extended attributes with:

xattr -l filename.png
com.apple.macl:
00000000 03 00 53 DA 55 1B AE 4C 4E 88 9D CA B7 5C 50 F3 |..S.U..LN.....P.|
00000010 16 94 03 00 27 63 64 97 98 FB 4F 02 84 F3 D0 DB |....'cd...O.....|
00000020 89 53 C3 FC 03 00 27 63 64 97 98 FB 4F 02 84 F3 |.S....'cd...O...|
00000030 D0 DB 89 53 C3 FC 00 00 00 00 00 00 00 00 00 00 |...S............|
00000040 00 00 00 00 00 00 00 00 |........|
00000048
com.apple.quarantine: 0081;607842eb;Brave;F643CD5F-6071-46AB-83AB-390BA944DEC5

Attributes can be removed with:

xattr -d com.apple.quarantine filename.png

#You can also remove this attribute from every file with
find . -iname '*' -print0 | xargs -0 xattr -d com.apple.quarantine

And find all the quarantined files with:

find / -exec ls -ld {} \; 2>/dev/null | grep -E "[x\-]@ " | awk '{printf $9; printf "\n"}' | xargs -I {} xattr -lv {} | grep "com.apple.quarantine"

XProtect

X-Protect is also part of Gatekeeper. It's Apple’s built in malware scanner. It keeps track of known malware hashes and patterns. You can get information about the latest XProtect update running:

system_profiler SPInstallHistoryDataType 2>/dev/null | grep -A 4 "XProtectPlistConfigData" | tail -n 5

MRT: Malware Removal Tool

Should malware make its way onto a Mac, macOS also includes technology to remediate infections. The Malware Removal Tool (MRT) is an engine in macOS that remediates infections based on updates automatically delivered from Apple (as part of automatic updates of system data files and security updates). MRT removes malware upon receiving updated information and it continues to check for infections on restart and login. MRT doesn’t automatically reboot the Mac. (From here)

Automatic Security Updates

Apple issues the updates for XProtect and MRT automatically based on the latest threat intelligence available. By default, macOS checks for these updates daily. Notarisation updates are distributed using CloudKit sync and are much more frequent.

TCC

TCC (Transparency, Consent, and Control) is a mechanism in macOS to limit and control application access to certain features, usually from a privacy perspective. This can include things such as location services, contacts, photos, microphone, camera, accessibility, full disk access, and a bunch more.

From a user’s perspective, they see TCC in action when an application wants access to one of the features protected by TCC. When this happens the user is prompted with a dialog asking them whether they want to allow access or not. This response is then stored in the TCC database.

Check some of the already given permissions to apps in System Preferences ==> Security & Privacy ==> Privacy ==> Files and Folders.

The TCC database is just a sqlite3 database, which makes the task of investigating it much simpler. There are two different databases, a global one in /Library/Application Support/com.apple.TCC/TCC.db and a per-user one located in /Users/<username>/Library/Application Support/com.apple.TCC/TCC.db. The first database is protected from editing with SIP (System Integrity Protection), but you can read them by granting terminal(or your editor) full disk access.

This information was taken from here (read the original source for more information).

Some protected directories:

  • $HOME/Desktop

  • $HOME/Documents

  • $HOME/Downloads

  • iCloud Drive

...

Unprotected directories:

  • $HOME (itself)

  • $HOME/.ssh, $HOME/.aws, etc

  • /tmp

Bypasses

By default an access via SSH will have "Full Disk Access". In order to disable this you need to have it listed but disabled (removing it from the list won't remove those privileges):

Here you can find examples of how some malwares have been able to bypass this protection:


SIP - System Integrity Protection

This protection was enabled to help keep root level malware from taking over certain parts of the operating system. Although this means applying limitations to the root user many find it to be worthwhile trade off.

The most notable of these limitations are that users can no longer create, modify, or delete files inside of the following four directories in general:

  • /System

  • /bin

  • /sbin

  • /usr

Note that there are exceptions specified by Apple: The file /System/Library/Sandbox/rootless.conf holds a list of files and directories that cannot be modified. But if the line starts with an asterisk it means that it can be modified as exception.

For example, the config lines:

				/usr
* /usr/libexec/cups
* /usr/local
* /usr/share/man

Means that /usr cannot be modified except for the 3 allowed folders allowed.

The final exception to these rules is that any installer package signed with the Apple’s certificate can bypass SIP protection, but only Apple’s certificate. Packages signed by standard developers will still be rejected when trying to modify SIP protected directories.

Note that if a file is specified in the previous config file but it doesn't exist, it can be created. This might be used by malware to obtain stealth persistence. For example, imagine that a .plist in /System/Library/LaunchDaemons appears listed but it doesn't exist. A malware may create one and use it as persistence mechanism.

Also, note how files and directories specified in rootless.conf have a rootless extended attribute:

xattr /System/Library/LaunchDaemons/com.apple.UpdateSettings.plist
com.apple.rootless

ls -lO /System/Library/LaunchDaemons/com.apple.UpdateSettings.plist
-rw-r--r--@ 1 root wheel restricted,compressed 412 1 Jan 2020 /System/Library/LaunchDaemons/com.apple.UpdateSettings.plist

SIP handles a number of other limitations as well. Like it doesn't allows for the loading of unsigned kexts. SIP is also responsible for ensuring that no macOS system processes are debugged. This also means that Apple put a stop to dtrace inspecting system processes.

Check if SIP is enabled with:

csrutil status
System Integrity Protection status: enabled.

If you want to disable it, you need to put the computer in recovery mode (start it pressing command+R for Intel or start an keep holding the power button for Apple Silicon) and execute: csrutil disable

You can also configure it to be enabled but without debugging protections by doing:

csrutil enable --without debug

Once you reboot into macOS, you can check the status os SIP which will show the custom configuration:

% csrutil status
System Integrity Protection status: unknown (Custom Configuration).

Configuration:
Apple Internal: disabled
Kext Signing: enabled
Filesystem Protections: enabled
Debugging Restrictions: disabled
DTrace Restrictions: enabled
NVRAM Protections: enabled
BaseSystem Verification: enabled
Boot-arg Restrictions: enabled
Kernel Integrity Protections: enabled
Authenticated Root Requirement: enabled

This is an unsupported configuration, likely to break in the future and leave your machine in an unknown state.

Some other configuration options for SIP:

csrutil enable --no-internal
csrutil enable --without kext
csrutil enable --without fs
csrutil enable --without debug
csrutil enable --without dtrace
csrutil enable --without nvram

Apple Binary Signatures

When checking some malware sample you should always check the signature of the binary as the developer that signed it may be already related with malware.

#Get signer
codesign -vv -d /bin/ls 2>&1 | grep -E "Authority|TeamIdentifier"

#Check if the app’s contents have been modified
codesign --verify --verbose /Applications/Safari.app

#Check if the signature is valid
spctl --assess --verbose /Applications/Safari.app

Installed Software & Services

Check for suspicious applications installed and privileges over the.installed resources:

system_profiler SPApplicationsDataType		#Installed Apps
system_profiler SPFrameworksDataType #Installed framework
lsappinfo list #Installed Apps
launchtl list #Services

User Processes

# will print all the running services under that particular user domain.
launchctl print gui/<users UID>

# will print all the running services under root
launchctl print system

# will print detailed information about the specific launch agent. And if it’s not running or you’ve mistyped, you will get some output with a non-zero exit code: Could not find service “com.company.launchagent.label” in domain for login
launchctl print gui/<user's UID>/com.company.launchagent.label

Launchd

launchd is the first process executed by OX S kernel at startup and the last one to finish at shut down. It should always have the PID 1. This process will read and execute the configurations indicated in the ASEP plists in:

  • /Library/LaunchAgents: Per-user agents installed by the admin

  • /Library/LaunchDaemons: System-wide daemons installed by the admin

  • /System/Library/LaunchAgents: Per-user agents provided by Apple.

  • /System/Library/LaunchDaemons: System-wide daemons provided by Apple.

When a user logs in the plists located in /Users/$USER/Library/LaunchAgents and /Users/$USER/Library/LaunchDemons are started with the logged users permissions.

The main difference between agents and daemons is that agents are loaded when the user logs in and the daemons are loaded at system startup (as there are services like ssh that needs to be executed before any user access the system). Also agents may use GUI while daemons need to run in the background.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.apple.someidentifier</string>
<key>ProgramArguments</key>
<array>
<string>/Users/username/malware</string>
</array>
<key>RunAtLoad</key><true/> <!--Execute at system startup-->
<key>StartInterval</key>
<integer>800</integer> <!--Execute each 800s-->
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key></false> <!--Re-execute if exit unsuccessful-->
<!--If previous is true, then re-execute in successful exit-->
</dict>
</dict>
</plist>

There are cases where an agent needs to be executed before the user logins, these are called PreLoginAgents. For example, this is useful to provide assistive technology at login. They can be found also in /Library/LaunchAgents(see here an example).

New Daemons or Agents config files will be loaded after next reboot or using launchctl load <target.plist> It's also possible to load .plist files without that extension with launchctl -F <file> (however those plist files won't be automatically loaded after reboot). It's also possible to unload with launchctl unload <target.plist> (the process pointed by it will be terminated),

To ensure that there isn't anything (like an override) preventing an Agent or Daemon from running run: sudo launchctl load -w /System/Library/LaunchDaemos/com.apple.smdb.plist

List all the agents and daemons loaded by the current user:

launchctl list

Cron

List the cron jobs of the current user with:

crontab -l

You can also see all the cron jobs of the users in /usr/lib/cron/tabs/ and /var/at/tabs/ (needs root).

In macOS several folders executing scripts with certain frequency can be found in:

ls -lR /usr/lib/cron/tabs/ /private/var/at/jobs /etc/periodic/

There you can find the regular cron jobs, the at jobs (not very used) and the periodic jobs (mainly used for cleaning temporary files). The daily periodic jobs can be executed for example with: periodic daily.

kext

In order to install a KEXT as a startup item, it needs to be installed in one of the following locations:

/System/Library/Extensions
  • KEXT files built into the macOS operating system.
/Library/Extensions
  • KEXT files installed by 3rd party software

You can list currently loaded kext files with:

kextstat #List loaded kext
kextload /path/to/kext.kext #Load a new one based on path
kextload -b com.apple.driver.ExampleBundle #Load a new one based on path
kextunload /path/to/kext.kext
kextunload -b com.apple.driver.ExampleBundle

Login Items

In System Preferences => Users & Groups => Login Items you can find items to be executed when the user logs in.

It is possible to list them, add and remove from the command line:

#List all items:
osascript -e 'tell application "System Events" to get the name of every login item'

#Add an item:
osascript -e 'tell application "System Events" to make login item at end with properties {path:"/path/to/itemname", hidden:false}'

#Remove an item:
osascript -e 'tell application "System Events" to delete login item "itemname"'

Login/Logout Hooks

They are deprecated but can be used to execute commands when a user logs in.

cat > $HOME/hook.sh << EOF
#!/bin/bash
echo 'My is: \`id\`' > /tmp/login_id.txt
EOF
chmod +x $HOME/hook.sh
defaults write com.apple.loginwindow LoginHook /Users/$USER/hook.sh

This setting is stored in /Users/$USER/Library/Preferences/com.apple.loginwindow.plist

defaults read /Users/$USER/Library/Preferences/com.apple.loginwindow.plist
{
LoginHook = "/Users/username/hook.sh";
MiniBuddyLaunch = 0;
TALLogoutReason = "Shut Down";
TALLogoutSavesState = 0;
oneTimeSSMigrationComplete = 1;
}

To delete it:

defaults delete com.apple.loginwindow LoginHook

In the previous example we have created and deleted a LoginHook, it's also possible to create a LogoutHook.

The root user one is stored in /private/var/root/Library/Preferences/com.apple.loginwindow.plist


Passwords

Shadow Passwords

Each user in macOS has their own file which holds the password hash and other information for that particular user. The password has is a PBKDF2-SHA512 hash. There is no "master" /etc/shadow file in macOS.

Shadow passwords are stored with the users configuration in plist files located in /var/db/dslocal/nodes/Default/users/.

There is also a nice Python3 script that will extract the hash and convert it to Hashcat format:

https://gist.github.com/teddziuba/3ff08bdda120d1f7822f3baf52e606c2

CAUTION: This script WILL trip Crowdstrike. Alert gCDC first!

sudo python3 extract_hash.py steve   
$ml$123456$dac54a6185e90802f02c7eae1f3cde1ffd0a81a3db97ef8e5b46dab9b81c270a$7cdd1468956f6ba15baa391faf075e9b68c9247b038a57d916cf54e2601db29b592c2eabfe728c5412101f92146ae5c15bf1383f0183b1ccea38dc44d9f510d1d90e8002915709c0821b088dd6312ecb8af2fe3d31fa98807526f9cda85860baa1d84ee8a3c1a5239219372e02e261eace9d6fdf791ab379793ff36c4345ac38