Skip to content

Instantly share code, notes, and snippets.

@thimslugga
Last active April 11, 2025 07:06
Show Gist options
  • Save thimslugga/17adbee3c45713594c091e80ecd0cf69 to your computer and use it in GitHub Desktop.
Save thimslugga/17adbee3c45713594c091e80ecd0cf69 to your computer and use it in GitHub Desktop.
EC2 Mac Tuning Tips
#!/bin/bash
#set -euo pipefail
#IFS=$'\n\t'
# https://stream.lib.utah.edu/index.php?c=browse&m=results&q=Mac+Admins&sort=newest
# https://macos-defaults.com/
# https://ss64.com/mac/defaults.html
# https://real-world-systems.com/docs/defaults.1.html
#
# https://babodee.wordpress.com/2016/04/09/launchctl-2-0-syntax/
# https://keith.github.io/xcode-man-pages/launchd.plist.5.html
# https://www.real-world-systems.com/docs/launchdPlist.1.html
#
# https://mroi.github.io/apple-internals/
# https://theapplewiki.com/wiki/Main_Page
# https://github.com/mathiasbynens/dotfiles/blob/main/.macos
#
# sudo systemsetup -printcommands
# Ask for the administrators password upfront
#sudo -v
function isRoot() {
if [[ "${EUID}" -ne 0 ]]; then
echo >&2 "script requires super user privileges e.g. sudo .."
exit 1
fi
}
isRoot
function commandExists() {
local cmd
cmd="$1"
if command -v "${cmd}" &> /dev/null; then
echo "command installed: ${cmd}"
return 0
else
return 1
fi
}
# Block until all network services have completed configuring or have timed out in the process of configuring
function waitfornetwork() {
ipconfig waitall
}
waitfornetwork
function askToContinue() {
read -p "Do you want to continue? [Y/n] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo -e "Closing...\n"
exit
fi
}
# Quit any system preference windows to prevent conflict related to settings we are changing.
#osascript -e 'tell application "System Preferences" to quit'
#osascript -e 'tell application "System Events" to get every window of (every process whose class of windows contains window'
# Usage: keepAlive, update existing `sudo` time stamp until `.macos` has finished
function keepAlive() {
while true; do
sudo -n true
sleep 60
kill -0 "$$" || exit
done 2>/dev/null &
}
function run_command() {
echo "Running: $1"
eval $1
if [ $? -eq 0 ]; then
echo "Success: $1"
else
echo "Failed: $1"
fi
}
# Usage: runAsUser <command> <arguments>
function runAsUser() {
# https://launchd-dev.macosforge.narkive.com/kilDaid6/starting-agents-in-specific-gui-sessions
# https://scriptingosx.com/2020/08/running-a-command-as-another-user/
local current_user current_user_uid
current_user=$(stat -f%Su /dev/console)
#current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
current_user_uid=$(id -u "${current_user}")
#if [ -z "${current_user}" -o "${current_user}" = "loginwindow" ]; then
# echo "error: no user logged in"
# exit 1
#fi
if [ "${current_user}" != "loginwindow" ]; then
launchctl asuser "${current_user_uid}" sudo -u "${current_user}" "${@}"
#launchctl asuser "${current_user_uid}" sudo -iu "${current_user}" "${@}"
#launchctl asuser "${current_user_uid}" /path/to/command arguments
#launchctl asuser "${UID:-"$(id -u)"}" ${1+"$@"}
else
echo "error: no user logged in"
#exit 1
fi
}
function runAsRoot() {
local username uid
username=root
uid=1
# -i, Run the shell as a login shell.
# -u, Run the command as another target user.
sudo launchctl asuser "${uid}" sudo -iu "${uid}" "${@}"
}
function extendVolume() {
# Extend the volume size
PHYSDISK=$(/usr/sbin/diskutil list physical external | head -n1 | cut -d" " -f1)
APFS_CONTAINER=$(/usr/sbin/diskutil list physical external | grep "Apple_APFS" | tr -s " " | cut -d" " -f8)
sudo /usr/sbin/diskutil repairDisk $PHYSDISK
sudo diskutil apfs resizeContainer $APFSCONT 0
sudo diskutil apfs resizeContainer $APFS_CONTAINER 0
}
function getProxyDetails() {
local p
p="${1}"
enable="$(scutil --proxy | grep "${p}Enable" | cut -d: -f2)"
host="$(scutil --proxy | grep "${p}Proxy" | cut -d: -f2 | tr -d " ")"
port="$(scutil --proxy | grep "${p}Port" | cut -d: -f2 | tr -d " ")"
if [[ "${enable}" -eq 1 ]]; then
echo "${host}:${port}"
fi
}
function setProxyDetails() {
http_proxy=$(getProxyDetails HTTP)
https_proxy=$(getProxyDetails HTTPS)
ftp_proxy=$(getProxyDetails FTP)
[ -n "${http_proxy}" ] && echo "export http_proxy=${http_proxy}"
[ -n "${https_proxy}" ] && echo "export https_proxy=${https_proxy}"
[ -n "${ftp_proxy}" ] && echo "export ftp_proxy=${ftp_proxy}"
}
# Get the macOS full version details
#system_profiler SPSoftwareDataType
#/usr/libexec/PlistBuddy -x -c 'Print "ProductVersion"' /System/Library/CoreServices/SystemVersion.plist
#/usr/bin/plutil -p /System/Library/CoreServices/SystemVersion.plist
function macosFullVersion() {
local version
version="$(sw_vers --productVersion)"
echo "${version}"
}
# Get the macOS major version details
function macosMajorVersion() {
local major
major="$(sw_vers --productVersion | cut -d '.' -f1)"
echo "${major_version}"
}
if [[ $(macosMajorVersion) -ge 14 ]]; then
echo "macOS version is 14 or greater."
# add commands here
else
echo "macOS version appears to be less than 14."
fi
# Create backup of defaults and launchd
function backupDefaults() {
/usr/bin/defaults read | tee ./defaults.pre.txt
}
# Backup the current launchd configuration
function backupLaunchdServices() {
/bin/launchctl list | tee ./launchctl-list.pre.txt
/bin/launchctl list | grep -E '^[0-9]+' | tee ./launchctl-enabled-services.txt
#/usr/bin/find /var/db/com.apple.xpc.launchd/ -type f -print -exec defaults read {} \; 2>/dev/null
#/usr/bin/defaults read /System/Library/LaunchDaemons/com.apple.apsd.plist
}
function backupSystemProfile() {
/usr/sbin/system_profiler SPConfigurationProfileDataType -json | tee ./system-profile.pre.json
}
function getHostInfo() {
local host_info
host_info=$(hostinfo)
echo "${host_info}"
}
function getHostHwDetails() {
local host_hw_details
host_hw_details=$(/usr/sbin/system_profiler SPHardwareDataType)
echo "${host_hw_details}"
}
# Get the host hardware UUID
function getHostHwUUID() {
local host_hw_uuid=''
#host_hw_uuid=$(system_profiler SPHardwareDataType | awk '/Hardware UUID/{print $3}')
host_hw_uuid=$(ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}')
echo "${host_hw_uuid}"
}
# Get specific Mac cpu details
function getHostHwCpu() {
local host_hw_cpu=''
host_hw_cpu=$(sysctl -n machdep.cpu.brand_string)
echo "${host_hw_cpu}"
}
# Get the status of SIP
function getSipStatus() {
if hash csrutil 2>/dev/null; then
local sip_status
sip_status="$(csrutil status | head -n 1)"
if [[ "$sip_status" = "status: enabled" ]]; then
echo "SIP is enabled."
return 0
elif [[ "${sip_status}" = "status: enabled (Custom Configuration)" ]]; then
echo "SIP appears to be partially enabled."
return 0
elif [[ "${sip_status}" = *"status: disabled"* ]]; then
echo "SIP is disabled."
return 0
else
echo "Unknown SIP status."
return 1
fi
else
echo "csrutil command not found. unable to proceed."
return 1
fi
}
function nudgeToAllowSystemExtensions() {
# https://developer.apple.com/library/archive/technotes/tn2459/_index.html
# If security extension doesn't show up in system preferences, you
# may be able to poke the system to rescan and show it again.
# Library/Application Support and /Library/Extensions
sudo touch /Library/Extensions
#sudo touch /System/Library/Extensions && sudo kextcache -u /
#sudo update_dyld_shared_cache -force
sync
systemextensionsctl list
#codesign -display -r - <path to application>
}
# Get the current locale
function getCurrentLocale() {
# sudo defaults read -g AppleLocale
local curr_locale
curr_locale=$(defaults read -g AppleLocale)
echo "${curr_locale}"
}
function setCurerntLocale() {
# Set current locale to UTF-8
echo "Set the following settings to match the "United States" region default.."
export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"
defaults write -globalDomain AppleLocale "en_US"
defaults write -globalDomain AppleLanguages "(en)"
defaults write -globalDomain AppleMeasurementUnits "Inches"
defaults write -globalDomain AppleTemperatureUnit "Fahrenheit"
defaults write -globalDomain AppleMetricUnits -bool false
}
# Install Apple Rosetta 2 on Apple Silicon based hosts
function installRosetta2() {
local mac_arch
mac_arch="$(arch)"
if [[ "${mac_arch}" == 'arm64' ]]; then
echo "Installing Rosetta 2..."
/usr/sbin/softwareupdate --install-rosetta --agree-to-license
else
echo "Rosetta 2 is not required on this architecture."
fi
}
# Cleanup Rosetta 2 JIT bytecode cache
# https://eclecticlight.co/2021/01/06/rosetta-2-and-its-jit-compiled-code/
function cleanupRosettaJITBytecodeCache() {
local storage_space
storage_space="${1}"
sudo /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -P -total "${storage_space}" /System/Volumes/Data
}
#cleanupRosettaJITBytecodeCache "500G"
# Force empty the trash of the currently logged in user
function emptyUsersTrash() {
local current_user
current_user="$(stat -f "%Su" /dev/console)"
if [ -z "$current_user" ]; then
echo "Error: Unable to determine the current user. Aborting."
exit 1
else
echo "Emptying trash for user: $current_user"
su "${current_user}" -c "rm -rf ~/.Trash/*"
#sudo rm -rf /Users/"$current_user"/.Trash/*
return 0
fi
}
# Disable macOS GateKeeper runtime protection service
function disableGateKeeper() {
# https://support.apple.com/guide/security/gatekeeper-and-runtime-protection-sec5599b66df/web
sudo spctl --master-disable && spctl --status
}
function disableSetupAssistant() {
# System file created after initial setup
test ! -f /private/var/db/.AppleSetupDone && sudo touch /private/var/db/.AppleSetupDone
# Remove configuration profiles
#touch /Volumes/Data/private/var/db/.AppleSetupDone
#launchctl disable system/com.apple.ManagedClient.enroll
#rm -rf /var/db/ConfigurationProfiles/Settings/.{cloudConfigHasActivationRecord,cloudConfigRecordFound}
#touch /var/db/ConfigurationProfiles/Settings/.{cloudConfigProfileInstalled,cloudConfigRecordNotFound}
#rm -rf /Volumes/Macintosh\ HD/var/db/ConfigurationProfiles/Settings/.{cloudConfigHasActivationRecord,cloudConfigRecordFound}
#touch /Volumes/Macintosh\ HD/var/db/ConfigurationProfiles/Settings/.{cloudConfigProfileInstalled,cloudConfigRecordNotFound}
#sudo /bin/sh -c 'echo "0.0.0.0 iprofiles.apple.com" >> /etc/hosts'
#sudo /bin/sh -c 'echo "0.0.0.0 mdmenrollment.apple.com" >> /etc/hosts'
#sudo /bin/sh -c 'echo "0.0.0.0 deviceenrollment.apple.com" >> /etc/hosts'
#sudo /bin/sh -c 'echo "0.0.0.0 gdmf.apple.com" >> /etc/hosts'
#/sbin/fsck -fy
# For Catalina it is: /sbin/mount -uw /System/Volumes/Data
#/sbin/mount -uw /
#rm var/db/dslocal/nodes/Default/users/admin.plist
#rm -r /users/admin
#rm var/db/.AppleSetupDone
rm "/Volumes/Macintosh HD/var/db/.AppleSetupDone"
rm "/Volumes/Macintosh HD/Library/Keychains/apsd.keychain"
rm -rf "/Volumes/Macintosh HD/var/db/ConfigurationProfiles/"
rm -rf "/Volumes/Macintosh HD/Users/user"
# https://gist.github.com/sghiassy/a3927405cf4ffe81242f4ecb01c382ac?permalink_comment_id=5138350#gistcomment-5138350
# https://raw.githubusercontent.com/maclifevn/bypasmdm/main/mdm.sh
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -create "/Local/Default/Users/$username"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -create "/Local/Default/Users/$username" UserShell "/bin/zsh"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -create "/Local/Default/Users/$username" RealName "$realname"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -create "/Local/Default/Users/$username" UniqueID "501"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -create "/Local/Default/Users/$username" PrimaryGroupID "20"
#mkdir -p "/Volumes/Data/Users/$username"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -create "/Local/Default/Users/$username" NFSHomeDirectory "/Users/$username"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -passwd "/Local/Default/Users/$username" "$password"
#dscl -f /Volumes/Data/private/var/db/dslocal/nodes/Default localhost -append "/Local/Default/Groups/admin" GroupMembership "$username"
}
# Update APFS Preboot volume
# https://eclecticlight.co/2024/04/22/apfs-command-tools/
function updateApfsPreboot() {
diskutil apfs list
#sudo update_dyld_shared_cache -root /
# To force the syncing of the local Open Directory and AFPS credentials store.
sudo diskutil apfs updatePreboot /
#sudo diskutil apfs listusers /
}
# Get the APFS volume encryption details
function getApfsAuthCredentials() {
diskutil apfs list
diskutil apfs listusers /
diskutil apfs listCryptoUsers /
}
function getLocalUserList() {
dscl . -list /Users | grep -v '^_'
}
function getLocalGroupsList() {
dscl . -list /Groups
}
function getLocalGroupMembership() {
local groupname
groupname="${1}"
dscl . -read /Groups/"${groupname}"
}
function getLocalUserDetails() {
local username
username="${1}"
dscl . -read /Users/"${username}"
#grab the users plist file from /private/var/db/dslocal/nodes/Default/users/
}
# Create new user
function addNewUser() {
local username realname password
username="${1}"
realname="${2}"
password="${3}"
# Create the user
}
# Prevent the user from obtaining a secureToken when setting password.
function preventSecureToken() {
local user
user="${1:-ec2-user}"
sudo /usr/bin/dscl . append /Users/"${user}" AuthenticationAuthority ";DisabledTags;SecureToken"
}
# Set the password for the ec2-user, this should result in ec2-user getting a Secure Token
function setUserPassword() {
local user
user="${1:-ec2-user}"
sudo /usr/bin/dscl . -passwd /Users/"${user}"
}
setUserPassword ec2-user
function getSecureTokenStatus() {
local user
user="${1:-ec2-user}"
sysadminctl -secureTokenStatus "${user}"
#sudo sysadminctl interactive -secureTokenStatus "${user}"
}
function setupUserEnvironment() {
# Shell environment stuff
touch ~/.{profile,bash_profile,bashrc}
cat <<'EOF' | tee -a "$HOME"/.bashrc
# Bash
export BASH_SILENCE_DEPRECATION_WARNING=1
# Language
export LANG=en_US.UTF-8
# Homebrew
export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_ANALYTICS=1
export HOMEBREW_NO_GOOGLE_ANALYTICS=1
export HOMEBREW_NO_INSTALL_CLEANUP=1
export HOMEBREW_NO_ENV_HINTS=1
export HOMEBREW_NO_ENV_FILTERING=1
export ACCEPT_EULA=y
EOF
touch ~/.{zshenv,zprofile,zlogin,zshrc}
cat <<'EOF' | tee -a "$HOME"/.zshrc
export LANG=en_US.UTF-8
# Homebrew
export HOMEBREW_NO_ANALYTICS=1
export HOMEBREW_NO_GOOGLE_ANALYTICS=1
export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_INSTALL_CLEANUP=1
export HOMEBREW_NO_ENV_HINTS=1
export HOMEBREW_NO_ENV_FILTERING=1
export ACCEPT_EULA=y
eval "$(/opt/homebrew/bin/brew shellenv)"
# ruby rbenv
if which rbenv > /dev/null; then
eval "$(rbenv init -)";
fi
EOF
source "${HOME}"/.zshrc
cat <<'EOF' | tee "$HOME/.curlrc"
# https://everything.curl.dev/cmdline/configfile
# http://curl.haxx.se/docs/manpage.html
#user-agent = "Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0"
referer = ";auto"
connect-timeout = 10
max-time = 90
progress-bar
verbose
show-error
remote-time
ipv4
#silent
# Print timings after each call. Use curl -q to suppress this file
#write-out = "%{http_code} ns:%{time_namelookup} conn:%{time_connect} appconn:%{time_appconnect} prexfr:%{time_pretransfer} rdr:%{time_redirect} ttfb:%{time_starttransfer} TOTAL:%{time_total}\n"
#-w "%{stderr}\n፧%{response_code} ⧖ %{time_total}s ⇵ %{speed_download}/%{speed_upload}bps ▼ %{size_download}(%{size_header})b▲ %{size_upload}(%{size_request})b%{stdout}\n\n"
EOF
cat <<EOF | tee "$HOME/.screenrc"
startup_message off
EOF
}
setupUserEnvironment
#cat <<'EOF' | tee -a ~/.zprofile
#
#export LANG=en_US.UTF-8
#
# Homebrew
#eval "$(/opt/homebrew/bin/brew shellenv)"
#export HOMEBREW_NO_AUTO_UPDATE=1
#export HOMEBREW_NO_INSTALL_CLEANUP=1
#export HOMEBREW_NO_ENV_HINTS=1
#export HOMEBREW_NO_ENV_FILTERING=1
#export ACCEPT_EULA=y
#
# ruby
#if which rbenv > /dev/null; then
# eval "$(rbenv init -)";
#fi
#
#EOF
#source ~/.zprofile
function installHomebrew() {
export HOMEBREW_NO_ANALYTICS=1
export HOMEBREW_NO_GOOGLE_ANALYTICS=1
# Install homebrew
#/usr/bin/ruby -e "$(curl -sSfL https://raw.githubusercontent.com/Homebrew/install/master/install)"
#/bin/bash -c "$(curl -sSfL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>/dev/null
# Disable homebrew analytics
"$(brew --prefix)"/bin/brew analytics off
# Installing from the API is now the default behaviour,
# so you can save space and time by running the following.
"$(brew --prefix)"/bin/brew untap homebrew/core
"$(brew --prefix)"/bin/brew untap homebrew/cask
"$(brew --prefix)"/bin/brew update
"$(brew --prefix)"/bin/brew upgrade
"$(brew --prefix)"/bin/brew upgrade --cask
"$(brew --prefix)"/bin/brew cleanup
#eval "$(/opt/homebrew/bin/brew shellenv)"
}
installHomebrew
function reinstallOpenssl() {
# Reinstall the following to resolve CA bundle symlink issues
"$(brew --prefix)"/bin/brew reinstall openssl ca-certificates
# Install curl + link
#"$(brew --prefix)"/bin/brew install curl --with-openssl
#"$(brew --prefix)"/bin/brew link --force curl
}
reinstallOpenssl
function addHomebrewTaps() {
local homebrew_taps
homebrew_taps=("Homebrew/bundle" "aws/tap" "sebsto/macos" "xfreebird/utils")
for tap in "${homebrew_taps[@]}"; do
"$(brew --prefix)"/bin/brew tap "${tap}"
done
}
addHomebrewTaps
function installAwsTools() {
# AWSCLIv2 Bundled Installer
#url="https://awscli.amazonaws.com/AWSCLIV2.pkg"
#sudo installer -pkg "$awscliv2_pkg_path" -target /
# Upgrade ENA Driver, activation requires using GUI
"$(brew --prefix)"/bin/brew install --cask aws/aws/amazon-ena-ethernet-dext
# EC2 Instance Connect
"$(brew --prefix)"/bin/brew install --cask aws/aws/ec2-instance-connect
# Amazon SSM Agent
"$(brew --prefix)"/bin/brew install aws/aws/amazon-ssm-agent
# EFS Utils
"$(brew --prefix)"/bin/brew install aws/aws/amazon-efs-utils
# Session Manager Plugin
"$(brew --prefix)"/bin/brew install --cask session-manager-plugin
# SAM CLI
"$(brew --prefix)"/bin/brew install aws-sam-cli
}
installAwsTools
# List launchtl managed services
function launchctl-ls() {
#sudo launchctl list
#launchctl list
launchctl print system
}
# Enable SSH service in macOS
function enableRemoteLogin() {
sudo systemsetup -setremotelogin on
sudo systemsetup -getremotelogin
# Add the usser to the remote login group
#sudo dseditgroup -o edit -a $USER -t user com.apple.access_ssh
}
#enableRemoteLoginService
# Enable VNC service in macOS
function enableScreenSharingService() {
# Access Screen Sharing service viah SSH tunnel i.e. local port forwarding.
# For example: ssh -N -L 5900:localhost:5900 ec2-user@host
# Enable macOS Screen Sharing service
echo "[+] Enable macOS Screen Sharing service.."
#sudo /usr/bin/defaults write /var/db/launchd.db/com.apple.launchd/overrides.plist com.apple.screensharing -dict Disabled -bool false
sudo /bin/launchctl enable system/com.apple.screensharing
# Prior macOS 12.1, it was possible to enable the Screen Sharing service via just the one command.
sudo /bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
#sudo /bin/launchctl bootstrap system /System/Library/LaunchDaemons/com.apple.screensharing.plist
# Allow Screen Sharing (Cmd-K in Finder) to connect to vnc://localhost/
/usr/bin/defaults write com.apple.ScreenSharing skipLocalAddressCheck -bool true
# To only allow VNC connections from localhost, MUST use an SSH tunnel and forward to local 5900.
#/usr/bin/defaults write /Library/Preferences/com.apple.RemoteManagement.plist VNCOnlyLocalConnections -bool yes
# Enable Fast User Switching for multiple user sessions at the same time like RDP
# https://www.kevinmcox.com/2022/04/adventures-in-fast-user-switching-on-macos-monterey/
sudo /usr/bin/defaults write /Library/Preferences/.GlobalPreferences MultipleSessionEnabled -bool true
/usr/bin/defaults write "Apple Global Domain" MultipleSessionsEnabled -bool true
# Configure how the Fast User switching menu is displayed as the user
/usr/bin/defaults write .GlobalPreferences userMenuExtraStyle -int 0
# Enable Fast User switching as the user using the following integer
/usr/bin/defaults -currentHost write com.apple.controlcenter UserSwitcher -int 2
}
#enableScreenSharingService
function disableScreenSharingService() {
# Restart and disable the Apple Remote Desktop (ARD) service on macOS
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -configure -activate -access -on -privs -all -allowaccessfor -allusers -restart -agent
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate -configure -access -off
# Stop and disable the macOS screen sharing services
sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
sudo /bin/launchctl disable system/com.apple.screensharing
}
function restartScreenSharingService() {
echo "[+] Restart macOS Screen Sharing service.."
sudo /bin/launchctl unload /System/Library/LaunchDaemons/com.apple.screensharing.plist \
&& sudo /bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
}
function reenableScreenSharingService() {
# Disable and stop service
sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
sudo /bin/launchctl disable system/com.apple.screensharing
# Enable and start service
sudo /bin/launchctl enable system/com.apple.screensharing
sudo /bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
}
function dump_tccdb_screensharing_entries() {
local tccdb_path
tccdb_path="/Library/Application Support/com.apple.TCC/TCC.db"
sqlite3 "${db_path}" \
"SELECT * FROM access WHERE client = 'com.apple.screensharing.agent';"
}
function enableAppleRemoteDesktop() {
# Deprecated: Alternative kickstart method that is no longer supported on newer macOS releases
# Activate and allow for all
#sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -restart -agent -privs -all
# Activate and allow for only specific users
#sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -allowAccessFor -specifiedUsers ec2-user
# Disable
#sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate
}
#enableAppleRemoteDesktop
function enableVncServer() {
# Install third party x11vnc and vnc viewer as it's required for enabling gui session.
brew install x11vnc vnc-viewer
# Make sure VNC viewer does not ask about the EULA.
test -d ~/.vnc/config.d || mkdir -p "${HOME}/.vnc/config.d"
echo 'EulaAccepted=e9afb455678129385e7b56353af525d360097b40' >"${HOME}/.vnc/config.d/vncviewer"
echo 'localhost::5900/extra=1e01' >"${HOME}/.vnc/identities"
}
#enableVncServer
function enableRemoteEvents() {
sudo systemsetup -setremoteappleevents on || true
}
enableRemoteEvents
# Create the users login keychain
function makeUserLoginKeychain() {
# Create the users login keychain directory
test -d ~/Library/Keychains || mkdir -p "${HOME}/Library/Keychains"
# Create the user login keychain for the user e.g. ec2-user
security create-keychain ~/Library/Keychains/login.keychain
# Unlock the new user login keychain
security unlock-keychain ~/Library/Keychains/login.keychain
# Use the specified preference domain and set the login keychain for the user
security login-keychain -d user -s ~/Library/Keychains/login.keychain
# Verify
ls -lA ~/Library/Keychains/
# User system
security default-keychain -d user
security list-keychains -d user
# System keychain
security default-keychain
security list-keychains
}
makeUserLoginKeychain
# Expected output:
#
# security default-keychain -d user
# "/Users/ec2-user/Library/Keychains/login.keychain-db"
# security list-keychains -d user
# "/Users/ec2-user/Library/Keychains/login.keychain-db"
# security default-keychain
# "/Users/ec2-user/Library/Keychains/login.keychain-db"
# security list-keychains
# "/Users/ec2-user/Library/Keychains/login.keychain-db"
# "/Library/Keychains/System.keychain"
# Download the Apple CA cert for signing and import it to the users login keychain
function importAppleCertificates() {
local certs certs_dir
certs=('AppleWWDRCAG3.cer' 'DeveloperIDG2CA.cer')
certs_dir="/private/tmp"
# https://github.com/actions/runner-images/blob/main/images/macos/assets/add-certificate.swift
#curl -sSfL 'https://raw.githubusercontent.com/actions/runner-images/main/images/macos/assets/add-certificate.swift' -o add-certificate.swift
#swiftc -suppress-warnings add-certificate.swift
test -d "${certs_dir}" || mkdir -p "${certs_dir}"
# Download the Apple certificates and add to the users login keychain
for cert in "${certs[@]}"; do
echo "Download and adding certificate: ${cert}"
certs_path="${certs_dir}/${cert}"
curl -sSfL "https://www.apple.com/certificateauthority/${cert}" -o "${certs_path}"
# Add to the users login keychain
test -f "${certs_path}" && security import "${certs_path}" ~/Library/Keychain/login.keychain-db
test -f "${certs_path}" && rm -f "${certs_path}"
done
}
importAppleCertificates
# Enable auto login and disable macOS screen lock and idle to screensaver
function enableAutoLogin() {
local macuuid
macuuid=$(ioreg -rd1 -c IOPlatformExpertDevice | grep -i "UUID" | cut -c27-62)
echo "${macuuid}"
# https://github.com/xfreebird/kcpassword
brew install kcpassword
test -f /etc/kcpassword || sudo touch /etc/kcpassword
#echo '00000000: 1ced 3f4a bcbc ba2c caca 4e82' | sudo xxd -r - /etc/kcpassword
/usr/bin/defaults write com.apple.loginwindow autoLoginUser -bool true
#/usr/bin/defaults read com.apple.loginwindow
sudo /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow autoLoginUser -string 'ec2-user'
# Show IP address, hostname, OS version, etc. when clicking the clock in the login window
sudo /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo HostName
# Disable screensaver
sudo /usr/bin/defaults write /Library/Preferences/com.apple.screensaver loginWindowIdleTime 0
/usr/bin/defaults -currentHost write com.apple.screensaver idleTime 0
/usr/bin/defaults write com.apple.screensaver askForPassword -bool false
/usr/bin/defaults write com.apple.screensaver askForPasswordDelay -int 0
/usr/bin/defaults write /Users/"${USER}"/Library/Preferences/com.apple.screensaver.plist CleanExit "YES"
# Disable lock
/usr/bin/defaults write com.apple.loginwindow DisableScreenLock -bool true
sysadminctl -screenLock off -password ec2-user
# Verify
sysadminctl -autologin status
#sudo /usr/bin/plutil -p "/var/db/dslocal/nodes/Default/users/ec2-user.plist"
#killall cfprefsd
}
enableAutoLogin
function getMobileAccounts() {
for username in $(dscl . -list /Users | grep -v '^_'); do
# There are different types of authentication authorities e.g. LocalCachedUser, Kerberos and AD.
# LocalCachedUser is a specific type of authentication authority used for Mobile Accounts on macOS.
userAuthAuthority=$(dscl . -read "/Users/${username}" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
if [ -n "${userAuthAuthority}" ]; then
echo "User is a Mobile Account: ${userAuthAuthority}"
fi
done
}
#getMobileAccounts
### Networking
function getImdsToken() {
local nic
nic=$(/usr/sbin/netstat -rn 2>&1 | /usr/bin/grep -m 1 'default' | /usr/bin/awk '{ print $4 }')
imdsToken=$(curl --interface "${nic}" -w '\n' -H "X-aws-ec2-metadata-token-ttl-seconds: 180" -X PUT "http://169.254.169.254/latest/api/token")
echo "${imdsToken}"
}
#getImdsToken
# Add more specific /32 route for IMDS that will persist.
function setImportantRoutes() {
# https://apple.stackexchange.com/questions/401512/exclamation-mark-in-the-expire-column/470645#470645
# https://raw.githubusercontent.com/apple-open-source/macos/master/network_cmds/netstat.tproj/route.c
local eni eni_gw
eni=$(/usr/sbin/netstat -rn 2>&1 | /usr/bin/grep -m 1 'default' | /usr/bin/awk '{ print $4 }')
eni_gw=$(ipconfig getoption "${eni}" router)
# IMDS
sudo route delete 169.254.169.254
/usr/sbin/networksetup -setadditionalroutes "Thunderbolt Ethernet Slot 0" 169.254.169.254 255.255.255.255 "${eni_gw}"
# VPC DNS
#sudo route delete 169.254.169.253
#/usr/sbin/networksetup -setadditionalroutes "Thunderbolt Ethernet Slot 0" 169.254.169.253 255.255.255.255 "${eni_gw}"
# Amazon Time Sync
#sudo route delete 169.254.169.123
#/usr/sbin/networksetup -setadditionalroutes "Thunderbolt Ethernet Slot 0" 169.254.169.123 255.255.255.255 "${eni_gw}"
# Verify
#arp -n -a
netstat -n -r -a -l
# 169.254.169.254 172.31.32.1 172.31.43.126 UGHS 0 0 9001 en5
}
setImportantRoutes
# Get network interface details
function getNicDetails() {
local nic nic_ip nic_sm nic_gw nic_dns
nic=$(/usr/sbin/netstat -rn 2>&1 | /usr/bin/grep -m 1 'default' | /usr/bin/awk '{ print $4 }')
nic_ip=$(ipconfig getifaddr "${nic}")
nic_sm=$(ipconfig getoption "${nic}" subnet_mask)
nic_gw=$(ipconfig getoption "${nic}" router)
nic_dns=$(ipconfig getoption "${nic}" domain_name_server)
#ipconfig getpacket "${nic}"
#ipconfig getsummary "${nic}"
}
getNicDetails
function getWifiDetails() {
local wifi_details
wifi_details=$(networksetup -listallhardwareports | awk '/Wi-Fi|AirPort|Wireless/{getline; print $2}')
echo "${wifi_details}"
}
# Set EC2 ENI as primary network service interface
function setNicOrder() {
# View current order
#/usr/sbin/networksetup -listnetworkserviceorder
# mac2-m2.metal and mac2-m2pro.metal
/usr/sbin/networksetup -listallnetworkservices | /usr/bin/grep -c "*Wi-Fi" || /usr/sbin/networksetup -ordernetworkservices "Thunderbolt Ethernet Slot 0" "Thunderbolt Bridge" "Ethernet"
# mac2.metal
/usr/sbin/networksetup -setnetworkserviceenabled "Wi-Fi" off || true
/usr/sbin/networksetup -listallnetworkservices | /usr/bin/grep -c "*Wi-Fi" && /usr/sbin/networksetup -ordernetworkservices "Thunderbolt Ethernet Slot 0" "Thunderbolt Bridge" "Ethernet" "Wi-Fi"
#/usr/sbin/networksetup -ordernetworkservices "Thunderbolt Ethernet Slot 0, Port 1" "Thunderbolt Ethernet Slot 0, Port 2" "Thunderbolt Ethernet Slot 0" "Thunderbolt Bridge" "Ethernet" "Wi-Fi"
# Verify
/usr/sbin/networksetup -listnetworkserviceorder
}
setNicOrder
# Set IPv6 to automatic for primary interface
function setNicIpv6() {
/usr/sbin/networksetup -setv6automatic "Thunderbolt Ethernet Slot 0"
}
setNicIpv6
# Set DNS servers to the VPC resolver for the primary interface
function setDnsResolvers() {
local dns_servers
dns_servers="${*:-169.254.169.253}"
# Set DNS server for interface
/usr/sbin/networksetup -setdnsservers "Thunderbolt Ethernet Slot 0" "${dns_servers}"
# Verify
#scutil --dns
}
setDnsResolvers 169.254.169.253
function setTimezone() {
local timezone
timezone="${1:-GMT}"
sudo /usr/sbin/systemsetup -settimezone "${timezone}"
}
setTimezone GMT
function enableNetworkTime() {
sudo /usr/sbin/systemsetup -getusingnetworktime | grep On || { sudo /usr/sbin/systemsetup -setusingnetworktime off 2>&1 && sudo /usr/sbin/systemsetup -setusingnetworktime on 2>&1; }
sudo /usr/sbin/sysadminctl -automaticTime on
}
# Set time sync details
function setTimeServersAndSync() {
# The AWS Time Sync service performing leap smearing, which means you should NEVER mix them with
# servers/pools that do not perform leap smearing or the exact same method of leap smearing.
local time_servers
time_servers="${1:-169.254.169.123}"
sudo /usr/sbin/systemsetup -setnetworktimeserver "${time_servers}"
#sudo /usr/sbin/systemsetup -setnetworktimeserver time.aws.com
# Sync the current date and time
sudo /usr/bin/sntp -sS "${time_servers}"
#ntpdate -u "${time_servers}"
}
setTimeServersAndSync 169.254.169.123
function disableCaptivePortal() {
# When macOS connects to new networks, it checks for Internet connectivity and may launch a Captive Portal assistant utility application.
# https://web.archive.org/web/20171008071031/http://blog.erratasec.com/2010/09/apples-secret-wispr-request.html
# https://web.archive.org/web/20130407200745/http://www.divertednetworks.net/apple-captiveportal.html
# https://web.archive.org/web/20170622064304/https://grpugh.wordpress.com/2014/10/29/an-undocumented-change-to-captive-network-assistant-settings-in-os-x-10-10-yosemite/
sudo /usr/bin/defaults write /Library/Preferences/SystemConfiguration/com.apple.captive.control.plist Active -bool false
}
disableCaptivePortal
# Bypass proxies for the following resources
function setProxyBypass() {
local bypass_for
bypass_for="::1,localhost,127.0.0.1,169.254.169.254,169.254.169.123,169.254.169.253,*.local,*.amazonaws.com"
/usr/sbin/networksetup -setproxybypassdomains "Thunderbolt Ethernet Slot 0" "${bypass_for}"
}
setProxyBypass
function enableApplicationFirewall() {
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingopt detail
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp on
#sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 1
# Verify
#/usr/bin/osascript -l JavaScript -e "$.NSUserDefaults.alloc.initWithSuiteName('com.apple.security.firewall').objectIsForcedForKey('EnableFirewall')"
}
#enableApplicationFirewall
# Disable the macOS built-in application firewall
function disableApplicationFirewall() {
# https://support.apple.com/guide/mac-help/block-connections-to-your-mac-with-a-firewall-mh34041/mac
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode off
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode off
#sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 0
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp on
#sudo pkill -HUP socketfilterfw
# Verify
/usr/bin/osascript -l JavaScript -e "$.NSUserDefaults.alloc.initWithSuiteName('com.apple.security.firewall').objectIsForcedForKey('EnableFirewall')"
}
disableApplicationFirewall
function addAppFirewallException() {
# Xcode
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /Applications/Xcode.app/Contents/MacOS/Xcode
# iOS Simulator
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator
# Samba File Sharing Service
#sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /usr/sbin/smbd
#sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp /usr/sbin/smbd
}
function getApplicationFirewallStatus() {
/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate --getblockall --getallowsigned --getstealthmode --listapps
}
function enableDeveloperMode() {
# https://www.manpagez.com/man/1/DevToolsSecurity/
# You need to add at least one tool to the list for the 'developer tools' section to become visible in the
# system preferences -> security & privacy -> Privacy list. Run the following to add Terminal.app as a developer
# tool, enable in the Privacy & Security Settings.
sudo /usr/sbin/spctl developer-mode enable-terminal
# Change the security authorization policies for developer systems e.g. enables access to developer tools for your user.
#
# When you run an Xcode project from a standard i.e. non-admin user, you might be asked to enter credentials of a user
# in the "Developer Tools group.".
#
# This will stop the prompt:
#
# "Developer tools access needs to take control of another process for debugging to continue. Type your password to allow this."
#
# https://stackoverflow.com/questions/9132826/stop-developer-tools-access-needs-to-take-control-of-another-process-for-debugg/74489896#74489896
#
# Enables "Developer mode"
sudo /usr/sbin/DevToolsSecurity --enable
sudo dscl . append /Groups/_developer GroupMembership "$(whoami)"
#sudo dscl . append /Groups/_developer GroupMembership $USER
#/usr/sbin/dseditgroup -o edit -t group -a staff _developer
#sudo /usr/libexec/PlistBuddy -c "Set :rights:system.privilege.taskport:class allow" authorization.plist
# If the user(s) are AD bound users
#/usr/sbin/dseditgroup -o edit -t group -a "AD/Domain Users" _developer
# Verify user is member of _developer group
dsmemberutil checkmembership -U "$(whoami)" -G "_developer"
#id
}
enableDeveloperMode
function enableAutomationMode() {
# https://keith.github.io/xcode-man-pages/automationmodetool.1.html
# https://developer.apple.com/forums/thread/693850
# https://developer.apple.com/forums/thread/733752
# https://github.com/appium/appium-mac2-driver
#max_retries=10
#while [ "${max_attempts}" -gt 0 ]; do
#sudo xcode-select -s '/Applications/Xcode_15.4.app'
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo /usr/sbin/DevToolsSecurity --enable
automationmodetool enable-automationmode-without-authentication
# Expected output:
# Enter the password for user 'ec2-user':
# Setting up machine to allow Automation Mode without requiring user authentication... succeeded.
}
function disableAutomationMode() {
automationmodetool disable-automationmode-without-authentication
}
function forceAutomationWithoutAuthentication() {
expect_script="$HOME/automationmodetool.expect"
cat <<EOF >>"${expect_script}"
spawn automationmodetool enable-automationmode-without-authentication
expect "Enter the password for user 'ec2-user':"
send "ec2-user\\n"
expect "Setting up machine to allow Automation Mode without requiring user authentication... succeeded."
EOF
expect -f "${expect_script}"
}
forceAutomationWithoutAuthentication
### Security
#man security
# Allows the user(s) who are members of the developer group to perform UI interactions e.g. run the iOS simulator.
#sudo /usr/bin/security authorizationdb remove system.privilege.taskport is-developer || true
#sudo /usr/bin/security authorizationdb write system.privilege.taskport is-developer
# https://apple.stackexchange.com/a/458553
cat <<'EOF' | tee ./taskport-default.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>allow-root</key>
<false/>
<key>authenticate-user</key>
<true/>
<key>class</key>
<string>user</string>
<key>comment</key>
<string>Used by task_for_pid(...).
Task_for_pid is called by programs requesting full control over another program
for things like debugging or performance analysis. This authorization only applies
if the requesting and target programs are run by the same user; it will never
authorize access to the program of another user. WARNING: administrators are advised not to modify this right.</string>
<key>created</key>
<real>557959080.243554</real>
<key>group</key>
<string>_developer</string>
<key>modified</key>
<real>557959080.243554</real>
<key>session-owner</key>
<false/>
<key>shared</key>
<true/>
<key>timeout</key>
<integer>36000</integer>
<key>tries</key>
<integer>10000</integer>
<key>version</key>
<integer>0</integer>
</dict>
</plist>
EOF
sudo security authorizationdb write system.privilege.taskport <taskport-default.plist
sudo /usr/bin/security authorizationdb read system.privilege.taskport
#/usr/bin/security authorizationdb read system.privilege.taskport
sudo /usr/bin/security authorizationdb write system.privilege.taskport allow || true
# https://www.dssw.co.uk/reference/authorization-rights/
# http://www.afp548.com/2013/10/22/modifying-the-os-x-mavericks-authorization-database/
# https://forums.developer.apple.com/forums/thread/86537
#echo "select name from rules;" | sudo sqlite3 /var/db/auth.db > right-names.txt
#for i in $(cat right-names.txt); do
# echo "--- right '$i' ---" >> right-specifications.txt;
# security authorizationdb read $i >> right-specifications.txt;
#done
#https://stackoverflow.com/a/9678612
#security unlock-keychain -p <password> "${HOME}/Library/Keychains/login.keychain"
# Enable osascript over SSH automatically without sshd-keygen warning and full disk access.
/usr/bin/defaults write com.apple.universalaccessAuthWarning /System/Applications/Utilities/Terminal.app -bool true
/usr/bin/defaults write com.apple.universalaccessAuthWarning /usr/libexec -bool true
/usr/bin/defaults write com.apple.universalaccessAuthWarning /usr/libexec/sshd-keygen-wrapper -bool true
/usr/bin/defaults write com.apple.universalaccessAuthWarning com.apple.Terminal -bool true
/usr/bin/defaults write com.apple.universalaccessAuthWarning com.apple.Messages -bool true
#/usr/bin/defaults read com.apple.universalaccessAuthWarning
### Apple VoiceOver Framework
# https://www.apple.com/voiceover/info/guide/_1124.html
#
# To allow VoiceOver to be controlled by AppleScript:
# 1. Create the file /private/var/db/Accessibility/.VoiceOverAppleScriptEnabled as it needs to exist and contain the character a.
# 2. Create VoiceOver database file specifying automation is enabled.
#sudo bash -c 'echo -n "a" > /private/var/db/Accessibility/.VoiceOverAppleScriptEnabled'
# In addition to the above database file you will also need to set a system preference entry, which updates
# the system preference defaults specifying that automation is enabled.
/usr/bin/defaults write com.apple.VoiceOver4/default SCREnableAppleScript -bool true
#/usr/bin/defaults read com.apple.VoiceOver4/default SCREnableAppleScript
/usr/bin/defaults write com.apple.VoiceOverTraining doNotShowSplashScreen -bool true
#/System/Library/CoreServices/VoiceOver.app/Contents/MacOS/VoiceOverStarter
/usr/bin/defaults write com.apple.HIToolbox AppleDictationAutoEnable -bool false
# Disable apple speech recognition
sudo /usr/bin/defaults write "com.apple.speech.recognition.AppleSpeechRecognition.prefs" StartSpeakableItems -bool false
### TCC.db aka PPPC
# Note: Apps that have requested and been granted Security > Privacy permissions can be read via the following db.
# System TCC DB
#sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db 'select * from access'
# User TCC DB
#sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db 'select * from access'
#sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db 'SELECT client FROM access WHERE auth_value AND service = "kTCCServiceSystemPolicyAllFiles"'
#sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db 'SELECT client FROM access WHERE auth_value AND service = "kTCCServiceSystemPolicyAllFiles"'
#sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db .dump
### Audit and OpenBSM
# Enable macOS's audit facility, auditd, receives notifications from the kernel
# when certain system calls, such as open, fork, and exit, are made.
#
# Note: The audit log notifications are captured and written to an seperate audit log.
#
# The -s specifies that the audit system should [re]synchronize its configuration
# from the audit control file. A new log file will be created. The attributable
# flags parameter from the audit_control(5) configuration file is set at login time
# and is not synchronized with this flag.
#
# https://github.com/usnistgov/macos_security
# https://www.stigviewer.com/stig/apple_macos_13_ventura/
# https://www.stigviewer.com/stig/apple_macos_13_ventura/2023-08-28/MAC-3_Public/
# https://derflounder.wordpress.com/2023/10/18/re-enabling-openbsm-auditing-on-macos-sonoma/
#
# /etc/security/audit_control
sudo cp /etc/security/audit_control.example /etc/security/audit_control
sudo /bin/launchctl enable system/com.apple.auditd
#sudo /bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.auditd.plist
sudo /bin/launchctl list | grep auditd
#/usr/sbin/audit -s
# Enable support for queued jobs via atrun
function enableAtRun() {
# https://ss64.com/mac/at.html
# https://unix.stackexchange.com/questions/478823/making-at-work-on-macos/478840#478840
# https://superuser.com/a/1614696
# https://alvinalexander.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs/
# In System Preferences > Security & Privacy > Full Disk Access add /usr/libexec/atrun to the list.
# In Big Sur and later you will find the actual binary under /usr/libexec/atrun.
# Load the LaunchDaemon
#sudo /bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist
sudo /bin/launchctl load -F /System/Library/LaunchDaemons/com.apple.atrun.plist
# Enter allowed usernames in /var/at/at.allow, one username per line
cat <<EOF | sudo tee /var/at/at.allow
ec2-user
EOF
#atq
#at -f script.sh now + 30 minutes
}
#enableAtRun
# Enable the Accessibility API for assistive devices
# https://apple.stackexchange.com/questions/60476/how-to-avoid-the-gui-password-prompt-when-using-osascript
# https://community.jamf.com/t5/jamf-pro/enable-accessibility-api/m-p/51922
sudo touch /private/var/db/.AccessibilityAPIEnabled
echo -n 'a' | sudo tee /private/var/db/.AccessibilityAPIEnabled >/dev/null 2>&1
sudo chmod 444 /private/var/db/.AccessibilityAPIEnabled
#sudo security authorizationdb write system.preferences.accessibility allow
# Disable guest user logins and access
function disableGuestAccount() {
sudo /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool false
sudo /usr/sbin/sysadminctl -guestAccount off
sudo /usr/sbin/sysadminctl -afpGuestAccess off
sudo /usr/sbin/sysadminctl -smbGuestAccess off
}
#disableGuestAccount
# Enable macOS Location services
sudo /usr/bin/defaults write /var/db/locationd/Library/Preferences/ByHost/com.apple.locationd LocationServicesEnabled -bool true
/bin/launchctl kickstart -k system/com.apple.locationd 2>&1
# Disable location services
#sudo /usr/bin/defaults write /var/db/locationd/Library/Preferences/ByHost/com.apple.locationd LocationServicesEnabled -bool false; /bin/launchctl kickstart -k system/com.apple.locationd 2>&1
# Verify
sudo -u "_locationd" defaults -currentHost read "/var/db/locationd/Library/Preferences/ByHost/com.apple.locationd"
# Disable Multicast traffic
sudo /usr/bin/defaults write /Library/Preferences/com.apple.RemoteManagement ARD_MulticastAllowed -bool false
sudo /usr/bin/defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool false
# Disable AirDrop and AirPlay
function disableAirDrop() {
sudo /usr/bin/defaults write /Library/Preferences/com.apple.NetworkBrowser DisableAirDrop -bool true
sudo /usr/bin/defaults write /Library/Preferences/com.apple.NetworkBrowser DisableAirPlay -bool true
#/usr/bin/defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool false;
}
# Prevent the auto bluetooth setup assistant window from accidentally popping up
function disableBluetoothSetupAssistant() {
sudo /usr/bin/defaults write /Library/Preferences/com.apple.airport.bt.plist bluetoothCoexMgmt Hybrid
sudo /usr/bin/defaults write /Library/Preferences/com.apple.Bluetooth BluetoothAutoSeekKeyboard '0'
sudo /usr/bin/defaults write /Library/Preferences/com.apple.Bluetooth BluetoothAutoSeekPointingDevice '0'
sudo /usr/bin/defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState '0' >/dev/null 2>&1
}
disableBluetoothSetupAssistant
# Disable Bluetooth and Wi-Fi from showing up in the System Preferences
# https://www.hexnode.com/mobile-device-management/help/script-to-manage-preference-panes-on-macos-ventura/
sudo /usr/bin/defaults write "/Library/Preferences/com.apple.systempreferences" DisabledSystemSettings -array "com.apple.BluetoothSettings" "com.apple.wifi-settings-extension"
# Tweak input
/usr/bin/defaults write NSGlobalDomain com.apple.swipescrolldirection -bool false
/usr/bin/defaults write -g NSWindowShouldDragOnGesture -bool true
/usr/bin/defaults write -g NSAutomaticQuoteSubstitutionEnabled -bool false
/usr/bin/defaults write -g NSAutomaticDashSubstitutionEnabled -bool false
sudo /usr/bin/defaults write /Library/Preferences/com.apple.keyboardtype "keyboardtype" -dict-add "3-7582-0" -int 40
# Disable automatic capitalization as it’s annoying when typing code
defaults write NSGlobalDomain NSAutomaticCapitalizationEnabled -bool false
# Disable smart dashes as they’re annoying when typing code
defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false
# Disable automatic period substitution as it’s annoying when typing code
defaults write NSGlobalDomain NSAutomaticPeriodSubstitutionEnabled -bool false
# Disable smart quotes as they’re annoying when typing code
defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false
# Disable auto-correct
defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false
# Disabling press-and-hold for keys in favor of a key repeat
/usr/bin/defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
# Only use UTF-8 in Terminal.app
/usr/bin/defaults write com.apple.terminal StringEncodings -array 4
# Enable Secure Keyboard Entry in Terminal.app
# https://security.stackexchange.com/a/47786/8918
defaults write com.apple.terminal SecureKeyboardEntry -bool true
# Disable the annoying line marks
defaults write com.apple.Terminal ShowLineMarks -int 0
### macOS Notifications
# Disable the macOS Notification Center
launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist 2>/dev/null
#killall NotificationCenter
### macOS Desktop Tweaks
# General Desktop Performance Tuning
function disableStageManager() {
local currentUser currentUserUID
currentUser=$(ls -l /dev/console | awk '/ / { print $3 }')
currentUserUID=$(id -u "${currentUser}")
sudo launchctl asuser "${currentUserUID}" sudo -iu "${currentUser}" /usr/bin/defaults write com.apple.WindowManager GloballyEnabled -bool false
sudo su -l "${currentUser}" -c '/usr/bin/defaults write com.apple.WindowManager AutoHide -bool false'
}
sudo /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow DesktopPicture ""
/usr/bin/defaults write com.apple.Accessibility DifferentiateWithoutColor -int 1
/usr/bin/defaults write com.apple.Accessibility ReduceMotionEnabled -int 1
/usr/bin/defaults write com.apple.universalaccess reduceMotion -int 1
/usr/bin/defaults write com.apple.universalaccess reduceTransparency -int 1
/usr/bin/defaults write com.apple.finder DisableAllAnimations -bool true
/usr/bin/defaults write -g AppleFontSmoothing -int 2
sudo /usr/bin/defaults write /Library/Preferences/com.apple.windowserver DisplayResolutionEnabled -bool true
# Remove all the items in the dock
#/usr/bin/defaults write com.apple.dock persistent-apps -array ''
#/usr/bin/defaults write com.apple.dock persistent-others -array ''
# Save screenshots to ~/Pictures/screenshots by default
test -d "${HOME}/Pictures/screenshots" || mkdir -p "${HOME}/Pictures/screenshots"
/usr/bin/defaults write com.apple.screencapture location -string "${HOME}/Pictures/screenshots"
/usr/bin/defaults write com.apple.screencapture type -string "png"
/usr/bin/defaults write com.apple.screencapture disable-shadow -bool true
# Prefer tabs when opening documents
/usr/bin/defaults write -globalDomain "AppleWindowTabbingMode" -string "always"
# Apply Finder Tweaks
function applyFinderTweaks() {
# Hide all the desktop icons i.e. files that are still in the desktop
# directory but they will not be shown on the desktop.
# http://osxdaily.com/2009/09/23/hide-all-desktop-icons-in-mac-os-x/
/usr/bin/defaults write com.apple.finder CreateDesktop -bool false
/usr/bin/defaults write com.apple.finder ShowHardDrivesOnDesktop -bool false
/usr/bin/defaults write com.apple.finder ShowMountedServersOnDesktop -bool false
/usr/bin/defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool false
/usr/bin/defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool false
# Show status bar in finder
/usr/bin/defaults write com.apple.finder ShowStatusBar -bool true
# Show path bar in finder
/usr/bin/defaults write com.apple.finder ShowPathbar -bool true
# Display full POSIX path as the finder window title
/usr/bin/defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
# Keep folders on top when sorting by name
/usr/bin/defaults write com.apple.finder _FXSortFoldersFirst -bool true
# Show all filename extensions in Finder
/usr/bin/defaults write NSGlobalDomain AppleShowAllExtensions -bool true
# Disable the warning when changing a file extension
/usr/bin/defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
# These directories are hidden by default
# Show the ~/Library folder
test -d "${HOME}/Library" && chflags nohidden ~/Library
#test -d "${HOME}/Library" && chflags hidden ~/Library
# Show the /Volumes folder
sudo chflags nohidden /Volumes
#sudo chflags hidden /Volumes
killall Finder
}
applyFinderTweaks
### Disk Utility
# Enable the debug menu in Disk Utility
function enableDiskUtilityDebugMenu() {
/usr/bin/defaults write com.apple.DiskUtility DUDebugMenuEnabled -bool true
/usr/bin/defaults write com.apple.DiskUtility advanced-image-options -bool true
}
enableDiskUtilityDebugMenu
# Force enabling TRIM
function forceEnableTrimSSD() {
# Note: This should be enabled by default.
sudo trimforce enable
#log show --start $(date +%F) | grep -i spaceman_trim_free_blocks
}
function forceDisableTrimSSD() {
# Note: This should be enabled by default.
sudo trimforce disable
}
function listDisksDefragmentation() {
diskutil list
diskutil apfs defragment volumeDevice enable
}
# Disable macOS Lockdown mode
function disableLockdownMode() {
/usr/bin/defaults write .GlobalPreferences.plist LDMGlobalEnabled -bool false
}
### macOS Pop-ups
# Prevent applications from re-opening after reboot
# Needed for physical mac hosts that are utilized for CI purposes.
function disableAppsReopenOnReboot() {
sudo chown root ~/Library/Preferences/ByHost/com.apple.loginwindow*
sudo chmod 000 ~/Library/Preferences/ByHost/com.apple.loginwindow*
echo "Unload notificationcenterui.plist"
launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist
}
function remove32BitWarning() {
echo "Remove 32-bit Warnings."
rm -f ~/Library/Preferences/com.apple.coreservices.uiagent.plist
}
# Prevent finder windows from popping up for certain events
function disableFinderPopups() {
/usr/bin/defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool false
/usr/bin/defaults write com.apple.finder WarnOnEmptyTrash -bool false
}
# Prevent the Photos app from popping up when devices "plugged in"
function disablePhotosHotplug() {
/usr/bin/defaults -currentHost write com.apple.ImageCapture disableHotPlug -bool true
}
# Disable the Apple feedback assistant
function disableFeedbackAssistant() {
/usr/bin/defaults write com.apple.appleseed.FeedbackAssistant Autogather -bool false
}
# Disable the "Application X has crashed" dialog
function disableCrashReporter() {
/usr/bin/defaults write com.apple.CrashReporter DialogType none
launchctl unload -w /System/Library/LaunchAgents/com.apple.ReportCrash.plist
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.ReportCrash.Root.plist
}
# Disable the "Are you sure you want to open this application?" dialog
function disableQuarantinePopup() {
/usr/bin/defaults write com.apple.LaunchServices LSQuarantine -bool false
}
# Disable disk image verification e.g. Verifying ...
function disableDiskImageVerifyPopup() {
/usr/bin/defaults write com.apple.frameworks.diskimages skip-verify -bool true
/usr/bin/defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true
/usr/bin/defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true
}
# Disable opening of a new finder window when a volume is mounted
function disableFinderWindowOnVolumePopup() {
/usr/bin/defaults write com.apple.frameworks.diskimages auto-open-ro-root -bool false
/usr/bin/defaults write com.apple.frameworks.diskimages auto-open-rw-root -bool false
/usr/bin/defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool false
}
# Disable writing of .DS_Store files to network and usb attached storage devices
function disableDsStoreFiles() {
/usr/bin/defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
/usr/bin/defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true
}
# Disable Time Machine backups
function disableTimeMachineBackups() {
# Prevent Time Machine from prompting to use new hard drives as backup volume
/usr/bin/defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true
# Disable Time Machine Backup Service
sudo /usr/bin/tmutil disable
# Add exclusions for Time Machine backups
sudo /usr/bin/tmutil addexclusion -p /Users/ec2-user
#sudo /usr/bin/tmutil addexclusion -p /Users/ec2macadmin
sudo /usr/bin/tmutil addexclusion -p /Users/Shared
sudo /usr/bin/tmutil addexclusion -p /Users/template
# Exclue private directories related to Rosetta byte code cache
sudo /usr/bin/tmutil addexclusion -p /private/var/db/oah
sudo /usr/bin/tmutil addexclusion -p /private/var/db/diagnostics
# Exclude all system folders
sudo /usr/bin/tmutil addexclusion -p /Applications
sudo /usr/bin/tmutil addexclusion -p /Library
sudo /usr/bin/tmutil addexclusion -p /System
# Exclude hidden rootfs folders
sudo /usr/bin/tmutil addexclusion -p /bin
sudo /usr/bin/tmutil addexclusion -p /cores
sudo /usr/bin/tmutil addexclusion -p /etc
sudo /usr/bin/tmutil addexclusion -p /Network
sudo /usr/bin/tmutil addexclusion -p /sbin
sudo /usr/bin/tmutil addexclusion -p /tmp
sudo /usr/bin/tmutil addexclusion -p /user
sudo /usr/bin/tmutil addexclusion -p /var
sudo /usr/bin/tmutil addexclusion -p /Volumes
sudo /usr/bin/tmutil addexclusion -p /vm
}
disableTimeMachineBackups
# Useful for improving Time Machine backup prep. times, Mac App Store install speeds, etc.
#sudo /usr/sbin/sysctl debug.lowpri_throttle_enabled=0
#/usr/sbin/sysctl debug.lowpri_throttle_enabled
# To restore defaults
#sudo /usr/sbin/sysctl debug.lowpri_throttle_enabled=1
### Disable Printing
/usr/bin/defaults write -g PMPrintingExpandedStateForPrint -bool true
# Automatically quit printer app once the print jobs complete
/usr/bin/defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true
# Disable cupsd
sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/org.cups.cupsd.plist
#sudo /bin/launchctl remove /System/Library/LaunchDaemons/org.cups.cupsd.plist
# Disable Printers & Scanners from showing up in the System Preferences
sudo defaults write "/Library/Preferences/com.apple.systempreferences" DisabledSystemSettings -array "com.apple.Print-Scan-Settings.extension"
### Spotlight ###
# Disable spotlight indexing i.e. make sure you have Spotlight fully off or privacy on for the build directory
# or indexing will slow it down). See the following 'System Preferences -> Spotlight -> Privacy'
#
# https://apple.stackexchange.com/questions/87090/how-to-programatically-add-folder-to-spotlight-do-not-index
# https://discussions.apple.com/thread/255226813?sortBy=best
# -i off - Sets the indexing status for the provided volumes to off.
# -a Apply command to all stores on all volumes.
# -d Disables Spotlight searches on the provided volume.
# -E This flag will cause each local store for the volumes indicated to be erased.
function disableSpotlight() {
#sudo killall mds || true
sudo /usr/bin/defaults write ~/.Spotlight-V100/VolumeConfiguration.plist Exclusions -array "/Volumes"
sudo /usr/bin/defaults write ~/.Spotlight-V100/VolumeConfiguration.plist Exclusions -array "/Network"
#sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist || true
#sudo rm -rf /.Spotlight-V100/*
# Disable spotlight and and stop indexing
sudo /usr/bin/mdutil -a -i off / || true
sudo /usr/bin/mdutil -a -i off || true
# Disable spotlight indexing /Volumes
sudo /usr/bin/mdutil -i off /Volumes
# Disable spotlight indexing of /System/Volumes/Data
#sudo /usr/bin/mdutil -i off -d / /System/Volumes/Data || true
sudo /usr/bin/mdutil -a -i off -d / /System/Volumes/Data || true
# Erase spotlight index
sudo /usr/bin/mdutil -E / || true
}
for i in $(seq 1 5); do
disableSpotlight
res=$?
if [[ $res -eq 0 ]]; then
echo "Spotlight disabled"
break
else
echo "Failed to disable spotlight, $i retry..."
sleep 2
fi
done
#exit $res
### macOS Updates
function disableSoftwareUpdates() {
# Disable automatic software updates
sudo /usr/sbin/softwareupdate --schedule off
sudo /usr/bin/defaults write com.apple.commerce AutoUpdate -bool false
sudo /usr/bin/defaults write com.apple.commerce AutoUpdateRestartRequired -bool false
# DO NOT automatically check and download updates
sudo /usr/bin/defaults write com.apple.SoftwareUpdate AutomaticCheckEnabled -bool false
sudo /usr/bin/defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 0
sudo /usr/bin/defaults write com.apple.SoftwareUpdate AutomaticDownload -int 0
#sudo /usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -bool false
# DO NOT automatically install macOS updates
sudo /usr/bin/defaults write com.apple.SoftwareUpdate AutomaticallyInstallMacOSUpdates -bool false
# DO NOT automatically install new application updates
sudo /usr/bin/defaults write com.apple.SoftwareUpdate AutomaticallyInstallAppUpdates -bool false
# DO NOT automatically install new config data
sudo /usr/bin/defaults write com.apple.SoftwareUpdate ConfigDataInstall -bool false
# DO NOT automatically install critical updates
sudo /usr/bin/defaults write com.apple.SoftwareUpdate CriticalUpdateInstall -int 0
#sudo /usr/bin/defaults write com.apple.SoftwareUpdate CriticalUpdateInstall -bool false
# DO NOT allow the install of pre-release updates
sudo /usr/bin/defaults write com.apple.SoftwareUpdate AllowPreReleaseInstallation -bool false
}
disableSoftwareUpdates
### Power Settings
# Automatically restart on power loss, freeze, etc.
sudo /usr/sbin/systemsetup -setrestartpowerfailure on
sudo /usr/sbin/systemsetup -setrestartfreeze on
sudo /usr/bin/pmset -a autorestart 1
#sudo /usr/sbin/systemsetup -setwaitforstartupafterpowerfailure 0
#sudo /usr/sbin/systemsetup -getwaitforstartupafterpowerfailure
# Disable napping, sleep mode, hibernation, etc.
sudo /usr/sbin/systemsetup -setdisplaysleep Off 2>/dev/null || true
sudo /usr/sbin/systemsetup -setsleep Never 2>/dev/null || true
sudo /usr/sbin/systemsetup -setcomputersleep Off 2>/dev/null || true
sudo /usr/sbin/systemsetup -setallowpowerbuttontosleepcomputer Off || true
/usr/bin/defaults write com.apple.loginwindow PowerButtonSleepsSystem -bool no
sudo /usr/bin/pmset -a displaysleep 0
sudo /usr/bin/pmset -a sleep 0
sudo /usr/bin/pmset -a disksleep 0
sudo /usr/bin/pmset -a disablesleep 1
sudo /usr/bin/pmset -a standby 0
sudo /usr/bin/pmset -a powernap 0
# Disable Hibernation
sudo /usr/bin/pmset -a hibernatemode 0
sudo rm -f /var/vm/sleepimage
sudo touch /private/var/vm/sleepimage
sudo chflags uchg /private/var/vm/sleepimage
# Disable sudden motion sensor (sms)
sudo /usr/bin/pmset -a sms 0
# Disable waking on random events
sudo /usr/bin/pmset -a ttyskeepawake 1
sudo /usr/bin/pmset -a womp 0
sudo /usr/bin/pmset -a ring 0
sudo /usr/bin/pmset -a proximitywake 0
# To view the current power settings
#/usr/bin/pmset -g;
#/usr/bin/pmset -g everything;
# To view assertions
#sudo /usr/bin/pmset assertions
#sudo /usr/bin/pmset assertionslog
#log show --style syslog --start "$(date +%Y-%m-%d) 00:00:00" | grep "Wake reason"
# Disable macOS App Nap feature
/usr/bin/defaults write NSGlobalDomain NSAppSleepDisabled -bool true 2>/dev/null
sudo -u ec2-user /usr/bin/defaults write NSGlobalDomain NSAppSleepDisabled -bool true 2>/dev/null
#sudo -u runner /usr/bin/defaults write NSGlobalDomain NSAppSleepDisabled -bool true 2>/dev/null
# Disable the Automatic Termination of Inactive Applications on macOS
/usr/bin/defaults write NSGlobalDomain NSDisableAutomaticTermination -bool true
# Disable saving of the App state and re-launch of saved app windows upon reboot and login
/usr/bin/defaults write com.apple.systempreferences NSQuitAlwaysKeepsWindows -bool false
/usr/bin/defaults write com.apple.loginwindow TALLogoutSavesState -bool false
/usr/bin/defaults write com.apple.loginwindow LoginwindowLaunchesRelaunchApps -bool false
### Apple ID and iCloud
# Disable prioritizing saving of files to iCloud drive
sudo -u ec2-user /usr/bin/defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
# Disable warnings when removing from iCloud drive
sudo -u ec2-user /usr/bin/defaults write com.apple.finder FXEnableRemoveFromICloudDriveWarning -boolean false
#ln -f -s ~/Library/Mobile\ Documents/com~apple~CloudDocs ~/icloud
#killall Finder;
# Disable Apple ID (https://appleid.apple.com/) in Systems Settings
sudo /usr/bin/defaults write "/Library/Preferences/com.apple.systempreferences" DisabledSystemSettings -array "com.apple.systempreferences.AppleIDSettings"
#/usr/bin/defaults read /Users/$loggedInUser/Library/Preferences/MobileMeAccounts.plist Accounts | grep AccountID | cut -d '"' -f 2
### macOS AppStore tweaks
/usr/bin/defaults write com.apple.appstore WebKitDeveloperExtras -bool true
### Safari tweaks
# https://apple.stackexchange.com/a/429820
# Kill open Safari
function killAllSafari() {
killall Safari
}
function launchSafariAndKill() {
# Launch Safari once to populate the defaults
/Applications/Safari.app/Contents/MacOS/Safari &
safari_pid="${!}"
disown
sleep 30
kill -9 "${safari_pid}"
}
function enableSafariWebDriver() {
sudo safaridriver --enable
}
enableSafariWebDriver
function applySafariTweaks() {
/usr/bin/defaults write com.apple.Safari HomePage -string "about:blank"
/usr/bin/defaults write com.apple.Safari WebKitDefaultTextEncodingName -string 'utf-8'
/usr/bin/defaults write com.apple.Safari WebKitPreferences.defaultTextEncodingName -string 'utf-8'
/usr/bin/defaults write com.apple.Safari ShowFullURLInSmartSearchField -bool true
/usr/bin/defaults write com.apple.Safari SuppressSearchSuggestions -bool false
/usr/bin/defaults write com.apple.Safari UniversalSearchEnabled -bool false
/usr/bin/defaults write com.apple.Safari.SandboxBroker ShowDevelopMenu -bool true
/usr/bin/defaults write com.apple.Safari IncludeDebugMenu -bool true
/usr/bin/defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true
# Disable safari opening "safe" files automatically after download
/usr/bin/defaults write com.apple.Safari AutoOpenSafeDownloads -bool false
# Disable prompt and notificatinons from websites asking to allow push notifications
/usr/bin/defaults write com.apple.Safari CanPromptForPushNotifications -bool false
# Disable AutoFill
/usr/bin/defaults write com.apple.Safari AutoFillPasswords -bool false
/usr/bin/defaults write com.apple.Safari AutoFillFromAddressBook -bool false
/usr/bin/defaults write com.apple.Safari AutoFillCreditCardData -bool false
/usr/bin/defaults write com.apple.Safari AutoFillMiscellaneousForms -bool false
# Disable auto-correction of spelling in Safari
/usr/bin/defaults write com.apple.Safari WebContinuousSpellCheckingEnabled -bool false
/usr/bin/defaults write com.apple.Safari WebAutomaticSpellingCorrectionEnabled -bool false
}
applySafariTweaks
### TextEdit
# Default to plain text and open and save files as UTF-8
/usr/bin/defaults write com.apple.TextEdit RichText -int 0
/usr/bin/defaults write com.apple.TextEdit PlainTextEncoding -int 4
/usr/bin/defaults write com.apple.TextEdit PlainTextEncodingForWrite -int 4
### Sysctl
# Kernel aiothreads
#/usr/sbin/sysctl kern.aiomax kern.aioprocmax kern.aiothreads
#/usr/sbin/sysctl -w kern.aiomax=900 kern.aioprocmax=256 kern.aiothreads=64
# Kernel max vnodes
# kern.maxvnodes: 263168 (263168 is 257 * 1024)
/usr/sbin/sysctl -a | grep -iE 'kern\..*vnodes'
sudo /usr/sbin/sysctl -w kern.maxvnodes=$((512 * 1024))
test -f /Library/LaunchDaemons/kern.maxvnodes.plist || cat <<'EOF' | sudo tee /Library/LaunchDaemons/kern.maxvnodes.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>kern.maxvnodes</string>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/sysctl</string>
<string>kern.maxvnodes=524288</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOF
#sudo /bin/launchctl bootout system /Library/LaunchDaemons/kern.maxvnodes.plist && sudo /bin/launchctl bootstrap system /Library/LaunchDaemons/kern.maxvnodes.plist
# Kernel Shared Memory
test -f /Library/LaunchDaemons/kern.sysv.sharedmemory.plist || cat <<'EOF' | sudo tee /Library/LaunchDaemons/kern.sysv.sharedmemory.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>kern.sysv.sharedmemory</string>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/sysctl</string>
<string>kern.sysv.shmmax=33554432</string>
<string>kern.sysv.shmmni=32</string>
<string>kern.sysv.shmseg=8</string>
<string>kern.sysv.shmall=8192</string>
<string>kern.sysv.shmmin=1</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOF
# Kernel Max Files
sudo /usr/sbin/sysctl -w kern.maxfiles=10485760
sudo /usr/sbin/sysctl -w kern.maxfilesperproc=1048576
test -f /Library/LaunchDaemons/kern.maxfiles.plist || cat <<'EOF' | sudo tee /Library/LaunchDaemons/kern.maxfiles.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>kern.maxfiles</string>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/sysctl</string>
<string>kern.maxfiles=10485760</string>
<string>kern.maxfilesperproc=1048576</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOF
sudo chown root:wheel /Library/LaunchDaemons/kern.maxfiles.plist
sudo chmod 0644 /Library/LaunchDaemons/kern.maxfiles.plist
#sudo /bin/launchctl bootout system /Library/LaunchDaemons/kern.maxfiles.plist && sudo /bin/launchctl bootstrap system /Library/LaunchDaemons/kern.maxfiles.plist
# Networking Port Range
sudo /usr/sbin/sysctl net.inet.ip.portrange.first=1024 net.inet.ip.portrange.last=65535
/usr/sbin/sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last
test -f /Library/LaunchDaemons/net.inet.ip.portrange.plist || cat <<'EOF' | sudo tee /Library/LaunchDaemons/net.inet.ip.portrange.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>net.inet.ip.portrange</string>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/sysctl</string>
<string>net.inet.ip.portrange.first=1024</string>
<string>net.inet.ip.portrange.last=65535</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOF
#sudo /bin/launchctl bootout system /Library/LaunchDaemons/net.inet.ip.portrange.plist && sudo /bin/launchctl bootstrap system /Library/LaunchDaemons/net.inet.ip.portrange.plist
# Blackhole audio
function installBlackholeAudio() {
# Install Blackhole audio
"$(brew --prefix)"/bin/brew install switchaudio-osx
"$(brew --prefix)"/bin/brew install sox
"$(brew --prefix)"/bin/brew install blackhole-2ch
SwitchAudioSource -s "BlackHole 2ch" -t input
SwitchAudioSource -s "BlackHole 2ch" -t output
}
installBlackholeAudio
function installCliClick() {
# Install cliclick
"$(brew --prefix)"/bin/brew install cliclick
}
installCliClick
$(brew --prefix)/bin/brew install screen tmux mosh
$(brew --prefix)/bin/brew install awscli jq
$(brew --prefix)/bin/brew install ripgrep
$(brew --prefix)/bin/brew install tree ncdu
$(brew --prefix)/bin/brew install mist-cli
# Configure Git
function installAndConfigureGit() {
"$(brew --prefix)"/bin/brew install git git-lfs git-secrets git-secret
"$(brew --prefix)"/bin/brew install fswatch watchman
# System
sudo git lfs install --system
# User
git lfs install
# User
git config --global init.defaultBranch main
git config --global color.ui auto
git config --global color.branch auto
git config --global color.diff auto
git config --global color.interactive auto
git config --global color.status auto
git config --global color.grep auto
git config --global branch.autosetuprebase always
git config --global fetch.prune true
# Disable advice
git config --global --add safe.directory "*"
git config --global advice.pushUpdateRejected false
git config --global advice.pushNonFFCurrent false
git config --global advice.pushNonFFMatching false
git config --global advice.pushAlreadyExists false
git config --global advice.pushFetchFirst false
git config --global advice.pushNeedsForce false
git config --global advice.statusHints false
git config --global advice.statusUoption false
git config --global advice.commitBeforeMerge false
git config --global advice.resolveConflict false
git config --global advice.implicitIdentity false
git config --global advice.detachedHead false
git config --global advice.amWorkDir false
git config --global advice.rmHints false
# https://github.blog/2022-06-29-improve-git-monorepo-performance-with-a-file-system-monitor/
# https://groups.google.com/a/chromium.org/g/chromium-dev/c/MbTkba8g_MU
git config --global core.untrackedCache true
git config --global core.fsmonitor true
# For a runner e.g. Gitlab, you don't want this set
# https://docs.gitlab.com/runner/install/osx.html#limitations-on-macos
git config --global credential.helper osxkeychain
#git config --system --unset credential.helper
#git config --global --add credential.helper ''
git config credential.helper
}
installAndConfigureGit
function installPython3() {
# Install Python 3
"$(brew --prefix)"/bin/brew install python3
}
# Install Ruby
function installRuby() {
# Install Ruby
"$(brew --prefix)"/bin/brew install ruby
# Install rbenv
# https://github.com/rbenv/ruby-build/discussions/2118
brew install libyaml
brew install rbenv
#rbenv install 2.7.8
#rbenv install -l | grep -v - | tail -2 | xargs -L1 rbenv install
#rbenv global $(rbenv install -l | grep -v - | tail -1)
#gem install bundler
}
# Install rust-lang
function installRustLang() {
# Install Rust
# https://rustup.rs/
"$(brew --prefix)"/bin/brew install rustup-init
rustup-init -y --no-modify-path --default-toolchain=stable --profile=minimal
source "${HOME}/.cargo/env"
#CARGO_HOME=$HOME/.cargo
}
function InstallXcodeinstall() {
# Install the full Xcode IDE and setup
"$(brew --prefix)"/bin/brew install xcodeinstall
}
function xcodeinstallAuthenticate() {
xcodeinstall authenticate
}
function installXcodeIde() {
local xcode_release
xcode_release="${1:-Xcode 15.4.xip}"
xcodeinstall download --name "${xcode_release}"
pushd /Applications || return
cp -a "${HOME}"/.xcodeinstall/download/"${xcode_release}" /Applications/"${xcode_release}"
sudo xip -x /Applications/"${xcode_release}"
popd || return
}
# https://xcodereleases.com/
installXcodeIde "Xcode 15.4.xip"
function setXcodeIde() {
# Set the specific Xcode to use
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
#sudo xcode-select -s '/Applications/Xcode_15.4.app'
# Verify
/usr/bin/xcrun --find xcodebuild
# Get the Xcodebuild Version
sudo /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -version
# Accept the xcodebuild -license OR sudo xcodebuild -license
sudo /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -license accept
# Verify
/usr/libexec/PlistBuddy -c 'Print' /Library/Preferences/com.apple.dt.Xcode.plist
/usr/libexec/PlistBuddy -c 'Print' /Applications/Xcode.app/Contents/Resources/LicenseInfo.plist
}
function xcodeFirstRun() {
xcodebuild -runFirstLaunch
#sudo xcodebuild -runFirstLaunch
}
# Apply Xcode Tweaks
function applyXcodeTweaks() {
defaults write com.apple.dt.Xcode ShowBuildOperationDuration YES
defaults write com.apple.dt.Xcode BuildSystemScheduleInherentlyParallelCommandsExclusively -bool YES
defaults write com.apple.iphonesimulator AllowFullscreenMode -bool YES
}
# Xcode download platforms
function xcodeDownloadPlatforms() {
local platforms
platforms=("iOS")
for platform in "${platforms[@]}"; do
xcodebuild -downloadPlatform "${platform}"
done
}
# Xcode download all platforms
function xcodeDownloadAllPlatforms() {
xcodebuild -runFirstLaunch
xcodebuild -downloadAllPlatforms
#xcodebuild -downloadAllPlatforms -allowUntrusted
}
### Xcode Simulators
# https://developer.apple.com/support/xcode/
# https://developer.apple.com/documentation/xcode_release_notes/
#
# Xcode 15 includes SDKs for iOS 17, iPadOS 17, tvOS 17, watchOS 10, and macOS Sonoma.
# The Xcode 15 release supports on-device debugging in iOS 12 and later, tvOS 12 and later,
# and watchOS 4 and later. Xcode 15 requires a Mac running macOS Ventura 13.5 or later.
# https://devimages-cdn.apple.com/downloads/xcode/simulators/index2.dvtdownloadableindex
#xcrun simctl runtime add "${HOME}/Downloads/watchOS 9 beta Simulator Runtime.dmg"
# Pre-iOS-16-era simulator runtimes are distributed using installer packages as disk images
# that copy all the runtime files directly to the fs. The latest runtimes contain all the files
# on the LZFSE-compressed disk image and the Xcodes simulator daemon will keeps these images
# mounted at a special volume path.
# https://macops.ca/xcode-14-new-platforms-packaging-format/
# https://macops.ca/xcode-deployment-the-dvtdownloadableindex-and-ios-simulators/
# https://en.wikipedia.org/wiki/LZFSE
# https://developer.apple.com/documentation/xcode/installing-additional-simulator-runtimes
#brew install timsutton/formulae/speedwagon
#speedwagon list
#speedwagon download 'iOS 17.5 Simulator Runtime'
# Downloading and installing simulators
ios_simulators=("17.5" "17.4" "17.3")
for sim in "${ios_simulators[@]}"; do
echo "Installing iOS ${sim} ..."
sudo xcversion simulators --install="iOS ${sim}"
echo "Successfuly installed iOS ${sim} ..."
done

macOS memory leak checker script for bluetoothd & configd

To check the memory:

top -o mem

Create the script:

cat <<'EOF' | sudo tee /usr/local/bin/memory-leak-checker.sh
#!/bin/zsh --no-rcs

# Check processes e.g. configd, bluetoothd, etc for high memory consumption e.g. >=512MB and kill them.
#
# To manually check yourself, you can use the following: top -o mem
#
# Usage:
#
#  $ sudo /usr/local/bin/memory-leak-checker.sh
#    configd memory usage is normal: 17MB
#    Killing bluetoothd (PID: 83) due to high memory usage: 917MB

SCRIPT_NAME="$(basename "${0}")"
SCRIPT_VERSION="2024.08.20-dev"

# Memory ceiling in MB
THRESHOLD='512';

PATH="/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

# Helper functions
function iso8601() {
  date +"%Y-%m-%dT%H:%M:%S%z"
}

function log() {
  local priority
  priority="${1}"
  shift
  echo -e "$(iso8601) ${priority} ${@}"
}

check_and_kill_process() {
    local process_name process_path pid mem_usage
    process_name="${1}"
    process_path="${2}"

    pid=$(pgrep -f "${process_path}")
    if [[ -z "${pid}" ]]; then
        log INFO "${process_name} process not found."
        return
    fi

    mem_usage=$(ps -o rss= -p "${pid}" | awk '{print int($1/1024)}')
    if [[ "${mem_usage}" -gt "${THRESHOLD}" ]]; then
        log WARN "${process_name} with PID: ${pid}) has high memory usage (>= ${THRESHOLD}): ${mem_usage}MB. Killing."
        kill "${pid}"
    else
        log INFO "${process_name} with PID: ${pid} does not have high memory usage (< ${THRESHOLD}): ${mem_usage}MB"
    fi
}

check_and_kill_process "configd" "/usr/libexec/configd"
check_and_kill_process "bluetoothd" "/usr/sbin/bluetoothd"

exit 0

EOF

sudo chmod a+x /usr/local/bin/memory-leak-checker.sh

Create the LaunchDaemon plist file:

cat <<'EOF' | sudo tee /Library/LaunchDaemons/com.amzn.memoryleakchecker.plist
<?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>
    <!-- Contains a unique string that identifies your daemon to launchd. -->
    <key>Label</key>
    <string>com.amzn.memoryleakchecker</string>
    <!-- Contains the arguments [to exec()] used to launch your daemon. -->
    <key>ProgramArguments</key>
    <array>
        <string>/bin/zsh</string>
        <string>/usr/local/bin/memory-leak-checker.sh</string>
    </array>
    <!-- Run every 15 minutes -->
    <key>StartCalendarInterval</key>
    <array>
        <dict>
            <key>Minute</key>
            <integer>0</integer>
        </dict>
        <dict>
            <key>Minute</key>
            <integer>15</integer>
        </dict>
        <dict>
            <key>Minute</key>
            <integer>30</integer>
        </dict>
        <dict>
            <key>Minute</key>
            <integer>45</integer>
        </dict>
    </array>
    <!-- Low priority -->
    <key>Nice</key>
    <integer>20</integer>
    <key>LowPriorityIO</key>
    <true/>
</dict>
</plist>
EOF

Verify, should return okay:

plutil -lint /Library/LaunchDaemons/com.amzn.memoryleakchecker.plist

Install and enable:

sudo /bin/chmod 644 /Library/LaunchDaemons/com.amzn.memoryleakchecker.plist
sudo /usr/sbin/chown root:wheel /Library/LaunchDaemons/com.amzn.memoryleakchecker.plist
sudo launchctl load -w /Library/LaunchDaemons/com.amzn.memoryleakchecker.plist

Verify:

launchctl list | grep -E 'amazon|amzn|aws'

To disable and remove:

sudo launchctl unload -w /Library/LaunchDaemons/com.amzn.memoryleakcheck.plist
sudo rm -f /Library/LaunchDaemons/com.amzn.memoryleakcheck.plist
sudo rm -f /usr/local/bin/memory-leak-check.sh
#!/bin/bash
# Install dnsmasq service
$(brew --prefix)/bin/brew update
$(brew --prefix)/bin/brew install dnsmasq
# Backup the default dnsmasq.conf
cp -a /opt/homebrew/etc/dnsmasq.conf /opt/homebrew/etc/dnsmasq.conf.bak
cat <<'EOF' | sudo tee /opt/homebrew/etc/dnsmasq.conf
# /opt/homebrew/etc/dnsmasq.conf
# https://thekelleys.org.uk/dnsmasq/docs/dnsmasq-man.html
# https://thekelleys.org.uk/gitweb/?p=dnsmasq.git
## Server Configuration
# Alternative would be just 127.0.0.1 with ::1
listen-address=::1,127.0.0.1
port=53
# dnsmasq binds to the wildcard address, even if it is listening
# on only some interfaces. It then discards requests that it
# shouldn't reply to. This has the advantage of working even
# when interfaces come and go and change address.
bind-interfaces
# Uncommenting this will cause the service to fail on macOS
#interface=lo
# The userid to which dnsmasq will change after startup
#user=dnsmasq
# The group which dnsmasq will run as
#group=dnsmasq
## Name resolution options
# Don't poll /etc/resolv.conf for changes
no-poll
# Don't read /etc/resolv.conf, get upstream servers only from cli or dnsmasq conf
no-resolv
# Never forward addresses in the non-routed address spaces
bogus-priv
# Never forward plain names
domain-needed
# Reject private addresses from upstream nameservers
stop-dns-rebind
# Exempt 127.0.0.0/8 and ::1 from rebinding checks
rebind-localhost-ok
# Query servers in order
strict-order
# Set the size of dnsmasq's cache, default is 150 names
cache-size=1000
# Negative replies from upstream servers normally contain
# time-to-live information in SOA records which dnsmasq uses
# for caching. If the replies from upstream servers omit this
# information, dnsmasq does not cache the reply. This option
# gives a default value for time-to-live (in seconds) which
# dnsmasq uses to cache negative replies even in the absence
# of an SOA record.
#neg-ttl=60
# Uncomment to enable validation of DNS replies and cache
# DNSSEC data
#dnssec
#dnssec-check-unsigned
#trust-anchor=.,19036,8,2,49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5
## Logging directives
#log-async
#log-dhcp
# Uncomment to log all queries
#log-queries
# Alternative would be /tmp/dnsmasq
log-facility=/var/log/dnsmasq.log
## Upstream servers
# AWS VPC Resolver
# https://docs.aws.amazon.com/vpc/latest/userguide/vpc-dns.html#AmazonDNS
server=169.254.169.253
# Cloudflare
#server=1.0.0.2
#server=1.1.1.2
# Additional hosts files to include
#addn-hosts=/opt/homebrew/etc/dnsmasq-blocklist
# Send queries for internal domain to internal resolver
#address=/int.example.com/10.10.10.10
# Examples of blocking TLDs or subdomains
#address=/.local/0.0.0.0
#address=/.facebook.com/0.0.0.0
# Disable iCloud Private Relay using DNS
# https://developer.apple.com/support/prepare-your-network-for-icloud-private-relay/
address=/mask.icloud.com/
address=/mask-h2.icloud.com/
# Disable Mozilla Firefox DoH using the Canary Domain
# https://support.mozilla.org/en-US/kb/canary-domain-use-application-dnsnet
address=/use-application-dns.net/
# Block enrollment with MDM
# https://support.apple.com/en-us/101555
#address=/iprofiles.apple.com/
#address=/mdmenrollment.apple.com/
#address=/deviceenrollment.apple.com/
#address=/gdmf.apple.com/
#address=/acmdm.apple.com/
#address=/albert.apple.com/
EOF
# Check the configuration syntax to make sure it's valid
dnsmasq --test
# Enable and start the service
sudo brew services start dnsmasq
# If you need to restart at all i.e. changes, etc.
#sudo brew services restart dnsmasq
# Verify
#brew services list
#ps aux | grep dnsmasq
#ifconfig
networksetup -listallhardwareports
# Set the DNS server for the active interface that was returned by the above commands
sudo networksetup -setdnsservers "Thunderbolt Ethernet Slot 0" 127.0.0.1
sudo killall -HUP mDNSResponder; sudo killall mDNSResponderHelper; sudo dscacheutil -flushcache
# Verify
scutil --dns | head
networksetup -getdnsservers "Thunderbolt Ethernet Slot 0"
dig +trace google.com
# These should return NXDOMAIN
dig mask.icloud.com
dig mask-h2.icloud.com
#!/bin/bash
# https://github.com/brave/brave-browser
# https://github.com/brave/brave-browser/blob/master/README.md
# https://github.com/brave/brave-browser/wiki/macOS-Development-Environment
# https://chromium.googlesource.com/chromium/src/+/lkgr/docs/mac_build_instructions.md#system-requirements
# https://source.chromium.org/chromium/chromium/src/+/main:build/config/mac/mac_sdk.gni;l=43
# https://github.com/chromium/chromium/blob/main/docs/mac_build_instructions.md
# https://github.com/brave/brave-browser/wiki/Troubleshooting
# https://community.brave.com/t/problem-building-brave-on-mac/529418
# https://github.com/brock/node-reinstall
# https://gist.github.com/brock/5b1b70590e1171c4ab54
# nodejs lts
$(brew --prefix)/bin/brew install node@20
#$(brew --prefix)/bin/brew link --force --overwrite node
$(brew --prefix)/bin/brew install wget
$(brew --prefix)/bin/brew install gcc
$(brew --prefix)/bin/brew install cmake
$(brew --prefix)/bin/brew install ninja
$(brew --prefix)/bin/brew install ccache
$(brew --prefix)/bin/brew install fswatch
$(brew --prefix)/bin/brew install gnu-time
$(brew --prefix)/bin/brew install git git-lfs gh
cat <<'EOF' | tee -a "${HOME}/.zshrc"
export PATH="/opt/homebrew/opt/node@20/bin:$PATH"
export LDFLAGS="-L/opt/homebrew/opt/node@20/lib"
export CPPFLAGS="-I/opt/homebrew/opt/node@20/include"
# https://github.com/chromium/chromium/blob/main/docs/mac_build_instructions.md
test -d ~/depot_tools && export PATH="$PATH:$HOME/depot_tools"
EOF
node --version
# npm settings
#npm config set ~/.local/share/node_modules
npm config set progress=false
npm config set registry https://registry.npmjs.org/
#cat ~/.npmrc
# yarn
npm install --global yarn
yarn --version
yarn set version stable
yarn config set enableTelemetry false
# Build brave
mkdir src
git clone https://github.com/brave/brave-core.git src/brave
cd src/brave
# Git tuning
# https://github.blog/2022-06-29-improve-git-monorepo-performance-with-a-file-system-monitor/
# https://groups.google.com/a/chromium.org/g/chromium-dev/c/MbTkba8g_MU
git config --global core.untrackedCache true
git config --global core.fsmonitor true
git update-index --test-untracked-cache
git config core.untrackedCache true
git config core.fsmonitor true
screen
~/src/brave/vendor/depot_tools/gn args --list ~/src/out/release_arm64
~/src/brave/vendor/depot_tools/gn args ~/src/out/release_arm64
time /usr/bin/caffeinate -i npm install
npm install -g [email protected]
#npm config set target_os macos
#npm config set target_arch arm64
time /usr/bin/caffeinate -i npm run init
# Building Brave
time /usr/bin/caffeinate -i npm run build release
#/usr/bin/caffeinate -i npm run build
#npm start [Release|Component|Static|Debug]
#~/src/brave/vendor/depot_tools/gn clean ~/src/out/release_arm64
#screen -d -r <pid>
#!/bin/zsh
### SMB tuning script for macOS
#------------------------------------------------------------------------------
# https://apple.stackexchange.com/questions/309016/smb-share-deadlocks-since-high-sierra
# https://knowledgebase.45drives.com/kb/macos-samba-optimization/
# https://forums.unraid.net/bug-reports/prereleases/search-of-smb-shares-not-working-macos-client-r1105/page/2/?tab=comments#comment-16571
# https://photographylife.com/afp-vs-nfs-vs-smb-performance
# https://infohub.delltechnologies.com/en-us/l/powerscale-onefs-macos-client-performance-and-user-experience-optimization/onefs-and-macos-5/
# https://www.snbforums.com/threads/mac-os-smb-max-nvme-throughput-on-10gbe-network.84665/
# https://support.7fivefive.com/kb/latest/mac-os-smb-client-configuration
# https://wiki.samba.org/index.php/Configure_Samba_to_Work_Better_with_Mac_OS_X
#------------------------------------------------------------------------------
#sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string "${COMPUTER_NAME}"
killall cfprefsd
test ! -f /Library/Preferences && mkdir -p /Library/Preferences
test ! -f ~/Library/Preferences/nsmb.conf && touch ~/Library/Preferences/nsmb.conf
test ! -f /etc/nsmb.conf && sudo touch /etc/nsmb.conf
# /etc/nsmb.conf
cat << '_HEREDOC_' | sudo tee -a /etc/nsmb.conf
# /etc/nsmb.conf
# parameter default value
#
# nbtimeout + + - 1s Timeout for resolving a NetBIOS name
# minauth + + - NTLMv2 Minimum authentication level allowed
# streams + + + yes Use NTFS Streams if server supported
# soft + + + no Force all mounts to be soft
# notify_off + + + no Turn off using notifications
# kloglevel + - - 0 Turn on SMB kernel logging
# protocol_vers_map + - - 7 Bitmap of SMB Versions that are enabled
# signing_required + - - no Turn on SMB client signing
# signing_req_vers + - - 6 Bitmap of SMB Versions that have signing required
# validate_neg_off + - - no Turn off using validate negotiate
# max_resp_timeout + + - 30s Max time to wait for any response from server
# submounts_off + + + no Turn off using submounts
# dir_cache_async_cnt + + - 10 Max async queries to fill dir cache
# dir_cache_max + + - 60s Max time to cache for a dir
# dir_cache_min + + - 30s Min time to cache for a dir
# max_dirs_cached + + - Varies Varies from 200-300 depending on RAM amount
# max_cached_per_dir + + - Varies Varies from 2000-10000 depending on RAM amount
# netBIOS_before_DNS + + + no Try NetBIOS resolution before DNS resolution
# mc_on + - - yes Turn on SMB multichannel (allow more than one channel per session)
# mc_prefer_wired + - - no Prefer wired NIC's over wireless in multichannel mode - Some Wi-Fi networks advertise faster speeds than the connected wired network.
# encrypt_cipher_map + - - 15 Bitmap of SMB 3.1.1 encryption algorithms that are enabled
# force_sess_encrypt + - - no Force session encryption for all mounts
# force_share_encrypt + - - no Force share encryption for all mounts
[default]
# Protocol version is specified using binary bitmap
# 7 => 0111 => SMB 1/2/3 should be enabled
# 6 => 0110 => Only SMB v2/3 should be enabled
# 4 => 0100 => Only SMB v3 should be enabled
# 3 => 0011 => Only SMB v1/2 should be enabled
# 2 => 0010 => Only SMB v2 should be enabled
# 1 => 0001 => Only SMB v1 should be enabled
# Force SMB v3 only
protocol_vers_map=4
# No SMB1, so disable NetBIOS
# See the following for more details:
# - https://support.apple.com/en-us/HT211927
port445=no_netbios
# Max time to wait for any response from server
#max_resp_timeout=600
# Use soft mounts by default
#soft=yes
# When you use an SMB 2 or SMB 3 connection, local caching is enabled by default.
# You might want to turn off local caching if content on the server changes frequently,
# or the Finder sometimes shows only a partial list of the contents of a share or folder
# for a few seconds. (On busy or large file shares when using OS X El Capitan or macOS Sierra,
# items might disappear from Finder while the local cache rebuilds.)
# See the following for more details: https://support.apple.com/en-us/101918
#dir_cache_max_cnt=0
# Disable directory caching
#dir_cache_off=yes
# Turn off packet signing due to macOS bugs
#
# See the following articles for more detais:
# - https://support.apple.com/en-us/HT205926
# - https://support.apple.com/en-us/HT212277
# - https://kb.promise.com/thread/disable-smb-signing-on-os-x-10-11-5-10-12-x/
signing_required=no
# Disable session signing
#
# See the following for more details: https://support.apple.com/en-us/HT204021
validate_neg_off=yes
# Turn off notifications
#
# Applying this setting can break workflows that require SMB notifications
# for folder listings to be current.
#
# Disabling change notifications can also lead to data corruption and other
# issues where multiple users are accessing the same files and directories.
#notify_off=yes
# Use NTFS streams if supported. It is not necessary to force macOS to use
# alternate data streams as it's been the default since macOS version 10.5.
streams=yes
# macOS 11.3 added SMB3 multichannel support and it is recommended to force macOS
# to prefer wired connections as some Wi-Fi networks may advertise faster speeds
# than the connected wired network.
#
# See the following for more details:
# - https://support.apple.com/en-us/102010
# - https://support.apple.com/en-us/HT212277
mc_on=on
mc_prefer_wired=yes
_HEREDOC_
# To speed up SMB file browsing, you can prevent macOS from reading .DS_Store files on SMB shares.
# This makes the Finder use only basic information to immediately display each folder's contents
# in alphanumeric order. See for more details: https://support.apple.com/en-us/HT208209.
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
### To enable smbd for making the macOS host into a SAMBA share server ###
sudo launchctl enable system/com.apple.smbd
sudo launchctl bootstrap system /System/Library/LaunchDaemons/com.apple.smbd.plist
#sudo launchctl stop com.apple.smbd && sudo launchctl start com.apple.smbd
# Restart the SMB service, without a stop/start
sudo launchctl kickstart -kp system/com.apple.smbd
# Stop the SMB Service
#sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.smbd.plist
# Start the SMB Service
#sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.smbd.plist
# Remove extended attributes for the shared directory
# $ xattr /path/to/shared/dir
# com.apple.FinderInfo
# com.apple.metadata:_kMDItemUserTags
# purgeable-drecs-fixed
#xattr /path/to/shared/dir
#xattr -d com.apple.metadata:_kMDItemUserTags /path/to/shared/dir
#xattr -d purgeable-drecs-fixed /path/to/shared/dir
#xattr -d com.apple.FinderInfo /path/to/shared/dir
# OR all directly
#
# xattr -c /path/to/shared/dir
# Check spotlight status for the network share, ideally it should be disabled
#mdutil -s /path/to/network/share/
# The macOS CLI utility smbutil can provide useful information about what features are
# available and enabled on SMB-mounted file shares. The following command displays information
# about mounted SMB shares and their supported features:
#smbutil statshares -a
# The smbutil command also has arguments for observing SMB3 multichannel operation.
# These commands can be used to verify that SMB multichannel is functional and that
# the appropriate NICs are involved in the multiple connections.
#smbutil multichannel
#smbutil multichannel -m /path/to/network/share
#!/bin/zsh
# NFS tuning script for macOS
sudo touch /etc/nfs.conf
cat <<'EOF' | sudo tee -a /etc/nfs.conf
nfs.server.bonjour = 0
nfs.server.bonjour.local_domain_only = 0
# Possible fix for mount issues
nfs.client.mount.options = vers=4.0
# -o mount option (a comma-separated string of options like e.g. option1,option2=val,option3
nfs.client.mount.options = mountport=2049
# A zero value treats the machine as a desktop for traditional NFS behavior, where hard mounts never time out.
nfs.client.is_mobile = 0
# The default is 12 seconds
nfs.client.initialdowndelay = 30
EOF
echo "done."
#!/bin/bash
PLIST="/Library/LaunchDaemons/com.amzn.detectnewhw.plist";
cat <<EOF | sudo tee "${PLIST}"
<?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>
<!-- Contains a unique string that identifies your daemon to launchd. -->
<key>Label</key>
<string>com.amzn.detectnewhw</string>
<!-- Contains the arguments [to exec()] used to launch your daemon. -->
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/networksetup</string>
<string>-detectnewhardware</string>
</array>
<!-- Run every boot -->
<key>RunAtLoad</key>
<true/>
<!-- low priority -->
<key>Nice</key>
<integer>20</integer>
<key>LowPriorityIO</key>
<true/>
</dict>
</plist>
EOF
/bin/chmod 644 "${PLIST}"
/usr/sbin/chown root:wheel "${PLIST}"

macOS Performance Benchmarking

System Information

General System Information

hostinfo
/usr/sbin/system_profiler SPHardwareDataType

Gather System Diagnose (sysdiagnose)

Gather system diagnostic in a gzipped tarball:

sudo /usr/bin/sysdiagnose -b -u -A sysdiagnose-$(hostname).tar.gz -f ~/

System CPU Details

sysctl -n machdep.cpu.brand_string

sysctl machdep.cpu
sysctl hw.ncpu

sysctl hw.physicalcpu hw.logicalcpu
sysctl -a | grep brand
powermetrics -s cpu_power,gpu_power

macmon

brew install vladkens/tap/macmon

TUI:

macmon

raw metrics:

macmon raw

mactop

brew install mactop
sudo mactop
sudo mactop --interval 1000 --color green

pumas

brew install graelo/tap/pumas
sudo pumas run

NeoAsitop

Note: A full installation of Xcode.app is required to install and build this software. Installing just the Command Line Tools is not sufficient.

brew tap op06072/neoasitop
brew install neoasitop

Asitop

brew install python3
python3 -m venv ~/.venvs/asitop --prompt asitop
source ~/.venvs/asitop/bin/activate
python3 -m pip install --upgrade pip asitop
sudo asitop

socpowerbud

https://github.com/dehydratedpotato/socpowerbud/releases

socpwrbud -a

mx-power-gadget

brew install mx-power-gadget

intel-power-gadget

brew install intel-power-gadget

System Memory Details

sysctl hw.memsize
system_profiler SPMemoryDataType

System Power Metrics

sudo powermetrics -s cpu_power,gpu_power

Benchmarking

brew update
brew install sysbench
brew install fio

CPU Performance Benchmarking

This command tests the CPU performance by calculating prime numbers up to 20,000:

sysbench --test=cpu --cpu-max-prime=20000 run

Memory Performance Benchmarking

Use sysbench for memory testing:

sysbench --test=memory run

Storage Performance Benchmarking

IO Size (Input/Ouput size) * IOPS (Input/Output operations per second) = Throughput

MB/s and MBps (Megabytes per second) = 1,000,000 bytes per second

# There are 1000000 bits per second in 1 megabits per second
Mb/s and Mbps (Megabits per second) =

8 Bits in a Byte
KiB (Kibibytes) = 1,024 bytes
MiB (Mebibytes): 1,024 x 1,024 bytes = 1,048,576 bytes
GiB (Gibibytes): 1,024 x 1,024 x 1,024 bytes = 1,073,741,824 bytes
[Instance size]   [Baseline / Max bandwidth (Mbps)]  [Baseline / Max throughput (MB/s, 128 KiB I/O)]  [Baseline / Max IOPS (16 KiB I/O)]
mac1.metal - 14000 (Mbps) - 1750.0 (MB/s, 128 KiB I/O) 	80000 Maximum IOPS (16 KiB I/O)
mac2.metal - 10000  (Mbps) - 1250.0 (MB/s, 128 KiB I/O) 	55000 Maximum IOPS (16 KiB I/O)
mac2-m2.metal - 8000 (Mbps) - 1000.0 (MB/s, 128 KiB I/O)  55000 Maximum IOPS (16 KiB I/O)
mac2-m2pro.metal - 8000 (Mbps) - 1000.0 (MB/s, 128 KiB I/O) 55000 Maximum IOPS (16 KiB I/O)
mac2-m1ultra.metal -
mac2-m2pro.metal => Maximum throughput (MB/s, 128 KiB I/O) => 1000.0 MB/s

fio

For storage performance benchmarking, we can use fio:

For larger blockszie i.e. 256k, should see lower overall IOPS i.e. half what you'd get with bs=128k, so if ~8000 IOPS then expect 8000/2=~4000 IOPS.

fio --filename=./fiorandrw256k.file --direct=1 --rw=randwrite --randrepeat=0 --ioengine=posixaio --bs=256k --iodepth=8 --time_based=1 --numjobs=1 --runtime=120 --name=fio_randrw_256k --size=50G --invalidate=1 --randrepeat=0 --do_verify=0 --verify_fatal=0 --eta-newline=1 --time_based --group_reporting --clocksource=clock_gettime

With a blocksize i.e. bs=128k, we should expect to see both the write throughput and IOPS hit their limits together e.g. mac2-m2.metall=1000MBps.

fio --filename=./fiorandrw128k.file --direct=1 --rw=randwrite --randrepeat=0 --ioengine=posixaio --bs=128k --iodepth=8 --time_based=1 --numjobs=1 --runtime=120 --name=fio_randrw_128k --size=50G --invalidate=1 --randrepeat=0 --do_verify=0 --verify_fatal=0 --eta-newline=1 --time_based --group_reporting --clocksource=clock_gettime

With a smaller blocksize, we should expect to see lower write throughput but higher overall iops e.g. limit is 8000, then you should see ~8000 IOPS.

fio --filename=./fiorandrw16k.file --direct=1 --rw=randwrite --randrepeat=0 --ioengine=posixaio --bs=16k --iodepth=8 --time_based=1 --numjobs=1 --runtime=120 --name=fio_randrw_16k --size=50G --invalidate=1 --randrepeat=0 --do_verify=0 --verify_fatal=0 --eta-newline=1 --time_based --group_reporting --clocksource=clock_gettime

Miscellaneous tests:

fio --name=randwrite --ioengine=sync --rw=randwrite --bs=4k --numjobs=1 --size=1G --runtime=60 --group_reporting

dd

time dd if=/dev/zero of=testfile bs=1m count=1024
time dd if=testfile of=/dev/null bs=1m
rm testfile

Stibium

curl -sL 'https://eclecticlightdotcom.files.wordpress.com/2023/06/stibium11.zip' -O

AmorphousDiskMark

Blackmagic Disk Speed Test

Network Performance

networkQuality

networkQuality
networkQuality -h
networkQuality -s
networkQuality -s -t 60
networkQuality -s -t 60 -i 1
networkQuality -s -t 60 -i 1 -f m

Speedtest Files

time curl http://speedtest.ftp.otenet.gr/files/test1Mb.db -o /dev/null |& tr '\r' '\n'
time curl https://speed.hetzner.de/1GB.bin -o /tmp/test.1g |& tr '\r' '\n'

speedtest-cli

brew install speedtest-cli
speedtest-cli
speedtest-cli --simple
speedtest-cli --list
speedtest-cli --server <server-id>

iperf3

brew update
brew install iperf3
iperf3 -s
iperf3 -c <host>
iperf3 -c <host> -R
iperf3 -c <host> -P 10
iperf3 -c <host> -P 10 -R
iperf3 -c <host> -P 10 -R -t 60
iperf3 -c <host> -P 10 -R -t 60 -i 1
iperf3 -c <host> -P 10 -R -t 60 -i 1 -f m
iperf3 -c <host> -P 10 -R -t 60 -i 1 -f m -w 1M
iperf3 -c <host> -P 10 -R -t 60 -i 1 -f m -w 1M -Z

get-network-info

General System Monitoring

Glances

Install via homebrew:

brew update
brew install glances

Usage:

glances

Netdata

brew update && brew install netdata
brew services start netdata
#/opt/homebrew/opt/netdata/sbin/netdata -D

OR

curl -sL 'https://get.netdata.cloud/kickstart.sh' -o /tmp/netdata-kickstart.sh \
  && sh /tmp/netdata-kickstart.sh --disable-telemetry --stable-channel --non-interactive --disable-cloud

sudo launchctl kickstart -k system/com.github.netdata

From your local workstation:

ssh -i <keypair> -L 19999:localhost:19999 ec2-user@<host>

Now visit the following in your web browser: http://localhost:19999

Bottom

Install via homebrew:

brew update
brew install bottom

Usage:

btm

htop

Install via homebrew:

brew update
brew install htop

Usage:

htop

CPU Monitoring

top -l 1 -n 0
top -l 1 -s 0

Process Management

procps

ps aux

ps -ef

# userid / processid / percent cpu / percent memory / work queue / command
# -e is similar to -A (all inclusive; your processes and others), and -o is to force a format
ps -e -o "uid pid pcpu pmem wq comm"

# if you are looking for a specific uid, you can chain it using awk or grep
ps -e -o "uid pid pcpu pmem wq comm" | grep 501
man ps

pstree

Process Tree utility

Install via homebrew:

brew install pstree
pstree
pstree -u <user>        # show only processes by your user
pstree -s <string>      # show only processes with string
pstree -help            # show help

Memory Usage and Management

top -o MEM

Swap usage:

sysctl vm.swapusage

vm_stat

vm_stat
paste <(vm_stat | awk 'NR>1' | grep -o ".*:") <(for i in $(vm_stat | awk 'NR>1' | tr -d '.' | awk '{print $NF}'); do perl -e "print $i/1024" | awk '{printf "%0.2f", $0}'; echo; done) | column -s: -t

EC2 Mac

ec2-macos-init

Cleanup instance specific stuff that is leftover from launch:

sudo /usr/local/bin/ec2-macos-init clean -all

Apple Resources

macOS VMs

Troubleshooting macOS MV Issues

Temporary Files

The temporary directory cleanup is actually run by infrastructure inherited from BSD. You can read about it in the man page and by reading the following files.

It looks like daily_clean_tmps_days defaults to 3, meaning that a file gets deleted if it hasn’t been accessed in three days. Keep in mind that the specific details aren’t considered API, and can vary from release to release and platform to platform. For example, iOS has a very different system for handling temporary files.

/tmp
/private/var/tmp
man periodic.conf
cat /etc/defaults/periodic.conf
cat /etc/periodic/daily/110.clean-tmps
cat /System/Library/LaunchDaemons/com.apple.bsd.dirhelper.plist
grep -A6 StartCalendarInterval /System/Library/LaunchDaemons/com.apple.bsd.dirhelper.plist

To disable the temporary file cleanup service on macOS:

sudo launchctl unload /System/Library/LaunchDaemons/com.apple.bsd.dirhelper.plist

Troubleshooting Slow Uploads to S3

To disable TSO, run the following command before any steps interacting with S3:

sudo sysctl net.inet.tcp.tso=0
#sudo sysctl -w net.inet.tcp.tso=0

After disabling TSO, users will see better transfer speeds.

sudo launchctl unload /System/Library/LaunchDaemons/com.apple.bsd.dirhelper.plist

Xcode

Xcode Releases

Xcode CLI Tools

#mkdir -p /Applications/Xcode.app

The process will no longer be checked for the quarantine attribute i.e. xattr:

sudo spctl developer-mode enable-terminal

On macOS make sure you also install the command line developer tools:

xcode-select --install
xcode-select --install

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

brew update

OR

macos_ver=$(sw_vers -productVersion | cut -d'.' -f 1-2);

touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress;

package=$(softwareupdate -l |
  grep "\*.*Command Line *.* version ${macos_ver}" |
  head -n 1 | awk -F"*" '{print $2}' |
  sed -e 's/^ *//' |
  tr -d '\n')

softwareupdate -i "${package}" --verbose

rm /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress

If you didn't enable Developer Mode using Xcode you will be asked to authorize the debugger every time you use it. To enable Developer Mode and only have to authorize once per session use:

sudo /usr/sbin/DevToolsSecurity -enable

You might also need to add your user to the developer group:

sudo dscl . append /Groups/_developer GroupMembership $(whoami)
sudo xcode-select -s "/Applications/$(ls /Applications | grep -m 1 Xcode)"

Full Xcode IDE

/Applications/Xcode.app/Contents/MacOS/Xcode
~/Library/Developer/Xcode/Archives
~/Library/Developer/Xcode/Archives
~/Library/Developer/Xcode/iOS DeviceSupport
~/Library/Developer/CoreSimulator/
~/Library/Developer/CoreSimulator/Devices/
~/Library/Developer/CoreSimulator/Caches/dyld/
~/Library/Logs/CoreSimulator/CoreSimulator.log

iOS Simulators

A Simulator runtime is an embedded OS package that Simulator loads when running your app on a simulated device in Xcode. For example, when you test your app on a simulated iPhone running iOS 17, Simulator loads the iOS 17 Simulator runtime on the simulated device. To minimize download size, Xcode splits the Simulator runtimes for each platform into individual installs. This allows you to install only the Simulator runtimes specific to the platform you’re developing for. Xcode requires the current versions of Simulator runtimes to build projects and to run Simulator for those platforms. To create a simulator for iPhone with a paired Apple Watch, Xcode needs the Simulator runtime for both platforms. If you download Xcode from the Apple Developer website or the Mac App Store, you can download and install these files when you first launch Xcode, or install them later from the Xcode run destination, from Xcode Settings, or from the command line. Manage the amount of storage that Xcode requires by choosing Xcode > Settings > Platforms to view the currently installed Simulator runtimes, and remove any that you don’t need. You can reinstall or install additional Simulator runtimes at any time.

xcode-select -s /Applications/Xcode-beta.app
xcodebuild -runFirstLaunch
xcrun simctl runtime add "~/Downloads/watchOS 9 beta Simulator Runtime.dmg"

To download and install all the platforms that the Xcode version you selected supports, use the -downloadAllPlatforms option on xcodebuild.

xcodebuild -downloadAllPlatforms

To download and install Simulator runtimes for a specific platform, use the -downloadPlatform option and specify the platform.

xcodebuild -downloadPlatform iOS

xcrun

xcrun simctl delete unavailable
xcrun simctl erase all
xcrun simctl --set previews delete all
xcrun simctl runtime add ~/Downloads/iOS_17.2_Simulator_Runtime.dmg

xcodebuild

xcodebuild is a set of commands through which you can build an Xcode project. These build tools come built-in with the Xcode IDE and help us build from a terminal. However, they're particularly useful within CI/CD pipelines, where they are typically used in wrapper scripts.

sudo xcodebuild -license accept
sudo xcodebuild -runFirstLaunch
sudo xcodebuild -downloadAllPlatforms

xcodes

# https://github.com/RobotsAndPencils/xcodes
xcodes install --latest --experimental-unxip

xcclear

Run xcclear -d to diagnose your storage:

xcclear -d

Xcode Tuning

Troubleshooting Xcode Issues

xcrun simctl shutdown all

The string is just the simulator device's ID. To get that just follow this good guide: https://www.seanmcp.com/articles/find-an-ios-simulator-identifier/

xcrun simctl bootstatus D2AB0F53-7E2B-4533-979B-50E8392760F7 -b
xcrun simctl shutdown D2AB0F53-7E2B-4533-979B-50E8392760F7
xcrun simctl bootstatus D2AB0F53-7E2B-4533-979B-50E8392760F7 -b
arch -arm64 xcodebuild
/usr/libexec/PlistBuddy /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Library/Wallpaper/Collections/Collections.plist -c "add order array" -c "add order: string 23EC2CF1-0188-49FC-B214-EC1AB37FE5C4"
while true
do
    pkill AegirPoster
    pkill InfographPoster
    pkill CollectionsPoster
    pkill ExtragalacticPoster
    pkill KaleidoscopePoster
    pkill EmojiPosterExtension
    pkill AmbientPhotoFramePosterProvider
    pkill PhotosPosterProvider
    pkill AvatarPosterExtension
    pkill GradientPosterExtension
    pkill MonogramPosterExtension
    pkill apsd
    sleep 5
done

Open Source Building and Code Signing

Building

Code Signing

# From a Git checkout
cargo run --bin rcodesign -- --help
cargo install --bin rcodesign

# Remote install.
cargo install --git https://github.com/indygreg/PyOxidizer --branch main --bin rcodesign apple-codesign 

Swift

#!/bin/bash
# Helper functions
function yell() {
echo "${0}: ${*}" >&2;
}
function die() {
yell "${*}"; exit 111;
}
# Usage: try <command>
function try() {
"${@}" || die "⚠️ cannot ${*}";
}
# Usage: retry <command>
function retry() {
local attempt maxattempts delay
attempt=1
maxattempts=5
delay=15
while true; do
"${@}" && break || {
if [[ "${attempt}" -lt "${maxattempts}" ]]; then
((attempt++))
yell "Command failed. Attempt ${attempt}/${maxattempts}:"
sleep "${delay}";
else
die "The command has failed after ${attempt} attempts."
fi
}
done
}
# Block until all network services have completed configuring or
# they have timed out while they were in the process of configuring
function netwait() {
try ipconfig waitall
}
# Sync the current date and time before proceeding with IMDS and EC2 API calls
function forcetimesync() {
sudo /usr/bin/sntp -sS 169.254.169.123
#ntpdate -u 169.254.169.123
}
#!/usr/bin/env bash
export HOMEBREW_NO_ANALYTICS=1
export HOMEBREW_NO_GOOGLE_ANALYTICS=1
export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_INSECURE_REDIRECT=1
export HOMEBREW_CASK_OPTS="--appdir=~/Applications --require-sha"
if test ! $(which brew); then
echo "Installing homebrew for macOS.. "
# Install Apple Rosetta 2 on Apple Silicon based hosts
if [[ $(arch) == 'arm64' ]]; then
/usr/sbin/softwareupdate --install-rosetta --agree-to-license
fi
# Install Xcode CLI
xcode-select --install;
# Install homebrew
/usr/bin/ruby -e "$(curl -sSfL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
# Disable homebrew analytics
$(brew --prefix)/bin/brew analytics off
# Installing from the API is now the default behaviour.
# Run the following so you can save space and time by running the following.
$(brew --prefix)/bin/brew untap homebrew/core
$(brew --prefix)/bin/brew untap homebrew/cask
# Brew update
$(brew --prefix)/bin/brew update
# Brew upgrade
#$(brew --prefix)/bin/brew upgrade
#$(brew --prefix)/bin/brew upgrade --cask
# Brew cleanup
$(brew --prefix)/bin/brew cleanup
#eval "$(/opt/homebrew/bin/brew shellenv)"
# Brew bundle dump
#$(brew --prefix)/bin/brew bundle dump
#$(brew --prefix)/bin/brew bundle dump --force
# Brew bundle install
$(brew --prefix)/bin/brew bundle
#$(brew --prefix)/bin/brew bundle install --file /path/to/Brewfile
#$(brew --prefix)/bin/brew bundle install --file ~/Brewfile
# View brew install packages and their dependencies
#$(brew --prefix)/bin/brew deps --tree --installed
# https://homebrew-file.readthedocs.io/
#
# Usage:
#
# brew bundle dump
# brew bundle dump --force
# brew bundle install --file /path/to/Brewfile
# Specify directory to install GUI applications
cask_args appdir: "/Applications"
# Taps
#tap "homebrew/core"
#tap "homebrew/bundle"
#tap "homebrew/services"
#tap "homebrew/autoupdate"
#tap "homebrew/cask"
#tap "homebrew/cask-drivers"
#tap "homebrew/cask-fonts"
#tap "homebrew/cask-versions"
#tap "homebrew/command-not-found"
#tap "buo/cask-upgrade"
tap "aws/tap"
tap "sebsto/macos"
#tap "1password/tap"
# Install packages
#brew "[email protected]"
brew "openssl"
brew "ca-certificates"
brew "mas"
brew "cliclick"
brew "betterdisplay"
brew "displayplacer"
brew "deskpad"
brew "xcodeinstall"
#brew "binutils"
#brew "findutils"
#brew "diffutils"
#brew "htop"
brew "bottom"
brew "glances"
brew "netdata"
brew "fio"
brew "ncdu"
brew "duf"
brew "tree"
brew "mosh"
brew "screen"
brew "tmux"
brew "awscli"
brew "wget"
#brew "curl"
brew "jq"
brew "eza"
#brew "chezmoi"
#brew "stow"
#brew "gnupg"
#brew "pinentry-mac"
brew "git"
brew "git-lfs"
#brew "git-delta"
brew "gh"
#brew "hub"
#brew "github-keygen"
#brew "difftastic"
brew "delta"
brew "colordiff"
brew "fswatch"
brew "watchman"
brew "ripgrep"
brew "fd"
brew "fzf"
#brew "neovim"
#brew "bash"
#brew "bash-completion"
#brew "zsh"
#brew "zsh-autosuggestions"
#brew "zsh-completions"
#brew "zsh-syntax-highlighting"
#brew "fish"
#brew "tldr"
brew "shellcheck"
brew "hadolint"
#brew "actionlint"
#brew "gcc"
brew "llvm"
brew "clang-build-analyzer"
#brew "make"
#brew "cmake"
#brew "autoconf"
#brew "boost"
brew "ccache"
#brew "cpplint"
brew "ninja"
#brew "helm"
brew "ansible"
#brew "terraform"
#brew "terragrunt"
#brew "terraform-ls"
brew "python3"
brew "node@20"
#brew "rust"
brew "rustup-init"
#brew "go"
#brew "mono"
#brew "hugo"
#brew "imagemagick"
#brew "docutils"
#brew "pandoc"
#brew "pulumi"
#brew "ffmpeg"
#brew "youtube-dl"
#brew "hunspell"
# Audio
brew "switchaudio-osx"
brew "sox"
brew "blackhole-2ch"
# GNU
brew "gnu-time"
#brew "gnu-tar"
#brew "gnu-which"
#brew "gnu-indent"
#brew "gnu-sed"
#brew "gawk"
#brew "grep"
#brew "findutils"
# GitHub Action
# Gitlab Runner
#brew "gitlab-runner"
# CircleCi
#brew "circleci"
# Casks - https://github.com/Homebrew/homebrew-cask/tree/master/Casks
#cask 'rectangle-pro'
#cask 'iterm2'
cask 'google-chrome'
#cask 'firefox'
#cask 'visual-studio-code'
#cask "sublime-text"
#cask "emacs"
#cask "utm"
#cask "docker"
#cask "postman"
#cask 'alfred'
#cask 'dropbox'
#cask 'virtualbox'
#cask 'slack'
#cask 'spotify'
#cask '1password'
#cask 'appcleaner'
#cask 'discord'
#cask "slack"
#cask "arq"
#cask "carbon-copy-cloner"
# Intel
#cask "intel-power-gadget"
# Apple Silicon
#cask "mx-power-gadget"
# Fonts
#cask "font-fira-code"
#cask "font-fira-code-nerd-font"
# Install java before jenkins
#cask 'java'
#brew 'jenkins'
# MAS
#mas "com.apple.dt.Xcode", id: 497799835 # Xcode
# sudo xcodebuild -license accept
#mas "com.agilebits.onepassword-osx", id: 443987910 # 1Password
#mas "com.apple.iWork.Pages", id: 409201541 # Pages
#mas "com.apple.iWork.Keynote", id: 409183694 # Keynote
#mas "com.apple.iWork.Numbers", id: 409203825 # Numbers
# install vscode extensions
# function vscode() {
# code --install-extension $1
# }
#vscode "eamodio.gitlens"
#vscode "esbenp.prettier-vscode"
#vscode "golang.go"
#vscode "GitHub.copilot"
#vscode "GitHub.github-vscode-theme"
#vscode "github.vscode-github-actions"
#vscode "hashicorp.terraform"
#vscode "ms-azuretools.vscode-docker"
#vscode "ms-kubernetes-tools.vscode-kubernetes-tools"
#vscode "ms-python.python"
#vscode "ms-python.vscode-pylance"
#vscode "ms-vscode-remote.remote-containers"
#vscode "ms-vscode.makefile-tools"
#vscode "redhat.vscode-yaml"
#!/bin/bash
USER=$(stat -f%Su /dev/console)
loggedInUser=$(stat -f%Su /dev/console)
# System Caches
sudo mv /private/var/log/privoxy /private/var/privoxy > /dev/null 2>&1
sudo /bin/rm -rf /private/var/log/* > /dev/null 2>&1
sudo mv /private/var/privoxy /private/var/log/privoxy > /dev/null 2>&1
# System Caches
sudo /bin/rm -rf /Users/$loggedInUser/Library/Logs/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Library/Logs/DiagnosticReports/*.* > /dev/null 2>&1 &
sudo /bin/rm -rf /private/var/tmp/com.apple.messages > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Caches/* > /dev/null 2>&1 &
sudo /bin/rm -rf /private/var/db/diagnostics/*/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Library/Logs/DiagnosticReports/ProxiedDevice-Bridge/*.ips > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/CrashReporter/* > /dev/null 2>&1 &
sudo /bin/rm -rf /private/tmp/gzexe* > /dev/null 2>&1
# Safari Cache
sudo /bin/rm -rf /Users/$loggedInUser/Library/Containers/com.apple.Safari/Data/Library/Caches/* > /dev/null 2>&1 &
sudo /bin/rm -rf /private/var/folders/ry/*/*/com.apple.Safari/com.apple.Safari/com.apple.metal/*/libraries.data > /dev/null 2>&1 &
sudo /bin/rm -rf /private/var/folders/ry/*/*/com.apple.Safari/com.apple.Safari/com.apple.metal/*/libraries.maps > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Containers/io.te0.WebView/Data/Library/Caches/WebKit > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Safari/History.db* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Safari/RecentlyClosedTabs.plist > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Safari/CloudHistoryRemoteConfiguration.plist > /dev/null 2>&1
# Chrome Caches
chromeApp="/Applications/Google Chrome.app"
if [[ -d "${chromeApp}" ]]; then
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/GPUCache/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Storage/ext/*/def/GPUCache/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/*-journal > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/databases/*-journal > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Visited\ Links > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Top\ Sites > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/History\ Provider\ Cache > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Current\ Tabs > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Network\ Action\ Predictor > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/*.ldb > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/*.log > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Extension\ State/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Session\ Storage/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Current\ Session > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/Storage/ext/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/Library/Application\ Support/Google/Chrome/*/*/Cache > /dev/null 2>&1
fi
# Clean the download history
sudo sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* 'delete from LSQuarantineEvent' > /dev/null 2>&1
# Clean Terminal History
sudo /bin/rm -rf /Users/$loggedInUser/.bash_sessions/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/.bash_history > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/.zsh_sessions/* > /dev/null 2>&1 &
sudo /bin/rm -rf /Users/$loggedInUser/.zsh_history > /dev/null 2>&1
# Applications Caches
for cf in $(ls ~/Library/Containers/); do
echo "Cleaning ~/Library/Containers/${cf}/Data/Library/Caches/"
rm -rf ~/Library/Containers/$cf/Data/Library/Caches/*
done
echo "done."
$ ssh ec2-3-26-159-255.ap-southeast-2.compute.amazonaws.com
┌───┬──┐ __| __|_ )
│ ╷╭╯╷ │ _| ( /
│ └╮ │ ___|\___|___|
│ ╰─┼╯ │ Amazon EC2
└───┴──┘ macOS Sonoma 14.2.1
Error reading managed configuration (2: No such file or directory). Proceeding with default configuration.
Error reading managed configuration (2: No such file or directory). Proceeding with default configuration.
Error reading managed configuration (2: No such file or directory). Proceeding with default configuration.
ec2-user@ip-172-31-34-123 ~ % mkdir -p ~/Library/Keychains
ec2-user@ip-172-31-34-123 ~ % security create-keychain ~/Library/Keychains/login.keychain
password for new keychain:
retype password for new keychain:
ec2-user@ip-172-31-34-123 ~ % security unlock-keychain ~/Library/Keychains/login.keychain
password to unlock /Users/ec2-user/Library/Keychains/login.keychain:
ec2-user@ip-172-31-34-123 ~ % ls -lA ~/Library/Keychains/
total 40
-r--r--r-- 1 ec2-user staff 0 Feb 9 21:41 .fl34AC2A0A
drwx------ 3 ec2-user staff 96 Feb 9 21:41 2E10E592-2698-5E8D-9C66-7AB9DD1296E6
-rw-r--r-- 1 ec2-user staff 20460 Feb 9 21:41 login.keychain-db
ec2-user@ip-172-31-34-123 ~ % security login-keychain -d user -s ~/Library/Keychains/login.keychain
ec2-user@ip-172-31-34-123 ~ % ls -lA ~/Library/Keychains/
total 40
-r--r--r-- 1 ec2-user staff 0 Feb 9 21:41 .fl34AC2A0A
drwx------ 3 ec2-user staff 96 Feb 9 21:41 2E10E592-2698-5E8D-9C66-7AB9DD1296E6
-rw-r--r-- 1 ec2-user staff 20460 Feb 9 21:41 login.keychain-db
ec2-user@ip-172-31-34-123 ~ % security default-keychain -d user
"/Users/ec2-user/Library/Keychains/login.keychain-db"
ec2-user@ip-172-31-34-123 ~ % security list-keychains -d user
"/Users/ec2-user/Library/Keychains/login.keychain-db"
ec2-user@ip-172-31-34-123 ~ % security default-keychain
"/Users/ec2-user/Library/Keychains/login.keychain-db"
ec2-user@ip-172-31-34-123 ~ % security list-keychains
"/Users/ec2-user/Library/Keychains/login.keychain-db"
"/Library/Keychains/System.keychain"
#!/bin/zsh -f
# EBS hydration script, it's got what EBS volumes crave!
# https://docs.aws.amazon.com/ebs/latest/userguide/ebs-initialize.html
# https://n2ws.com/blog/how-to-guides/pre-warm-ebs-volumes-on-aws
# https://aws.amazon.com/blogs/storage/addressing-i-o-latency-when-restoring-amazon-ebs-volumes-from-ebs-snapshots/
# https://www.youtube.com/watch?v=kaWzAEVZ6k8
# uname -m works too
case $(/usr/bin/arch) in
arm64) PATH="/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" ;;
*) PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" ;;
esac
export PATH
function log() { printf "[$(date)] ${@} \n" };
export HOMEBREW_NO_ENV_HINTS=1
export HOMEBREW_NO_INSTALL_CLEANUP=1
export HOMEBREW_NO_ENV_FILTERING=1
alias brewup="$(brew --prefix)/bin/brew update";
alias brewin="$(brew --prefix)/bin/brew install";
# /opt/homebrew/bin/fio
command -v fio >/dev/null 2>&1 \
|| { log "Required fio tool is not installed.."; brewup && brewin fio };
log "Hydrating the EBS volume.."
sudo /usr/bin/caffeinate -i $(brew --prefix)/bin/fio \
--filename=/dev/r$(df -h / | grep -o 'disk[0-9]') \
--rw=read \
--bs=4096k \
--iodepth=32 \
--numjobs=1 \
--group_reporting \
--eta-newline=1 \
--ioengine=posixaio \
--direct=1 \
--readonly \
--name=ebs-prewarm \
--output-format=json
log "done."
#!/bin/bash
# 1. Check whether the user has a password set as this is necessary to perform updates.
# 2. Check whether the user is a secure token holder as this is necessary to perform updates.
# 3. Check whether the user is a volume owner as this is necessary to perform updates.
function log() { echo "[$(date)] ${@}" };
# Set PATH depending on whether it is an x86_64 or Apple Silicon based EC2 Mac host.
# uname -m works too
case $(/usr/bin/arch) in
arm64) PATH="/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" ;;
*) PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" ;;
esac
#log $PATH
# Check whether FileVault2 enabled
function fileVaultCheck() {
sudo fdesetup isactive
};
# Check for existing enrollment with MDM
function enrollmentCheck() {
sudo /usr/bin/profiles status -type enrollment
sudo /usr/bin/profiles -Lv
sudo /usr/bin/profiles -P
#cat /Library/Logs/ManagedClient/ManagedClient.log
#log show --last 7d --predicate 'process == "mdmclient" OR subsystem == "com.apple.ManagedClient" OR processImagePath contains "mdmclient"'
};
function updateApfsPreboot() {
sudo diskutil apfs updatePreboot /
};
# Flush DNS cache
function flushDnsCache() {
log "The ${currUser} user is part of the admin group."
sudo /usr/bin/dscacheutil -flushcache \
&& sudo /usr/bin/killall -HUP mDNSResponder
};
function listSwu() {
/usr/sbin/softwareupdate -l --verbose --all
};
function downloadSwu() {
/usr/sbin/softwareupdate -d "${swuLabel}"
};
# For Apple Silicon based EC2 Mac instances
function forceInstallSwuAndReboot() {
sudo /usr/sbin/softwareupdate --install --all --restart --agree-to-license --force
};
# Re-run the following post update
function disableAutoSwu() {
/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool false
/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool false
/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticallyInstallMacOSUpdates -bool false
/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist ConfigDataInstall -bool false
/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool false
/usr/bin/defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool false
};
# Issues?
function swuIssuesChecker() {
# Check for errors
/usr/bin/defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist DDMPersistedErrorKey
# After running softwareupdate --dump-state, you can view the info it dumps in /var/log/install.log
/usr/sbin/softwareupdate --dump-state
cat /var/log/install.log
log show --last 10m --predicate "processImagePath Contains[c] 'softwareupdate'"
#sudo log stream --predicate "processImagePath Contains[c] 'softwareupdate'"
#sudo log stream --predicate "processImagePath Contains[c] 'softwareupdate' AND eventMessage Contains[c] 'progress'"
#sudo log collect --output /your/path
#sudo log collect --archive system_logs.logarchive
};
currUser=$(/usr/bin/stat -f%Su /dev/console)
currUserGroups=$(/usr/bin/id -Gn ${currUserGroups})
log "Check if the user has a password set.."
sudo /usr/bin/plutil -p "/var/db/dslocal/nodes/Default/users/${currUser}.plist"
#/usr/bin/dscl . -read /Users/$USER accountPolicyData | sed '1,2d' | /usr/bin/xpath -e "/plist/dict/real[preceding-sibling::key='passwordLastSetTime'][1]/text()" 2> /dev/null
#/usr/bin/dscl . -read /Users/$USER AuthenticationAuthority
log "Check if users password on the host is correct.."
# if after inputing password returns nothing, then password is assumed correct.
#su "${currUser}" -c exit
/usr/bin/dscl /Local/Default -authonly "${currUser}"
log "Check if the user is a secure token holder.."
sysadminctl -secureTokenStatus "${currUser}"
#sudo sysadminctl -secureTokenOn ec2-user -password <password_goes_here>
#sudo sysadminctl -secureTokenOn ec2-user -password -
#sudo sysadminctl interactive -secureTokenOn ec2-user -password –
# To find out which users on the host are secure token holders
for user in $(dscl . list /Users UniqueID | awk '$2 > 499 {print $1}'); do
printf "Checking ${user}..\n"
sudo sysadminctl -secureTokenStatus "${user}"
done
# Make sure the user is part of the admin group
#dscl . -read /Groups/admin GroupMembership | awk '{print $2, $3, $4, $5, $6, $7, $8, $9}'
# 0 = true, 67 = false
#if groups "{currUser}" | grep -q -w admin; then
if dseditgroup -o checkmember -m "${currUser}" admin > /dev/null; then
log "The ${currUser} user is part of the admin group."
else
log "The ${currUser} user is not part of the admin group."
: sudo dscl . -append /Groups/admin GroupMembership "${currUser}"
fi
# Check to see user names and GUIDs together and to check if you have a valid disk owner.
#sudo fdesetup list -extended
if sudo fdesetup list -extended | grep "${currUser}"; then
log "The ${currUser} user is a volume owner."
# View the current list of delegated volume owners on Apple Silicon based Mac host
sudo diskutil apfs listUsers /
#sudo diskutil apfs listUsers / -plist
# Replace GUID from previous command output to see more details about the user(s)
dscl . -search /Users GeneratedUID "${userGUID}"
else
log "The ${currUser} user is NOT a volume owner."
#sudo fdesetup add -usertoadd "${currUser}"
fi
# Check for proxy and security appliances e.g. zscaler
# https://help.zscaler.com/zia/verifying-users-traffic-being-forwarded-zscaler-service
# The request received from you didn't come from a Zscaler IP therefore you are not going through the Zscaler proxy service
scutil --proxy
curl -vvv https://ip.zscaler.com | grep "The request received from you"
log "Sometimes you have to kick macOS to make it do what you want..\n"
#/usr/bin/defaults read /Library/Preferences/com.apple.commerce.plist
/usr/bin/defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist
#sudo /bin/rm "/Library/Preferences/com.apple.SoftwareUpdate.plist"
sudo /bin/launchctl kickstart -k system/com.apple.softwareupdated
#/bin/launchctl kickstart -k system/com.apple.softwareupdated
#!/bin/zsh -f
sudo log config --subsystem com.apple.ManagedClient --mode="level:debug,persist:debug"
sudo /usr/bin/defaults write /Library/Preferences/com.apple.MCXDebug debugOutput -2
sudo /usr/bin/defaults write /Library/Preferences/com.apple.MCXDebug collateLogs 1
sudo touch /var/db/MDM_EnableDebug
# Enable debug logging for Jamf MDM Enrollment
sudo /usr/bin/defaults write /Library/Preferences/com.jamfsoftware.jamf.plist global_log_level DEBUG
# View logs
#tail -n 100 /Library/Logs/ManagedClient/ManagedClient.log
#tail -n 100 /var/log/system.log
#sudo log stream --info --debug --predicate 'subsystem contains "com.apple.ManagedClient.cloudconfigurationd"'
#sudo log stream --info --debug --predicate 'processImagePath contains "mdmclient" OR processImagePath contains "storedownloadd"'
#!/usr/bin/env bash
# Reset macOS route table and bounce interface
function is_root() {
if [[ "${EUID}" -ne 0 ]]; then
>&2 echo "This script requires super user privileges e.g. sudo..";
exit 1;
fi
}
is_root
networkInterface=$1
if [ -z ${networkInterface} ]; then
networkInterface="en1";
fi
# Display the current routing table
echo "********** BEFORE ****************************************"
netstat -rn
echo "**********************************************************"
# Flush the route table a few times (for good measure)
for i in {0..4}; do
sudo route -n flush # several times
done
# Display the route table after flushing
echo "********** AFTER *****************************************"
netstat -rn
echo "**********************************************************"
# Bounce the interface
echo "Bringing interface (${networkInterface}) down..."
sudo ifconfig "${networkInterface}" down
sleep 1
echo "Bringing interface (${networkInterface}) up..."
sudo ifconfig "${networkInterface}" up
sleep 1
# Display the route table after flushing and bouncing the interface
echo "********** FINALLY ***************************************"
netstat -rn
echo "**********************************************************"
#!/bin/bash
# Screen Sharing Fixer
# First try to restart and disable both the ARD and Screen Sharing
# service(s), then re-enable the screen sharing service.
# Restart and disable the Apple Remote Desktop (ARD) service
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -configure -activate -access -on -privs -all -allowaccessfor -allusers -restart -agent
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate -configure -access -off
# Stop and disable the macOS Screen Sharing service
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.screensharing.plist \
&& sudo launchctl disable system/com.apple.screensharing
# Re-enable the macOS Screen Sharing service
sudo launchctl enable system/com.apple.screensharing \
&& sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
# Now check the service e.g. listening on port 5900.
# You should see: `tcp4 0 0 *.5900`
sudo netstat -p tcp -van | grep LISTEN
# To restart just the service screen sharing services
#sudo /bin/launchctl unload /System/Library/LaunchDaemons/com.apple.screensharing.plist \
# && sudo /bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist
# Check the status of the service
# If it's disabled and/or not running, then this will likely return an error e.g.
# `Bad request. Could not find service "com.apple.screensharing" in domain for system`
sudo launchctl print system/com.apple.screensharing
# If it's enabled, this should return the following: `"com.apple.screensharing" => enabled`
# Ignore the fact that you see it in disabled services = {
sudo launchctl print-disabled system/
# View the log stream for screensharingd and related logs:
log show --last 1d --predicate 'processImagePath CONTAINS "screensharingd" AND eventMessage CONTAINS "Authentication"'
#log show --last 7d --predicate 'processImagePath CONTAINS "screensharingd" AND eventMessage CONTAINS "Authentication"'
#log stream --process screensharingd
#!/bin/zsh -f
cat <<'EOF' | tee privatelogs.cpp
#include <mach/mach_host.h>
#include <stdint.h>
#include <stdio.h>
const uint32_t private_data_flag = 1 << 24;
int main(int argc, char **argv) {
if (argc == 2 && ++argv) {
uint32_t diagnostic_flag;
host_get_atm_diagnostic_flag(mach_host_self(), &diagnostic_flag);
if (!strcmp(*argv, "status")) {
puts(diagnostic_flag & private_data_flag ? "enabled" : "disabled");
return 0;
} else if (!strcmp(*argv, "enable")) {
return host_set_atm_diagnostic_flag(mach_host_self(), diagnostic_flag | private_data_flag);
} else if (!strcmp(*argv, "disable")) {
return host_set_atm_diagnostic_flag(mach_host_self(), diagnostic_flag & ~private_data_flag);
}
} else {
fprintf(stderr, "Usage: %s <status|enable|disable>\n", *argv);
}
}
EOF
/usr/bin/g++ privatelogs.cpp -o privatelogs
./privatelogs enable
./privatelogs status
makemkvcon --noscan --minlength=0 -r backup --decrypt disc:0

Convert iso to mkv:

makemkvcon mkv iso:./movie.iso all .

Convert files to mkv:

makemkvcon mkv file:/path/to/the/VIDEO_TS/ all .

By drive number:

# scan for drive number, usually it'll be 0 if you have only one drive
makemkvcon -r --cache=1 info disc:9999
# rip a disc by drive number to a path
makemkvcon mkv disc:0 all .
#!/usr/bin/env bash
if [[ $UID -ne 0 ]]; then
echo "Please run ${0} as root e.g. sudo."
exit 1
fi
function runAsRoot() {
# Pass in the full path to the executable as $1
if [[ "${USER}" != "root" ]] ; then
echo "This script requires root priviledges e.g. sudo.."
sudo "${1}" && exit 0
fi
}
#runAsRoot "${0}"
# Usage: runAsUser <command> <arguments>
function runAsUser() {
local currentUser uid
currentUser=$(stat -f%Su /dev/console)
uid=$(id -u "${currentUser}")
if [ "${currentUser}" != "loginwindow" ]; then
launchctl asuser "${uid}" sudo -u "${currentUser}" "${@}"
else
echo "There is no users currently logged in to the host."
#exit 1
fi
}
# gid 20 is the "staff" group, which is the normal primary group for user accounts.
# gid 80 is the admin group and setting a users primary group ID to 80 will add them
# to the admin group and hence give them admin rights on the computer.
newUser="ec2macadmin"
newUserFull="ec2macadmin"
newUserPass="stevejobs"
newUserGroups=(staff admin)
adBindCheck=$(/usr/bin/dscl localhost -list . | grep "Active Directory")
# Get curret list of users with UIDs above 1000
listCurrUsers=$(/usr/bin/dscl . list /Users UniqueID | awk '$2 > 1000 {print $1}')
# Get the next available UID
currMaxUID=$(/usr/bin/dscl . -list /Users UniqueID | awk '{print $2}' | sort -ug | tail -1)
newUserUID=$((currMaxUID+1))
# Create the new user account
# sysadminctl -addUser "${newUser}" -fullName "${newUserFull}" -password -
/usr/bin/dscl . -create "/Users/${newUser}"
/usr/bin/dscl . -create "/Users/${newUser}" UniqueID "${newUserUID}"
/usr/bin/dscl . -create "/Users/${newUser}" UserShell /bin/zsh
/usr/bin/dscl . -create "/Users/${newUser}" RealName "${newUserFull}"
/usr/bin/dscl . -create "/Users/${newUser}" PrimaryGroupID 20
/usr/bin/dscl . -create "/Users/${newUser}" NFSHomeDirectory "/Users/${newUser}"
# Create home directory for the new user
newUserHomeDir="$(/usr/bin/dscl . -read "/Users/${newUser}" NFSHomeDirectory | awk '{print $2}')"
if [[ "$homedir" != "" ]]; then
createhomedir -c -u "${newUser}" > /dev/null
#mkdir -p "/Users/${newUser}"
#/usr/sbin/chown -R "${newUser}" "${newUserHomeDir}"
#/usr/sbin/chown -R "${newUser}":staff "${newUserHomeDir}"
fi
/usr/bin/dscl . -delete "/Users/${newUser}" AuthenticationAuthority &> /dev/null
#/usr/bin/dscl . -append "/Users/${newUser}" AuthenticationHint ''
#/usr/bin/dscl . -append "/Users/${newUser}" AvatarRepresentation ''
#/usr/bin/dscl . -append "/Users/${newUser}" inputSources ''
#/usr/bin/dscl . -delete "/Users/${newUser}" HeimdalSRPKey &> /dev/null
#/usr/bin/dscl . -delete "/Users/${newUser}" KerberosKeys &> /dev/null
#/usr/bin/dscl . -delete "/Users/${newUser}" ShadowHashData &> /dev/null
#/usr/bin/dscl . -delete "/Users/${newUser}" _writers_passwd &> /dev/null
#/usr/bin/dscl . -create "/Users/${newUser}" Password '*'
/usr/bin/dscl . -read "/Users/${newUser}" HeimdalSRPKey KerberosKeys ShadowHashData _writers_passwd Password 2>&1 | sort
#/usr/bin/dscl . -deletepl "/Users/${newUser}" accountPolicyData failedLoginCount &> /dev/null
#/usr/bin/dscl . -deletepl "/Users/${newUser}" accountPolicyData failedLoginTimestamp &> /dev/null
#/usr/bin/dscl . -deletepl "/Users/${newUser}" accountPolicyData passwordLastSetTime &> /dev/null
# To prevent a user from being granted a secure token when setting their password
#sudo /usr/bin/dscl . -append "/Users/${newUser}" AuthenticationAuthority ";DisabledTags;SecureToken"
# Set the password for the user
passwd "${newUser}"
#/usr/bin/dscl . -passwd "/Users/${newUser}" "${newUserPass}"
#/usr/bin/plutil -p "/var/db/dslocal/nodes/Default/users/${newUser}.plist"
#security set-keychain-password -o "${oldUserPass}" -p "${newUserPass}" /Users/username/Library/Keychains/login.keychain
#sudo /usr/bin/dscl . -passwd "/Users/${newUser}"
#sudo security set-keychain-password
#sudo rm -r /Users/username/Library/Keychains/*
# Add user to any specified groups
for group in "${newUserGroups}"; do
dseditgroup -o edit -t user -a "${newUser}" "${group}"
#sudo /usr/bin/dscl . -merge "/Groups/${group}" GroupMembership "${newUser}"
done
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user staff
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user admin
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user everyone
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user localaccounts
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user _appserverusr
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user _appserveradm
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user _lpadmin
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user _appstore
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user _lpoperator
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user _developer
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user com.apple.access_ssh
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user com.apple.access_screensharing
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user com.apple.access_ftp
#/usr/sbin/dseditgroup -o edit -a "${newUser}" -t user com.apple.sharepoint.group.1
# List users part of a group
/usr/bin/dscl . -read /groups/admin GroupMembership
# Verify new user is part of groups
#dsmemberutil checkmembership -U "${newUser}" -G admin
#dsmemberutil checkmembership -U "${newUser}" -G staff
#dsmemberutil checkmembership -U "${newUser}" -G wheel
# Remote Access i.e. SSH
sudo /usr/sbin/dseditgroup -o create -q com.apple.access_ssh
sudo /usr/sbin/dseditgroup -o edit -t user -a "${newUser}" com.apple.access_ssh
sudo /usr/bin/dscl . -read /Groups/com.apple.access_ssh
# Screen Sharing
#sudo /usr/sbin/dseditgroup -o create -q com.apple.access_screensharing
#sudo /usr/sbin/dseditgroup -o edit -a "${newUser}" -t user com.apple.access_screensharing
#sudo /usr/sbin/dseditgroup -o edit -a "${localGroup}" -t group com.apple.access_screensharing
#sudo /usr/sbin/dseditgroup -o edit -a "*DomainName**DomainUserName*" -t user com.apple.access_screensharing
#sudo /usr/sbin/dseditgroup -o edit -a "*DomainName**DomainGroupName*" -t group com.apple.access_screensharing
#sudo /usr/bin/dscl . -read /Groups/com.apple.access_screensharing
#sudo /usr/bin/dscl -f "/var/db/dslocal/nodes/Default" localonly -read /Local/Target/Groups/com.apple.access_screensharing
printf "Created user #${newUserUID}: ${newUser} (${newUserFull})\n"
#su - "${newUser}" -l
#sudo su - "${newUser}" -l
#!/bin/bash
## WIP
diskutil list
diskutil listFilesystems
#diskutil eraseDisk APFS buildvolume /dev/disk4
diskutil partitiondisk disk4 1 gpt apfs "buildvolume" 0
diskutil info disk4
#container=$(diskutil info disk4s2 | grep Container)
#diskutil apfs addVolume "${container##* }" APFS bv
#!/bin/bash
function get_proxy() {
p="$1"
enable="$(scutil --proxy | grep "${p}Enable" | cut -d: -f2)"
host="$(scutil --proxy | grep "${p}Proxy" | cut -d: -f2 | tr -d " ")"
port="$(scutil --proxy | grep "${p}Port" | cut -d: -f2 | tr -d " ")"
if [[ "$enable" -eq 1 ]] ; then
echo "${host}:${port}"
fi
};
http=$(get_proxy HTTP)
https=$(get_proxy HTTPS)
ftp=$(get_proxy FTP)
[ -n "$http" ] && echo export http_proxy=\"$http\"
[ -n "$https" ] && echo export https_proxy=\"$https\"
[ -n "$ftp" ] && echo export ftp_proxy=\"$ftp\"
#!/bin/bash
brew install screenresolution
cat <<"EOF" | sudo tee -a /usr/local/bin/set-screenresolution.sh
#!/bin/bash
sleep 20
/usr/local/bin/screenresolution set 1280x800x32@0
EOF
sudo chmod a+x /usr/local/bin/set-screenresolution.sh
sudo tee -a ~/Library/LaunchAgents/screenresolution.plist <<"EOF"
<?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>com.amazon.ec2.screenresolution</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/set-screenresolution.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
<key>LaunchOnlyOnce</key>
<true/>
<key>StandardErrorPath</key>
<string>/tmp/screenresolution.err</string>
<key>StandardOutPath</key>
<string>/tmp/screenresolution.out</string>
</dict>
</plist>
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment