Cover photo

Enforce Privacy & Security Best-Practices on macOS Using Terminal in 15 minutes

No need to run any compiled software on your system, just run the generated scripts using Terminal.

Good Morning!

Delivering interesting content every single week on Web3, Security, Crypto, NFTs, Design & AI.

It's FREE, Takes less than 5-minutes to read, and you are guaranteed to learn something.

Subscribe to get valuable News, Useful Resources and Insights every week to your Inbox!


Unveil the hidden potential of your Mac's Terminal to lock down your privacy and security like a pro. Dive into a world of powerful commands and master the art of protecting your digital haven.

Introduction: Unleashing Terminal Magic for Rock-Solid macOS Privacy and Security

Welcome to a realm where your Mac's true power lies beneath the sleek surface of its user-friendly interface. The Terminal, often overshadowed by its graphical counterparts, holds the key to transforming your macOS experience into an impregnable fortress of privacy and security. In this guide, we'll delve deep into the heart of Terminal commands, unlocking their potential to shield your digital life from prying eyes and malicious threats.

Are you tired of sifting through countless settings and apps to secure your Mac? Fret not, for we're about to embark on an exciting journey through the Terminal's secret passages. Buckle up, fellow Mac enthusiast, as we unveil a treasure trove of knowledge and equip you with the tools needed to enforce privacy and security best-practices like a seasoned hacker (minus the black hoodie and Matrix code).


Why Terminal? Unmasking the Power Behind the Command Line

"Why bother with Terminal when I have shiny icons and user-friendly settings?"

Ah, a valid question, my curious friend. While macOS offers a range of built-in security features, Terminal provides you with unparalleled control over your system's inner workings. Here's why diving into the command line can be a game-changer:

  1. Precision at Your Fingertips: Terminal commands allow you to make precise changes to your system, tailoring security measures to your exact needs. No more sifting through convoluted menus.

  2. Speed and Efficiency: Zip through tasks that would normally take several clicks with just a few keystrokes. Your time is valuable, after all.

  3. Access to Hidden Settings: Unearth settings that are usually tucked away, granting you access to advanced privacy configurations that the average user can only dream of.

  4. Script Your Defenses: With Terminal, you can create custom scripts to automate security processes, ensuring your Mac stays fortified without breaking a sweat.

The Commandments: Essential Terminal Commands for Fortifying Privacy

Ready to flex your newfound Terminal muscles? Here's a compilation of must-know commands to bolster your Mac's privacy defenses:

  1. Firewall Fortification (firewall-cmd): Shield your Mac from unauthorized network access by configuring the built-in firewall. Limit incoming connections and decide which apps can communicate through the network.

  2. File Encryption Mastery (gpg): Secure your sensitive files with military-grade encryption using the GnuPG tool. Keep your data locked down, even if someone gains physical access to your machine.

  3. Privacy-Preserving Browsing (tor): Explore the depths of the internet with enhanced privacy through the Tor network. Safeguard your online activities from prying eyes.

  4. Two-Factor Authentication (ssh-keygen): Elevate your authentication game by generating SSH key pairs. Bid farewell to solely relying on passwords for accessing your Mac.

  5. Cache Clearance (dscacheutil): Wipe away traces of your DNS cache, erasing any records of your online escapades. Keep your browsing history for your eyes only.


FAQs: Decrypting Your Terminal Mysteries

Q: Is it safe to use Terminal for security configurations? A: Absolutely! Terminal is a powerful tool in the hands of a cautious user. Just ensure you follow instructions carefully and double-check commands before hitting Enter.

Q: Can I undo changes made through Terminal? A: In most cases, yes. Many commands have reversal counterparts or can be undone by resetting settings. However, it's wise to back up your data before performing extensive changes.

Q: Will using Terminal void my warranty? A: Nope, using Terminal commands within macOS's intended scope won't void your warranty. However, venturing into unauthorized territories might raise some eyebrows at the Genius Bar.


๐Ÿ“™ Start by exploring different categories and choosing different tweaks.

Privacy Cleanup:

Clear Bash History:

rm -f ~/.bash_history

Clear zsh history:

rm -f ~/.zsh_history

Clear OS Logs:

Clear Diagnostics Logs:

sudo rm -rfv /private/var/db/diagnostics/*
sudo rm -rfv /var/db/diagnostics/*

Clear shared-cache strings data:

sudo rm -rfv /private/var/db/uuidtext/
sudo rm -rfv /var/db/uuidtext/

Clear Apple System Logs (ASL):

sudo rm -rfv /private/var/log/asl/*
sudo rm -rfv /var/log/asl/*
sudo rm -fv /var/log/asl.log # Legacy ASL (10.4)
sudo rm -fv /var/log/asl.db

Clear Install Logs:

sudo rm -fv /var/log/install.log

Clear All System Logs:

sudo rm -rfv /var/log/*

Clear System Application Logs:

sudo rm -rfv /Library/Logs/*

Clear Mail Logs:

rm -rfv ~/Library/Containers/com.apple.mail/Data/Library/Logs/Mail/*

Clear Audit Logs: (login, logout, authentication and other user activity)

sudo rm -rfv /var/audit/*
sudo rm -rfv /private/var/audit/*

Clear User Logs: (User Reports)

sudo rm -rfv ~/Library/Logs/*

Clear Daily Logs:

sudo rm -fv /System/Library/LaunchDaemons/com.apple.periodic-*.plist

Clear Receipt Logs for Installed Packages/Apps:

sudo rm -rfv /var/db/receipts/*
sudo rm -vf /Library/Receipts/InstallHistory.plist

Clear Browser History:

Clear Google Chrome Browser History:

rm -rfv ~/Library/Application\ Support/Google/Chrome/Default/History &>/dev/null
rm -rfv ~/Library/Application\ Support/Google/Chrome/Default/History-journal &>/dev/null

Clear Google Chrome Cache Files:

sudo rm -rfv ~/Library/Application\ Support/Google/Chrome/Default/Application\ Cache/* &>/dev/null

Clear Safari Caches:

rm -f ~/Library/Caches/com.apple.Safari/Cache.db
rm -f ~/Library/Safari/WebpageIcons.db
rm -rfv ~/Library/Caches/com.apple.Safari/Webpage\ Previews

Clear Safari Browsing History:

rm -f ~/Library/Safari/History.db
rm -f ~/Library/Safari/History.db-lock
rm -f ~/Library/Safari/History.db-shm
rm -f ~/Library/Safari/History.db-wal
# For older versions of Safari
rm -f ~/Library/Safari/History.plist # URL, visit count, webpage title, last visited timestamp, redirected URL, autocomplete
rm -f ~/Library/Safari/HistoryIndex.sk # History index

Clear Safari Downloads History:

rm -f ~/Library/Safari/Downloads.plist

Clear Safari Top Sites:

rm -f ~/Library/Safari/TopSites.plist

Clear Safari Last Session (Open Tabs) History:

rm -f ~/Library/Safari/LastSession.plist

Clear Copy of the Safari History:

rm -rfv ~/Library/Caches/Metadata/Safari/History

Clear Search History Embedded in Safari Preferences:

defaults write ~/Library/Preferences/com.apple.Safari RecentSearchStrings '( )'

Clear Safari Cookies:

rm -f ~/Library/Cookies/Cookies.binarycookies
rm -f ~/Library/Cookies/Cookies.plist

Clear Safari Zoom Level Preferences Per Site:

rm -f ~/Library/Safari/PerSiteZoomPreferences.plist

Clear URLs that are allowed to display notifications in Safari:

rm -f ~/Library/Safari/UserNotificationPreferences.plist

Clear Safari Per-Site Preference for Downloads, Geolocation, PopUps and Autoplays:

rm -f ~/Library/Safari/PerSitePreferences.db

Clear Firefox Cache:

sudo rm -rf ~/Library/Caches/Mozilla/
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/netpredictions.sqlite

Delete Firefox Form History:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/formhistory.sqlite
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/formhistory.dat

Delete Firefox Site Preference:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/content-prefs.sqlite

Delete Firefox session restore data (loads after the browser closes or crashes:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionCheckpoints.json
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore*.js*
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore.bak*
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore-backups/previous.js*
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore-backups/recovery.js*
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore-backups/recovery.bak*
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore-backups/previous.bak*
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/sessionstore-backups/upgrade.js*-20*

Delete Firefox Passwords:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/signons.txt
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/signons2.txt
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/signons3.txt
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/signons.sqlite
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/logins.json

Delete Firefox HTML5 Cookies:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/webappsstore.sqlite

Delete Firefox Crash Reports:

rm -rfv ~/Library/Application\ Support/Firefox/Crash\ Reports/
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/minidumps/*.dmp

Delete Firefox Backup Files:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/bookmarkbackups/*.json
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/bookmarkbackups/*.jsonlz4

Delete Firefox Cookies:

rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/cookies.txt
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/cookies.sqlite
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/cookies.sqlite-shm
rm -fv ~/Library/Application\ Support/Firefox/Profiles/*/cookies.sqlite-wal
rm -rfv ~/Library/Application\ Support/Firefox/Profiles/*/storage/default/http*

Clear Third Party Application Data:

Clear Adobe Cache:

sudo rm -rfv ~/Library/Application\ Support/Adobe/Common/Media\ Cache\ Files/* &>/dev/null

Clear Gradle Cache:

if [ -d "/Users/${HOST}/.gradle/caches" ]; then
    rm -rfv ~/.gradle/caches/ &> /dev/null
fi

Clear Dropbox Cache:

if [ -d "/Users/${HOST}/Dropbox" ]; then
    sudo rm -rfv ~/Dropbox/.dropbox.cache/* &>/dev/null
fi

Clear Google Drive File Stream Cache:

killall "Google Drive File Stream"
rm -rfv ~/Library/Application\ Support/Google/DriveFS/[0-9a-zA-Z]*/content_cache &>/dev/null

Clear Composer Cache:

if type "composer" &> /dev/null; then
    composer clearcache &> /dev/null
fi

Clear Homebrew Cache:

if type "brew" &>/dev/null; then
    brew cleanup -s &>/dev/null
    rm -rfv $(brew --cache) &>/dev/null
    brew tap --repair &>/dev/null
fi

Clear Any Old Versions of Ruby Gems:

if type "gem" &> /dev/null; then
    gem cleanup &>/dev/null
fi

Clear Docker:

if type "docker" &> /dev/null; then
    docker system prune -af
fi

Clear Pyenv-VirtualEnv Cache:

if [ "$PYENV_VIRTUALENV_CACHE_PATH" ]; then
    rm -rfv $PYENV_VIRTUALENV_CACHE_PATH &>/dev/null
fi

Clear NPM Cache:

if type "npm" &> /dev/null; then
    npm cache clean --force
fi

Clear Yarn Cache:

if type "yarn" &> /dev/null; then
    echo 'Cleanup Yarn Cache...'
    yarn cache clean --force
fi

iOS Cleanup:

Clear iOS Applications:

rm -rfv ~/Music/iTunes/iTunes\ Media/Mobile\ Applications/* &>/dev/null

Clear iOS Photo Caches:

rm -rf ~/Pictures/iPhoto\ Library/iPod\ Photo\ Cache/*

Remove iOS Device Backups:

rm -rfv ~/Library/Application\ Support/MobileSync/Backup/* &>/dev/null

Clear iOS Simulators:

if type "xcrun" &>/dev/null; then
    osascript -e 'tell application "com.apple.CoreSimulator.CoreSimulatorService" to quit'
    osascript -e 'tell application "iOS Simulator" to quit'
    osascript -e 'tell application "Simulator" to quit'
    xcrun simctl shutdown all
    xcrun simctl erase all
fi

Clear the List of iOS Devices Connected:

sudo defaults delete /Users/$USER/Library/Preferences/com.apple.iPod.plist "conn:128:Last Connect"
sudo defaults delete /Users/$USER/Library/Preferences/com.apple.iPod.plist Devices
sudo defaults delete /Library/Preferences/com.apple.iPod.plist "conn:128:Last Connect"
sudo defaults delete /Library/Preferences/com.apple.iPod.plist Devices
sudo rm -rfv /var/db/lockdown/*

Reset Privacy Permissions For All Applications:

Reset Camera Permissions:

tccutil reset Camera

Reset Microphone Permissions:

tccutil reset Microphone

Reset Accessibility Permissions:

tccutil reset Accessibility

Reset Screen Capture Permissions:

tccutil reset ScreenCapture

Reset Reminders Permissions:

tccutil reset Reminders

Reset Photos Permissions:

tccutil reset Photos

Reset Calendar Permissions:

tccutil reset Calendar

Reset Full Disk Access Permissions:

tccutil reset SystemPolicyAllFiles

Reset Contacts Permissions:

tccutil reset SystemPolicyAllFiles

Reset Desktop Folder Permissions:

tccutil reset SystemPolicyDesktopFolder

Reset Documents Folder Permissions:

tccutil reset SystemPolicyDocumentsFolder

Reset Downloads Permissions:

tccutil reset SystemPolicyDownloadsFolder

Reset All App Permissions:

tccutil reset All

Clear CUPS Printer Job Cache:

sudo rm -rfv /var/spool/cups/c0*
sudo rm -rfv /var/spool/cups/tmp/*
sudo rm -rfv /var/spool/cups/cache/job.cache*

Empty Trash on All Volumes:

sudo rm -rfv /Volumes/*/.Trashes/* &>/dev/null
sudo rm -rfv ~/.Trash/* &>/dev/null

Clear System Cache Files:

sudo rm -rfv /Library/Caches/* &>/dev/null
sudo rm -rfv /System/Library/Caches/* &>/dev/null
sudo rm -rfv ~/Library/Caches/* &>/dev/null

Clear XCode Derived Data and Archives:

rm -rfv ~/Library/Developer/Xcode/DerivedData/* &>/dev/null
rm -rfv ~/Library/Developer/Xcode/Archives/* &>/dev/null
rm -rfv ~/Library/Developer/Xcode/iOS Device Logs/* &>/dev/null

Clear DNS Cache:

sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

Purge Inactive Memory:

sudo purge

Configure Programs:

Disable Automatically Downloading Parallels Desktop Updates:

defaults write 'com.parallels.Parallels Desktop' 'Application preferences.Download updates automatically' -bool no

Disable Automatically Checking for Parallels Desktop Updates:

defaults write 'com.parallels.Parallels Desktop' 'Application preferences.Check for updates' -int 0

Turn off Ads in Parallels Desktop:

defaults write 'com.parallels.Parallels Desktop' 'ProductPromo.ForcePromoOff' -bool yes
defaults write 'com.parallels.Parallels Desktop' 'WelcomeScreenPromo.PromoOff' -bool yes

Disable Firefox Telemetry:

Enable Firefox policies so the telemetry can be configured.

sudo defaults write /Library/Preferences/org.mozilla.firefox EnterprisePoliciesEnabled -bool TRUE

Disable sending usage data.

sudo defaults write /Library/Preferences/org.mozilla.firefox DisableTelemetry -bool TRUE

Disable Microsoft Office Diagnostics Data Sending:

defaults write com.microsoft.office DiagnosticDataTypePreference -string ZeroDiagnosticData

Uninstall Google Update:

googleUpdateFile=~/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/Resources/ksinstall
if [ -f "$googleUpdateFile" ]; then
    $googleUpdateFile --nuke
    echo Uninstalled google update
else
    echo Google update file does not exist
fi

Disable Homebrew User Behavior Analytics:

command='export HOMEBREW_NO_ANALYTICS=1'
declare -a profile_files=("$HOME/.bash_profile" "$HOME/.zprofile")
for profile_file in "${profile_files[@]}"
do
    touch "$profile_file"
    if ! grep -q "$command" "${profile_file}"; then
        echo "$command" >> "$profile_file"
        echo "[$profile_file] Configured"
    else
        echo "[$profile_file] No need for any action, already configured"
    fi
done

Disable NET Core CLI Telemetry:

command='export DOTNET_CLI_TELEMETRY_OPTOUT=1'
declare -a profile_files=("$HOME/.bash_profile" "$HOME/.zprofile")
for profile_file in "${profile_files[@]}"
do
    touch "$profile_file"
    if ! grep -q "$command" "${profile_file}"; then
        echo "$command" >> "$profile_file"
        echo "[$profile_file] Configured"
    else
        echo "[$profile_file] No need for any action, already configured"
    fi
done

Disable PowerShell Core Telemetry:

command='export POWERSHELL_TELEMETRY_OPTOUT=1'
declare -a profile_files=("$HOME/.bash_profile" "$HOME/.zprofile")
for profile_file in "${profile_files[@]}"
do
    touch "$profile_file"
    if ! grep -q "$command" "${profile_file}"; then
        echo "$command" >> "$profile_file"
        echo "[$profile_file] Configured"
    else
        echo "[$profile_file] No need for any action, already configured"
    fi
done

Configure OS:

Deactivate the Remote Management Service:

sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate -stop

Remove Apple Remote Desktop Settings:

sudo rm -rf /var/db/RemoteManagement
sudo defaults delete /Library/Preferences/com.apple.RemoteDesktop.plist
defaults delete ~/Library/Preferences/com.apple.RemoteDesktop.plist
sudo rm -r /Library/Application\ Support/Apple/Remote\ Desktop/ 
rm -r ~/Library/Application\ Support/Remote\ Desktop/
rm -r ~/Library/Containers/com.apple.RemoteDesktop

Disable "Ask Siri":

defaults write com.apple.assistant.support 'Assistant Enabled' -bool false

Disable Siri Voice Feedback:

defaults write com.apple.assistant.backedup 'Use device speaker for TTS' -int 3

Disable Siri Services (Siri and assistantd):

echo '--- Disable Siri services (Siri and assistantd)'
launchctl disable "user/$UID/com.apple.assistantd"
launchctl disable "gui/$UID/com.apple.assistantd"
sudo launchctl disable 'system/com.apple.assistantd'
launchctl disable "user/$UID/com.apple.Siri.agent"
launchctl disable "gui/$UID/com.apple.Siri.agent"
sudo launchctl disable 'system/com.apple.Siri.agent'
if [ $(/usr/bin/csrutil status | awk '/status/ {print $5}' | sed 's/\.$//') = "enabled" ]; then
    >&2 echo 'This script requires SIP to be disabled. Read more: https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection'
fi

Disable "Do you want to enable Siri?" Pop-up:

defaults write com.apple.SetupAssistant 'DidSeeSiriSetup' -bool True

Hide Siri from Menu Bar:

defaults write com.apple.systemuiserver 'NSStatusItem Visible Siri' 0

Hide Siri from Status Menu:

defaults write com.apple.Siri 'StatusMenuVisible' -bool false
defaults write com.apple.Siri 'UserHasDeclinedEnable' -bool true

Opt-Out from Siri Data Collection:

defaults write com.apple.assistant.support 'Siri Data Sharing Opt-In Status' -int 2

Disable Internet Based Spell Correction:

defaults write NSGlobalDomain WebAutomaticSpellingCorrectionEnabled -bool false

Disable Remote Apple Events:

sudo systemsetup -setremoteappleevents off

Do Not Store Documents to iCloud Drive by Default:

defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false

Do Not Show Recent Items on Dock:

defaults write com.apple.dock show-recents -bool false

Disable AirDrop File Sharing:

defaults write com.apple.NetworkBrowser DisableAirDrop -bool true

Disable Spotlight Indexing:

sudo mdutil -i off -d 

Disable Personalized Advertisements and Identifier Collection:

defaults write com.apple.AdLib allowIdentifierForAdvertising -bool false
defaults write com.apple.AdLib allowApplePersonalizedAdvertising -bool false
defaults write com.apple.AdLib forceLimitAdTracking -bool true

Security Improvements:

Prevent Automatically Allowing Incoming Connections to Signed Apps:

sudo defaults write /Library/Preferences/com.apple.alf allowsignedenabled -bool false

Prevent Automatically Allowing Incoming Connections to Downloaded Signed Apps:

sudo defaults write /Library/Preferences/com.apple.alf allowdownloadsignedenabled -bool false

Enable Application Firewall:

/usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
sudo defaults write /Library/Preferences/com.apple.alf globalstate -bool true
defaults write com.apple.security.firewall EnableFirewall -bool true

Turn on Firewall Logging:

/usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on
sudo defaults write /Library/Preferences/com.apple.alf loggingenabled -bool true

Turn on Stealth Mode:

/usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on
sudo defaults write /Library/Preferences/com.apple.alf stealthenabled -bool true
defaults write com.apple.security.firewall EnableStealthMode -bool true

Require a Password to Wake the Computer from Sleep or Screen Saver:

sudo defaults write /Library/Preferences/com.apple.screensaver askForPassword -bool true

Initiate Session Lock Five Seconds after Screen Saver is Started:

sudo defaults write /Library/Preferences/com.apple.screensaver 'askForPasswordDelay' -int 5

Disables Signing In as Guest from the Login Screen:

sudo defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool NO

Disables Guest Access to File Shares over AF:

sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server AllowGuestAccess -bool NO

Disables Guest Access to File Shares over SMB:

sudo defaults write /Library/Preferences/com.apple.AppleFileServer guestAccess -bool NO

Disable Remote Login (incoming SSH and SFTP connections):

echo 'yes' | sudo systemsetup -setremotelogin off

Disable Insecure TFTP Service:

sudo launchctl disable 'system/com.apple.tftpd'

Disable Bonjour Multicast Advertising:

sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool true

Disable Insecure Telnet Protocol:

sudo launchctl disable system/com.apple.telnetd

Disable Sharing of Local Printers with Other Computers:

cupsctl --no-share-printers

Disable Printing from Any Address including the Internet:

cupsctl --no-remote-any

Disable Remote Printer Administration:

cupsctl --no-remote-admin

Disable Captive Portal:

sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.captive.control.plist Active -bool false

Privacy over Security:

Clear File Quarantine Logs of all Downloaded Files:

db_file=~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2
db_query='delete from LSQuarantineEvent'
if [ -f "$db_file" ]; then
    echo "Database exists at \"$db_file\""
    if ls -lO "$db_file" | grep --silent 'schg'; then
        sudo chflags noschg "$db_file"
        echo "Found and removed system immutable flag"
        has_sytem_immutable_flag=true
    fi
    if ls -lO "$db_file" | grep --silent 'uchg'; then
        sudo chflags nouchg "$db_file"
        echo "Found and removed user immutable flag"
        has_user_immutable_flag=true
    fi
    sqlite3 "$db_file" "$db_query"
    echo "Executed the query \"$db_query\""
    if [ "$has_sytem_immutable_flag" = true ] ; then
        sudo chflags schg "$db_file"
        echo "Added system immutable flag back"
    fi
    if [ "$has_user_immutable_flag" = true ] ; then
        sudo chflags uchg "$db_file"
        echo "Added user immutable flag back"
    fi
else
    echo "No action needed, database does not exist at \"$db_file\""
fi

Clear File Quarantine Attribute from Downloaded Files:

find ~/Downloads        \
        -type f         \
        -exec           \
            sh -c       \
                '
                    attr="com.apple.quarantine"
                    file="{}"
                    if [[ $(xattr "$file") = *$attr* ]]; then
                        if xattr -d "$attr" "$file" 2>/dev/null; then
                            echo "๐Ÿงน Cleaned attribute from \"$file\""
                        else
                            >&2 echo "โŒ Failed to clean attribute from \"$file\""
                        fi
                    else
                        echo "No attribute in \"$file\""
                    fi
                '       \
            {} \;

Prevent Quarantine from Logging Downloaded Files:

file_to_lock=~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2
if [ -f "$file_to_lock" ]; then
    sudo chflags schg "$file_to_lock"
    echo "Made file immutable at \"$file_to_lock\""
else
    echo "No action is needed, file does not exist at \"$file_to_lock\""
fi

Disable Using Extended Quarantine Attribute on Downloaded Files (disables warning):

sudo defaults write com.apple.LaunchServices 'LSQuarantine' -bool NO

Prevent Gatekeeper from Automatically Reactivating Itself:

sudo defaults write /Library/Preferences/com.apple.security GKAutoRearm -bool true

Disable Gatekeeper:

os_major_ver=$(sw_vers -productVersion | awk -F "." '{print $1}')
os_minor_ver=$(sw_vers -productVersion | awk -F "." '{print $2}')
if  [[  $os_major_ver -le 10 \
        || ( $os_major_ver -eq 10 && $os_minor_ver -lt 7 )  \
    ]]; then
    echo "No action needed, Gatekeeper is not available this OS version"
else
    gatekeeper_status="$(spctl --status | awk '/assessments/ {print $2}')"
    if [ $gatekeeper_status = "disabled" ]; then
        echo "No action needed, Gatekeeper is already disabled"
    elif [ $gatekeeper_status = "enabled" ]; then
        sudo spctl --master-disable
        sudo defaults write '/var/db/SystemPolicy-prefs' 'enabled' -string 'no'
        echo "Disabled Gatekeeper"
    else
        >&2 echo "Unknown gatekeeper status: $gatekeeper_status"
    fi
fi

Disable Automatically Checking for Updates:

# For OS X Yosemite and later (>= 10.10)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'AutomaticCheckEnabled' -bool false

Disable Automatically Downloading New Updates when Available:

# For OS X Yosemite and later (>= 10.10)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'AutomaticDownload' -bool false

Disable Automatically Installing macOS Updates:

# For OS X Yosemite through macOS High Sierra (>= 10.10 && < 10.14)
sudo defaults write /Library/Preferences/com.apple.commerce 'AutoUpdateRestartRequired' -bool false
# For Mojave and later (>= 10.14)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'AutomaticallyInstallMacOSUpdates' -bool false

Disable Automatically Updating App from the App Store:

# For OS X Yosemite and later (>= 10.10)
sudo defaults write /Library/Preferences/com.apple.commerce 'AutoUpdate' -bool false
# For Mojave and later (>= 10.14)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'AutomaticallyInstallAppUpdates' -bool false

Disable Installation of macOS Beta Releases:

# For OS X Yosemite and later (>= 10.10)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'AllowPreReleaseInstallation' -bool false

Disable Automatically Installing Configuration Data (e.g. XProtect, Gatekeeper, MRT):

# For OS X Yosemite and later (>= 10.10)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'ConfigDataInstall' -bool false

Disable Automatically Installing System Data Files and Security Updates:

# For OS X Yosemite and later (>= 10.10)
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate 'CriticalUpdateInstall' -bool false

Disable Library Validation Entitlement (checks signature of libraries):

sudo defaults write /Library/Preferences/com.apple.security.libraryvalidation.plist 'DisableLibraryValidation' -bool true

BONUS:

stronghold is the easiest way to securely configure your Mac.

Installation Options

  1. Install with pip

    • pip install stronghold

    • stronghold

Configuration Options

  1. Firewall

    • Turn on Firewall?

      • This helps protect your Mac from being attacked over the internet.

    • Turn on logging?

      • If there IS an infection, logs are useful for determining the source.

    • Turn on stealth mode?

      • Your Mac will not respond to ICMP ping requests or connection attempts from closed TCP and UDP networks.

  2. General System Protection

    • Enable Gatekeeper?

      • Defend against malware by enforcing code signing and verifying downloaded applications before allowing them to run.

    • Prevent automatic software whitelisting?

      • Both built-in and downloaded software will require user approval for whitelisting.

    • Disable Captive Portal Assistant and force login through browser on untrusted networks?

      • Captive Portal Assistant could be triggered and direct you to a malicious site WITHOUT any user interaction.

  3. User Metadata Storage

    • Clear language modeling metadata?

      • This includes user spelling, typing and suggestion data.

    • Disable language modeling data collection?

    • Clear QuickLook metadata?

    • Clear Downloads metadata?

    • Disable metadata collection from Downloads?

    • Clear SiriAnalytics database?

  4. User Safety

    • Lock Mac as soon as screen saver starts?

    • Display all file extensions?

      • This prevents malware from disguising itself as another file type.

    • Disable saving documents to the cloud by default?

      • This prevents sensitive documents from being unintentionally stored on the cloud.

    • Show hidden files in Finder?

      • This lets you see all files on the system without having to use the terminal.

    • Disable printer sharing?

      • Offers redundancy in case the Firewall was not configured.


credit: privacy.sexy and stronghold


If you're enjoying today's newsletter, why not share it with your friends? They might find it just as informative and entertaining as you do.

Sharing is caring, and by spreading the word about this newsletter, you're helping to support ME and ensure that more great content gets produced in the future. Plus, you'll get to have even more conversations with your friends about the interesting topics covered in each edition.

There are three ways to show me that you enjoyed reading this article:

  1. Share this post with your friends


  1. Subscribe to my newsletter


  1. Collect this post (only 100 mints available)


I hope this was helpful!

Thank you for reading!

Letโ€™s bust some more in next article.


If you want more, be sure to

Loading...
highlight
Collect this post to permanently own it.
The BlogChain Newsletter logo
Subscribe to The BlogChain Newsletter and never miss a post.
#macos#privacy#security#terminal#guide
  • Loading comments...