MacOS 终端安全攻防学习笔记 2023-08-23 08:07:26 Steven Xeldax # MacOS 终端安全攻防学习笔记 [TOC] ## Mac系统常识 ### macOS系统的版本 |macos | 最新版本 | | ------------ | ------------ | | macOS Ventura | 13.2.1 | | macOS Monterey | 12.6.3 | |macOS Big Sur | 11.7.4 | |macOS Catalina | 10.15.7| |macOS Mojave|10.14.6| |macOS High Sierra|10.13.6| |macOS Sierra|10.12.6| |OS X El Capitan|10.11.6| |OS X Yosemite|10.10.5| |OS X Mavericks|10.9.5| |OS X Mountain Lion|10.8.5| |OS X Lion|10.7.5| |Mac OS X Snow Leopard|10.6.8| |Mac OS X Leopard|10.5.8| |Mac OS X Tiger|10.4.11| |Mac OS X Panther|10.3.9| |Mac OS X Jaguar|10.2.8| |Mac OS X Puma|10.1.5| |Mac OS X Cheetah|10.0.4| ### macOS常见概念 #### launchd (类似linux的systemd 系统服务) - 使用 launchctl list 查看正在运行的用户代理 - 使用 sudo launchctl list 查看正在运行的系统守护进程 - 通过指定服务名称查看,例如,launchctl list com.apple.Maps.mapspushd - 使用 defaults read 来检查在 /System/Library/LaunchDaemons 和 /System/Library/LaunchAgents 工作中的 plist - 使用 man,strings 和 Google 来学习运行中的代理和守护进程是什么 举例来说,想要知道某个系统启动的守护进程或者代理干了什么,可以输入以下指令: $ defaults read /System/Library/LaunchDaemons/com.apple.apsd.plist 看一看 Program 或者 ProgramArguments 这两个部分的内容,你就知道哪个二进制文件在运行,此处是 apsd。可以通过 man apsd 查看更多有关它的信息。 再举一个例子,如果你对 Apple Push Nofitications 不感兴趣,可以禁止这个服务: $ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.apsd.plist #### Gatekeeper 和 XProtect Gatekeeper 和 quarantine 系统试图阻止运行(打开)未签名或恶意程序及文件。 XProtect 防止执行已知的坏文件和过时的版本插件,但并不能清除或停止现有的恶意软件。 注意 Quarantine 会将下载的文件信息存储在 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2,这可能会造成隐私泄露的风险。简单的使用 strings 或下面的命令来检查文件: ``` $ echo 'SELECT datetime(LSQuarantineTimeStamp + 978307200, "unixepoch") as LSQuarantineTimeStamp, LSQuarantineAgentName, LSQuarantineOriginURLString, LSQuarantineDataURLString from LSQuarantineEvent;' | sqlite3 /Users/$USER/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2 ``` #### 系统监控 ##### OpenBSM 监测 macOS 具有强大的 OpenBSM 审计功能。你可以使用它来监视进程执行、网络活动等等。 跟踪监测日志,使用 praudit 工具: $ sudo praudit -l /dev/auditpipe ``` header,201,11,execve(2),0,Thu Sep 1 12:00:00 2015, + 195 msec,exec arg,/Applications/.evilapp/rootkit,path,/Applications/.evilapp/rootkit,path,/Applications/.evilapp/rootkit,attribute,100755,root,wheel,16777220,986535,0,subject,drduh,root,wheel,root,wheel,412,100005,50511731,0.0.0.0,return,success,0,trailer,201, header,88,11,connect(2),0,Thu Sep 1 12:00:00 2015, + 238 msec,argument,1,0x5,fd,socket-inet,2,443,173.194.74.104,subject,drduh,root,wheel,root,wheel,326,100005,50331650,0.0.0.0,return,failure : Operation now in progress,4354967105,trailer,88 header,111,11,OpenSSH login,0,Thu Sep 1 12:00:00 2015, + 16 msec,subject_ex,drduh,drduh,staff,drduh,staff,404,404,49271,::1,text,successful login drduh,return,success,0,trailer,111, ``` 看看 audit、praudit、audit_control 的操作手册,其它文件在 /etc/security目录下。 注意虽然 audit 手册 上说 -s 标签会立即同步到配置中,实际上需要重启才能生效。 ##### Dtrace iosnoop 监控磁盘 I/O opensnoop 监控文件打开 execsnoop 监控进程执行 errinfo 监控失败的系统调用 dtruss 监控所有系统调用 运行命令 man -k dtrace 去了解更多信息。 注意系统完整性保护和 DTrace 冲突,所以这些工具可能用不上了。  运行 ps -ef 列出所有正在运行的进程。 你也可以通过活动监视器来查看进程。 launchctl list 和 sudo launchctl list 分别列出用户运行和加载的程序、系统启动守护程序和代理。 网络 列出公开网络文件: ``` $ sudo lsof -Pni ``` 列出各种网络相关的数据结构的内容: ``` $ sudo netstat -atln ``` 你也可以通过命令行使用 Wireshark。 监控 DNS 查询和响应: ``` $ tshark -Y "dns.flags.response == 1" -Tfields \ -e frame.time_delta \ -e dns.qry.name \ -e dns.a \ -Eseparator=, ``` 监控 HTTP 请求和响应: ``` $ tshark -Y "http.request or http.response" -Tfields \ -e ip.dst \ -e http.request.full_uri \ -e http.request.method \ -e http.response.code \ -e http.response.phrase \ -Eseparator=/s ``` 监控 x509 证书: ``` $ tshark -Y "ssl.handshake.certificate" -Tfields \ -e ip.src \ -e x509sat.uTF8String \ -e x509sat.printableString \ -e x509sat.universalString \ -e x509sat.IA5String \ -e x509sat.teletexString \ -Eseparator=/s -Equote=d ``` #### OS X Specific Extensions(文件后缀名) - .dmg: 苹果磁盘映像文件在安装程序中非常常见。 - .kext: 必须遵循特定的结构,是驱动程序的 OS X 版本。 - .plist: 也称为属性列表,以 XML 或二进制格式存储信息。 可以是 XML 或二进制格式。二进制格式可以使用以下命令读取: defaults read config.plist /usr/libexec/PlistBuddy -c print config.plsit plutil -p config.plist - .app: 遵循目录结构的苹果应用程序。 - .dylib: 动态库(类似于 Windows DLL 文件) - .pkg: 与 xar(可扩展存档格式)相同。安装程序命令可用于安装这些文件的内容。 #### File hierarchy layout 文件系统磁盘目录 - /Applications: 安装的应用程序应该在这里。所有的用户都可以访问它们。 - /bin: 命令行二进制文件 - /cores: 用于存储核心转储 - /dev: 硬件设备。 - /etc: 配置文件 - /Library: 可以在此找到与首选项、缓存和日志相关的许多子目录和文件。根目录和每个用户目录中都存在一个 Library 文件夹。 - /private: 未记录,但许多提到的文件夹都是符号链接到私有目录。 - /sbin: 关键系统二进制文件(与管理有关) - /System: 使 OS X 运行的文件。这里主要应该只有苹果特定的文件(不是第三方的)。 - /tmp: 文件将在 3 天后被删除(它是 /private/tmp 的软链接) - /Users: 用户的主目录。 - /usr: 配置和系统二进制文件 - /var: 日志文件 - /Volumes: 挂载的驱动器将出现在这里。 #### MacOS特殊文件和目录 - .DS_Store: 这个文件在每个目录中,保存目录的属性和自定义设置。 - .Spotlight-V100: 这个文件夹出现在系统上每个卷的根目录上。 - .metadata_never_index: 如果这个文件在卷的目录中,spotlight不会索引这个卷 - <name>.noindex: 有此扩展名的文件和文件夹不会被 Spotlight 索引 - $HOME/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV**2: 包含了下载文件的信息 - /var/log/system.log: 系统日志 - /private/var/log/asl/*.asl: 系统日志 - $HOME/Library/Preferences/com.apple.recentitems.plist:存贮最近通过finder访问的文件和应用程序 - $HOME/Library/Preferences/com.apple.loginitems.plsit: 存储在系统启动时启动的项目 - $HOME/Library/Logs/DiskUtility.log: 磁盘实用程序的日志文件(包括USB等驱动器的信息) - /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist: 有关无线接入点的信息 - /private/var/db/launchd.db/com.apple.launchd/overrides.plist: 已经停用的守护进程列表 - /private/etc/kcpassword: 如果启用了自动登录,此文件将包含用户的登录密码与一个密钥进行 XOR 运算的结果。 #### 用户权限User Privileges ##### Common Users Daemon:保留给系统守护进程的用户。默认的守护进程帐户名称通常以“_”开头。 ``` _amavisd, _analyticsd, _appinstalld, _appleevents, _applepay, _appowner, _appserver, _appstore, _ard, _assetcache, _astris, _atsserver, _avbdeviced, _calendar, _captiveagent, _ces, _clamav, _cmiodalassistants, _coreaudiod, _coremediaiod, _coreml, _ctkd, _cvmsroot, _cvs, _cyrus, _datadetectors, _demod, _devdocs, _devicemgr, _diskimagesiod, _displaypolicyd, _distnote, _dovecot, _dovenull, _dpaudio, _driverkit, _eppc, _findmydevice, _fpsd, _ftp, _fud, _gamecontrollerd, _geod, _hidd, _iconservices, _installassistant, _installcoordinationd, _installer, _jabber, _kadmin_admin, _kadmin_changepw, _knowledgegraphd, _krb_anonymous, _krb_changepw, _krb_kadmin, _krb_kerberos, _krb_krbtgt, _krbfast, _krbtgt, _launchservicesd, _lda, _locationd, _logd, _lp, _mailman, _mbsetupuser, _mcxalr, _mdnsresponder, _mobileasset, _mysql, _nearbyd, _netbios, _netstatistics, _networkd, _nsurlsessiond, _nsurlstoraged, _oahd, _ondemand, _postfix, _postgres, _qtss, _reportmemoryexception, _rmd, _sandbox, _screensaver, _scsd, _securityagent, _softwareupdate, _spotlight, _sshd, _svn, _taskgated, _teamsserver, _timed, _timezone, _tokend, _trustd, _trustevaluationagent, _unknown, _update_sharing, _usbmuxd, _uucp, _warmd, _webauthserver, _windowserver, _www, _wwwproxy, _xserverdocs ``` Guest: 用于访客的帐户,具有非常严格的权限。 ``` state=("automaticTime" "afpGuestAccess" "filesystem" "guestAccount" "smbGuestAccess") for i in "${state[@]}"; do sysadminctl -"${i}" status; done; ``` Nobody: 当需要最小权限时,使用此用户执行进程。 Root ##### User Privileges Standard User:最基本的用户。这个用户需要从管理员用户那里授予权限,才能尝试安装软件或执行其他高级任务。他们不能独立完成这些任务。 Admin User:一个用户,大部分时间作为标准用户操作,但也被允许执行诸如安装软件和其他管理任务的根操作。所有属于管理员组的用户都可以通过 sudoers 文件访问 root。 Root:根用户是一个允许执行几乎任何操作的用户(有一些保护措施,如系统完整性保护会有限制)。 例如,根用户将无法将文件放置在 /System 中。 #### 文件ACL 当文件包含 ACL 时,在列出权限时会出现 "+",例如: ``` ls -ld Movies drwx------+ 7 username staff 224 15 Apr 19:42 Movies ``` 您可以使用以下命令读取文件的 ACL: ``` ls -lde Movies drwx------+ 7 username staff 224 15 Apr 19:42 Movies 0: group:everyone deny delete ``` 您可以使用以下命令查找所有包含 ACL 的文件(这很慢): ``` ls -RAle / 2>/dev/null | grep -E -B1 "\d: " ``` #### I/O Kit - Drivers I/O Kit 是 XNU 内核中的开源、面向对象的设备驱动程序框架,负责添加和管理动态加载的设备驱动程序。这些驱动程序允许将模块化代码动态添加到内核中,以便与不同的硬件一起使用。它们位于: /System/Library/Extensions 内置于 OS X 操作系统中的 KEXT 文件。 /Library/Extensions 第三方软件安装的 KEXT 文件。 使用 kextstat 命令打印已加载的驱动程序。 kextstat ``` kextstat Executing: /usr/bin/kmutil showloaded No variant specified, falling back to release Index Refs Address Size Wired Name (Version) UUID <Linked Against> 1 142 0 0 0 com.apple.kpi.bsd (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 2 11 0 0 0 com.apple.kpi.dsep (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 3 170 0 0 0 com.apple.kpi.iokit (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 4 0 0 0 0 com.apple.kpi.kasan (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 5 175 0 0 0 com.apple.kpi.libkern (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 6 154 0 0 0 com.apple.kpi.mach (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 7 88 0 0 0 com.apple.kpi.private (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 8 106 0 0 0 com.apple.kpi.unsupported (20.5.0) 52A1E876-863E-38E3-AC80-09BBAB13B752 <> 9 2 0xffffff8003317000 0xe000 0xe000 com.apple.kec.Libm (1) 6C1342CC-1D74-3D0F-BC43-97D5AD38200A <5> 10 12 0xffffff8003544000 0x92000 0x92000 com.apple.kec.corecrypto (11.1) F5F1255F-6552-3CF4-A9DB-D60EFDEB4A9A <8 7 6 5 3 1> ``` 在列出的前九个驱动程序中,它们加载在地址 0 中。这意味着它们不是真正的驱动程序,而是内核的一部分,无法卸载。 为了查找特定的扩展,您可以使用: ``` kextfind -bundle-id com.apple.iokit.IOReportFamily #按完整的 bundle-id 查找 kextfind -bundle-id -substring IOR #按 bundle-id 中的子字符串查找 ``` 要加载和卸载内核扩展,请执行以下操作: ``` kextload com.apple.iokit.IOReportFamily kextunload com.apple.iokit.IOReportFamily ``` #### MDM (Mobile Device Management) Mobile Device Management(MDM)是一种常用的技术,用于管理终端用户计算设备,如移动电话、笔记本电脑、台式机和平板电脑。在像 iOS、macOS 和 tvOS 这样的 Apple 平台上,它指的是管理员用于管理这些设备的一组特定功能、API 和技术。通过 MDM 管理设备需要一个兼容的商业或开源 MDM 服务器,该服务器实现了对 MDM 协议的支持。 实现集中化设备管理的一种方式 需要实现对 MDM 协议的支持的 MDM 服务器 MDM 服务器可以发送 MDM 命令,例如远程擦除或“安装此配置”。 移动设备管理(MDM)通常使用苹果推送通知服务(APNs)和MDM供应商服务器提供的RESTful API的组合来实现设备和与设备管理产品相关的服务器之间的通信。MDM服务器向设备发送以plist编码的字典形式的命令,所有通信都通过HTTPS进行。MDM服务器可以(并且通常)被固定,以确保通信只与受信任的服务器进行。苹果授予MDM供应商APNs证书以进行身份验证,从而建立设备和MDM服务器之间的安全连接。  #### DEP (Device Enrolment Program)? 设备管理计划(DEP)是由 Apple 提供的一项服务,通过提供 iOS、macOS 和 tvOS 设备的零触摸配置,简化了移动设备管理(MDM)的注册过程。与更传统的部署方法不同,这些方法需要最终用户或管理员采取行动来配置设备,或者手动向 MDM 服务器注册,DEP 的目标是引导这个过程,允许用户拆开一个新的 Apple 设备,并几乎立即将其配置为在组织中使用。 管理员可以利用 DEP 自动将设备注册到他们组织的 MDM 服务器中。一旦设备注册成功,它通常被视为组织拥有的“可信”设备,并且可以接收任意数量的证书、应用程序、WiFi 密码、VPN 配置等等。 允许设备在首次启动时自动注册到预配置的 MDM 服务器中 在设备全新的时候最有用 也可以用于重新配置工作流程(使用全新的操作系统进行擦除) 有三个API:一个用于经销商,一个用于MDM供应商,一个用于设备身份(未经记录):所谓的DEP“云服务”API。这由MDM服务器用于将DEP配置文件与特定设备关联。DEP API用于Apple授权经销商注册设备、检查注册状态和检查交易状态。未记录的私有DEP API。这由Apple设备用于请求其DEP配置文件。在macOS上,cloudconfigurationd二进制文件负责通过此API进行通信。更现代和基于JSON(而不是plist)。苹果授予MDM供应商OAuth令牌。 #### MDM enroll注册的过程步骤 1. 设备记录创建(经销商,苹果):创建新设备的记录。 2. 设备记录分配(客户):将设备分配给MDM服务器。 3. 设备记录同步(MDM供应商):MDM同步设备记录并将DEP配置文件推送到苹果。 4. DEP签到(设备):设备获取其DEP配置文件。 5. 配置文件检索(设备)。 6. 配置文件安装(设备)a. 包括MDM、SCEP和根CA负载。 7. MDM命令发布(设备)  涉及的二进制程序 mdmclient:由操作系统用于与MDM服务器通信。在macOS 10.13.3及更早版本中,它也可以用于触发DEP签到。 profiles:一个实用程序,可用于在macOS上安装、删除和查看配置文件。它也可以用于在macOS 10.13.4及更高版本上触发DEP签到。 cloudconfigurationd:设备注册客户端守护程序,负责与DEP API通信并检索设备注册配置文件。 #### keychains macos的钥匙串 ##### 钥匙串定义 主要的钥匙串有: 用户钥匙串(~/Library/Keychains/login.keychain-db),用于存储特定于用户的凭据,如应用程序密码、互联网密码、用户生成的证书、网络密码和用户生成的公钥/私钥。 系统钥匙串(/Library/Keychains/System.keychain),存储系统范围的凭据,如WiFi密码、系统根证书、系统私钥和系统应用程序密码。 ``` ~/Library/Keychains/login.keychain-db /Library/Keychains/System.keychain ``` ##### 访问钥匙串 ``` # Dump all metadata and decrypted secrets (a lot of pop-ups) security dump-keychain -a -d # Find generic password for the "Slack" account and print the secrets security find-generic-password -a "Slack" -g # Change the specified entrys PartitionID entry security set-generic-password-parition-list -s "test service" -a "test acount" -S ``` ## 在vitrulbox下使用macOS系统 参考如下文章进行部署 https://blog.csdn.net/holdsky/article/details/125854795 https://blog.csdn.net/chy555chy/article/details/51407410 创建macOS虚拟机 打开VirtualBox ,创建虚拟机 关键配置(其他默认): - CPU 2核 (如果安装失败,可以尝试修改为1核,再重新安装) - RAM 8G - 显存 128M - 磁盘空间 80G - 取消软驱启动 - 启用EFI - 使用USB 3.0控制器 此操作在Windows环境之行,且为必要步骤 ``` cd "C:\Program Files\Oracle\VirtualBox" VBoxManage.exe modifyvm "虛擬機名稱" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff VBoxManage setextradata "虛擬機名稱" VBoxInternal/Devices/efi/0/Config/DmiSystemProduct “MacBookPro15,1” VBoxManage setextradata "虛擬機名稱" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Mac-551B86E5744E2388" VBoxManage setextradata "虛擬機名稱" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc" VBoxManage setextradata "虛擬機名稱" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1 ```  ## macOS 防御软件 **Firewalls** Little Snitch: It will monitor every connection made by each process. Depending on the mode (silent allow connections, silent deny connection and alert) it will show you an alert every time a new connection is stablished. It also has a very nice GUI to see all this information. LuLu: Objective-See firewall. This is a basic firewall that will alert you for suspicious connections (it has a GUI but it isn't as fancy as the one of Little Snitch). **Persistence detection** KnockKnock: Objective-See application that will search in several locations where malware could be persisting (it's a one-shot tool, not a monitoring service). BlockBlock: Like KnockKnock by monitoring processes that generate persistence. **Keyloggers detection** ReiKey: Objective-See application to find keyloggers that install keyboard "event taps" **Ransomware detection** RansomWhere: Objective-See application to detect file encryption actions. Mic & Webcam detection OverSight: Objective-See application to detect application that starts using webcam and mic. **Process Injection detencion** Shield: Applicaiton that detects different process injection techniques. ## macOS权限维持 ### launchctl权限维持 launchctl是一个统一的服务管理框架,启动、停止和管理守护进程、应用程序、进程和脚本,他可以创建开机自启的进程包括守护进程。简而言之,可以利用这个东西来进行开机自启,权限维持。 plist脚本一般存放在以下目录: ~/Library/LaunchAgents 由用户自己定义的任务项 /Library/LaunchAgents 由管理员为用户定义的任务项,当用户登陆系统后才会被执行 /Library/LaunchDaemons 由管理员定义的守护进程任务项,只要系统启动了,哪怕用户不登陆系统也会被执行 /System/Library/LaunchAgents 由Mac OS X为用户定义的任务项 /System/Library/LaunchDaemons 由Mac OS X定义的守护进程任务项 ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd > <plist version="1.0"> <dict> <key>Label</key> <string>org.macports.repair</string> <key>ProgramArguments</key> <array> <string>/tmp/chrome.app/Contents/MacOS/auto</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> 这里给几个重要部分键值做一个说明: 1、 <string>org.macports.repair</string> 这里是文件名这里说明文件名是org.macports.repair.plist。 2、 <key>ProgramArguments</key> <array> <string>/tmp/chrome.app/Contents/MacOS/auto</string> </array> 这里是指需要执行的可执行文件路径,这里输入路径后会帮你自动执行这里的auto就是可执行的木马文件。 3、 <key>KeepAlive</key> <true/> 这里是是否保持持续运行,当进程被杀后还会重新执行,根据这里的的true/false 来判断默认false 4、 <key>RunAtLoad</key> <true/> 这里是选择是否开机自启,根据这里的的true/false 来判断默认false ``` launchctl执行命令 加载启动任务 launchctl load /Library/LaunchAgents/example.plist 加载任务, -w选项会在下次登录/重新启动时重新启动 launchctl load -w /Library/LaunchAgents/example.plist 停止并卸载任务。下次登录/重新启动时,任务仍将重新启动 launchctl unload /Library/LaunchAgents/example.plist 该任务将不会在下次登录/重新启动时重新启动 launchctl unload -w /Library/LaunchAgents/example.plist launchctl list sudo launchctl list(有时候一些需要用sudo才能执行的服务就需要用sudo才能查看) 木马持久化运行 将木马放入到我们plist写的指定目录下 ``` <array> <string>/tmp/chrome.app/Contents/MacOS/auto</string> </array> ``` 将木马app chrome.app放入到/tmp目录下即可 执行命令:launchctl load -w /Library/LaunchDaemons/org.macports.repair.plist便会开机自启 ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>mycommand</string> <key>ProgramArguments</key> <array> <string>/path/to/your/command</string> <string>arg1</string> <string>arg2</string> </array> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> </dict> </plist> ``` 在上面的代码中,您需要将<string>/path/to/your/command</string>替换为您要执行的命令的实际路径,并将<string>arg1</string>和<string>arg2</string>替换为您的命令需要的任何参数。 ### Cron 显示当前用户的crontab > crontab -l 也可以看到所有的crontab任务 在/usr/lib/cron/tabs/ 和 /var/at/tabs/ (needs root). ``` ls -lR /usr/lib/cron/tabs/ /private/var/at/jobs /etc/periodic/ ``` 定期脚本(/etc/periodic)是由在/System/Library/LaunchDaemons/com.apple.periodic*中配置的启动守护程序执行的。请注意,如果将脚本存储在/etc/periodic/中以提升特权,则将以文件所有者的身份执行该脚本。 ``` ls -l /System/Library/LaunchDaemons/com.apple.periodic* -rw-r--r-- 1 root wheel 887 May 13 00:29 /System/Library/LaunchDaemons/com.apple.periodic-daily.plist -rw-r--r-- 1 root wheel 895 May 13 00:29 /System/Library/LaunchDaemons/com.apple.periodic-monthly.plist -rw-r--r-- 1 root wheel 891 May 13 00:29 /System/Library/LaunchDaemons/com.apple.periodic-weekly.plist ``` ### kext 内核模块 ``` 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 ``` #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"' ``` 文件存储位置 > /Users/<username>/Library/Application Support/com.apple.backgroundtaskmanagementagent ### Login/Logout Hooks 虽然它们已被弃用,但仍可用于在用户登录时执行命令。此设置存储 ``` 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 ``` 在/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; } ``` 删除 > defaults delete com.apple.loginwindow LoginHook 在之前的示例中,我们创建并删除了一个LoginHook,也可以创建一个LogoutHook。Root用户的LogoutHook存储在/private/var/root/Library/Preferences/com.apple.loginwindow.plist中。 ### Profiles 配置文件可以强制用户使用特定的浏览器设置、DNS代理设置或VPN设置。还有许多其他有效载荷可用,使它们容易被滥用。您可以运行以下命令枚举它们: ls -Rl /Library/Managed\ Preferences/ ### Startup Items ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Description</key> <string>This is a description of this service</string> <key>OrderPreference</key> <string>None</string> <!--Other req services to execute before this --> <key>Provides</key> <array> <string>superservicename</string> <!--Name of the services provided by this file --> </array> </dict> </plist> ``` ## MacOS Command Cheatsheat ``` #User enumeration dscl . ls /Users dscl . read /Users/[username] dscl "/Active Directory/TEST/All Domains" ls /Users dscl "/Active Directory/TEST/All Domains" read /Users/[username] dscacheutil -q user #Computer enumeration dscl "/Active Directory/TEST/All Domains" ls /Computers dscl "/Active Directory/TEST/All Domains" read "/Computers/[compname]$" #Group enumeration dscl . ls /Groups dscl . read "/Groups/[groupname]" dscl "/Active Directory/TEST/All Domains" ls /Groups dscl "/Active Directory/TEST/All Domains" read "/Groups/[groupname]" #Domain Information dsconfigad -show 获取macos系统加入ad的信息 echo show com.apple.opendirectoryd.ActiveDirectory | scutil dscl "/Active Directory/[Domain]/All Domains" ls / #System info date cal uptime #show time from starting w #list users whoami #this user finger username #info about user uname -a #sysinfo cat /proc/cpuinfo #processor cat /proc/meminfo #memory free #check memory df #check disk launchctl list #List services atq #List "at" tasks for the user sysctl -a #List kernel configuration diskutil list #List connected hard drives nettop #Monitor network usage of processes in top style system_profiler SPSoftwareDataType #System info system_profiler SPPrintersDataType #Printer system_profiler SPApplicationsDataType #Installed Apps system_profiler SPFrameworksDataType #Instaled framework system_profiler SPDeveloperToolsDataType #Developer tools info system_profiler SPStartupItemDataType #Startup Items system_profiler SPNetworkDataType #Network Capabilities system_profiler SPFirewallDataType #Firewall Status system_profiler SPNetworkLocationDataType #Known Network system_profiler SPBluetoothDataType #Bluetooth Info system_profiler SPEthernetDataType #Ethernet Info system_profiler SPUSBDataType #USB info system_profiler SPAirPortDataType #Airport Info #Searches mdfind password #Show all the files that contains the word password mfind -name password #List all the files containing the word password in the name #Open any app open -a <Application Name> --hide #Open app hidden open some.doc -a TextEdit #Open a file in one application #Computer doesn't go to sleep caffeinate & #Screenshot # This will ask for permission to the user screencapture -x /tmp/ss.jpg #Save screenshot in that file #Get clipboard info pbpaste #system_profiler system_profiler --help #This command without arguments take lot of memory and time. system_profiler -listDataTypes system_profiler SPSoftwareDataType SPNetworkDataType #Network arp -i en0 -l -a #Print the macOS device's ARP table lsof -i -P -n | grep LISTEN smbutil statshares -a #View smb shares mounted to the hard drive #networksetup - set or view network options: Proxies, FW options and more networksetup -listallnetworkservices #List network services networksetup -listallhardwareports #Hardware ports networksetup -getinfo Wi-Fi #Wi-Fi info networksetup -getautoproxyurl Wi-Fi #Get proxy URL for Wifi networksetup -getwebproxy Wi-Fi #Wifi Web proxy networksetup -getftpproxy Wi-Fi #Wifi ftp proxy #Brew brew list #List installed brew search <text> #Search package brew info <formula> brew install <formula> brew uninstall <formula> brew cleanup #Remove older versions of installed formulae. brew cleanup <formula> #Remove older versions of specified formula. #Make the machine talk say hello -v diego #spanish: diego, Jorge, Monica #mexican: Juan, Paulina #french: Thomas, Amelie ########### High privileges actions sudo purge #purge RAM #Sharing preferences sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist (enable ssh) sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist (disable ssh) #Start apache sudo apachectl (start|status|restart|stop) ##Web folder: /Library/WebServer/Documents/ #Remove DNS cache dscacheutil -flushcache sudo killall -HUP mDNSResponder system_profiler SPApplicationsDataType #Installed Apps system_profiler SPFrameworksDataType #Instaled framework lsappinfo list #Installed Apps launchtl list #Services Specific MacOS Commands #System info date cal uptime #show time from starting w #list users whoami #this user finger username #info about user uname -a #sysinfo cat /proc/cpuinfo #processor cat /proc/meminfo #memory free #check memory df #check disk launchctl list #List services atq #List "at" tasks for the user sysctl -a #List kernel configuration diskutil list #List connected hard drives nettop #Monitor network usage of processes in top style system_profiler SPSoftwareDataType #System info system_profiler SPPrintersDataType #Printer system_profiler SPApplicationsDataType #Installed Apps system_profiler SPFrameworksDataType #Instaled framework system_profiler SPDeveloperToolsDataType #Developer tools info system_profiler SPStartupItemDataType #Startup Items system_profiler SPNetworkDataType #Network Capabilities system_profiler SPFirewallDataType #Firewall Status system_profiler SPNetworkLocationDataType #Known Network system_profiler SPBluetoothDataType #Bluetooth Info system_profiler SPEthernetDataType #Ethernet Info system_profiler SPUSBDataType #USB info system_profiler SPAirPortDataType #Airport Info #Searches mdfind password #Show all the files that contains the word password mfind -name password #List all the files containing the word password in the name #Open any app open -a <Application Name> --hide #Open app hidden open some.doc -a TextEdit #Open a file in one application #Computer doesn't go to sleep caffeinate #Screenshot # This will ask for permission to the user screencapture -x /tmp/ss.jpg #Save screenshot in that file #Get clipboard info pbpaste #system_profiler system_profiler --help #This command without arguments take lot of memory and time. system_profiler -listDataTypes system_profiler SPSoftwareDataType SPNetworkDataType #Network arp -i en0 -l -a #Print the macOS device's ARP table lsof -i -P -n | grep LISTEN smbutil statshares -a #View smb shares mounted to the hard drive #networksetup - set or view network options: Proxies, FW options and more networksetup -listallnetworkservices #List network services networksetup -listallhardwareports #Hardware ports networksetup -getinfo Wi-Fi #Wi-Fi info networksetup -getautoproxyurl Wi-Fi #Get proxy URL for Wifi networksetup -getwebproxy Wi-Fi #Wifi Web proxy networksetup -getftpproxy Wi-Fi #Wifi ftp proxy #Brew brew list #List installed brew search <text> #Search package brew info <formula> brew install <formula> brew uninstall <formula> brew cleanup #Remove older versions of installed formulae. brew cleanup <formula> #Remove older versions of specified formula. #Make the machine talk say hello -v diego #spanish: diego, Jorge, Monica #mexican: Juan, Paulina #french: Thomas, Amelie ########### High privileges actions sudo purge #purge RAM #Sharing preferences sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist (enable ssh) sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist (disable ssh) #Start apache sudo apachectl (start|status|restart|stop) ##Web folder: /Library/WebServer/Documents/ #Remove DNS cache dscacheutil -flushcache sudo killall -HUP mDNSResponder Installed Software & Services Check for suspicious applications installed and privileges over the.installed resources: system_profiler SPApplicationsDataType #Installed Apps system_profiler SPFrameworksDataType #Instaled 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 Create a user Without prompts /usr/bin/dscl . -create /Users/tccadmin /usr/bin/dscl . -create /Users/tccadmin tcc123 /usrbin/dscl . -create /Users/tccadmin RealName "TCC Admin" /usr/bin/dscl . -append /Groups/admin GroupMembership tccadmin ``` ``` # 提权 sudo dseditgroup -o edit -a steven -t user admin # 降权 sudo dseditgroup -o edit -d steven -t user admin delete user sudo /usr/bin/dscl . -delete /Users/dylan ########## # 获取当前登录用户名 /usr/bin/stat -f%Su /dev/console # 将当前用户添加到developer用户组 sudo dscl . append /Groups/_developer GroupMembership {username} ########## sudo dscl . create /Groups/docker sudo dseditgroup -o edit -a $(whoami) -t user docker . docker ps -a ####### get uuid UUID="$(/usr/sbin/system_profiler SPHardwareDataType | grep "Hardware UUID" | awk -F ": " '{print $2}' | xargs)" ##### # add user with admin privileges # . /etc/rc.common dscl . create /Users/$UserName dscl . create /Users/$UserName RealName $UserName LastID=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -1` NextID=$((LastID + 1)) dscl . create /Users/$UserName UniqueID $NextID dscl . create /Users/$UserName PrimaryGroupID $PrimaryGroupID dscl . create /Users/$UserName UserShell /bin/bash dscl . create /Users/$UserName NFSHomeDirectory /Users/$UserName # hide this account in the login window dscl . create /Users/$UserName IsHidden 1 dscl . passwd /Users/$UserName $PASSWORD createhomedir -u $UserName -c ``` https://github.com/crhuber/mac-cheatsheet ## 参考资料 https://www.freebuf.com/articles/web/361184.html https://book.hacktricks.xyz/macos-hardening/macos-red-teaming https://book.hacktricks.xyz/macos-hardening/macos-useful-commands https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-users https://book.hacktricks.xyz/macos-hardening/macos-auto-start-locations