# 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.*

By [The BlogChain Newsletter](https://paragraph.com/@kazani) · 2023-08-14

macos, privacy, security, terminal, guide

---

![](https://storage.googleapis.com/papyrus_images/bc1fe4f91ec552189afc6136ed228eac.png)

**Good Morning!**

**Delivering interesting content every single week on <u>Web3, Security, Crypto, NFTs, Design & AI</u>.**

**It's <u>FREE</u>, Takes less than _<u>5-minutes to read</u>_, and you are guaranteed to learn something.**

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

[Subscribe](https://paragraph.xyz/@kazani/subscribe)

* * *

![](https://storage.googleapis.com/papyrus_images/ba2c219f1813a699e4ce012ae81b5d2b.jpg)

**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.
=========================================================================

<u>Privacy Cleanup</u>:
=======================

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 <u>Google Chrome</u> 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 <u>Google Chrome</u> Cache Files:
---------------------------------------

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

Clear <u>Safari</u> 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 <u>Safari</u> 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 <u>Safari</u> Downloads History:
--------------------------------------

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

Clear <u>Safari</u> Top Sites:
------------------------------

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

Clear <u>Safari</u> Last Session (Open Tabs) History:
-----------------------------------------------------

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

Clear Copy of the <u>Safari</u> History:
----------------------------------------

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

Clear Search History Embedded in <u>Safari</u> Preferences:
-----------------------------------------------------------

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

Clear <u>Safari</u> Cookies:
----------------------------

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

Clear <u>Safari</u> Zoom Level Preferences Per Site:
----------------------------------------------------

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

Clear URLs that are allowed to display notifications in <u>Safari</u>:
----------------------------------------------------------------------

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

Clear <u>Safari</u> Per-Site Preference for Downloads, Geolocation, PopUps and Autoplays:
-----------------------------------------------------------------------------------------

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

Clear <u>Firefox</u> Cache:
---------------------------

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

Delete <u>Firefox</u> Form History:
-----------------------------------

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

Delete <u>Firefox</u> Site Preference:
--------------------------------------

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

Delete <u>Firefox</u> 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 <u>Firefox</u> 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 <u>Firefox</u> HTML5 Cookies:
------------------------------------

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

Delete <u>Firefox</u> Crash Reports:
------------------------------------

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

Delete <u>Firefox</u> Backup Files:
-----------------------------------

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

Delete <u>Firefox</u> 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

* * *

<u>Configure Programs:</u>
==========================

Disable Automatically <u>Downloading</u> Parallels Desktop Updates:
-------------------------------------------------------------------

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

Disable Automatically <u>Checking</u> for Parallels Desktop Updates:
--------------------------------------------------------------------

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

Turn off <u>Ads</u> in Parallels Desktop:
-----------------------------------------

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

Disable <u>Firefox</u> 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 <u>Microsoft Office</u> Diagnostics Data Sending:
---------------------------------------------------------

    defaults write com.microsoft.office DiagnosticDataTypePreference -string ZeroDiagnosticData

Uninstall <u>Google</u> 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 <u>Homebrew</u> 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

* * *

<u>Configure OS:</u>
====================

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 "<u>Ask Siri</u>":
--------------------------

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

Disable <u>Siri</u> Voice Feedback:
-----------------------------------

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

Disable <u>Siri</u> 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 "<u>Do you want to enable Siri</u>?" Pop-up:
----------------------------------------------------

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

Hide <u>Siri</u> from Menu Bar:
-------------------------------

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

Hide <u>Siri</u> from Status Menu:
----------------------------------

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

Opt-Out from <u>Siri</u> 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 <u>iCloud</u> 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 <u>AirDrop</u> File Sharing:
------------------------------------

    defaults write com.apple.NetworkBrowser DisableAirDrop -bool true

Disable <u>Spotlight</u> 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

* * *

<u>Security Improvements:</u>
=============================

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 <u>Downloaded</u> Signed Apps:
-------------------------------------------------------------------------------------

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

Enable Application <u>Firewall</u>:
-----------------------------------

    /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 <u>Password</u> to Wake the Computer from Sleep or Screen Saver:
--------------------------------------------------------------------------

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

Initiate <u>Session Lock</u> Five Seconds after Screen Saver is Started:
------------------------------------------------------------------------

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

Disables Signing In as <u>Guest</u> 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 <u>Local Printers</u> 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

* * *

<u>Privacy over Security:</u>
=============================

Clear File Quarantine <u>Logs</u> 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 <u>Attribute</u> 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 <u>Gatekeeper</u> from Automatically Reactivating Itself:
-----------------------------------------------------------------

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

Disable <u>Gatekeeper</u>:
--------------------------

    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 <u>macOS</u> 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 <u>macOS Beta</u> 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

* * *

<u>BONUS</u>:
=============

`stronghold` is the easiest way to securely configure your Mac.
---------------------------------------------------------------

![](https://storage.googleapis.com/papyrus_images/76f9643df0dd0c735a377e2145efb0ff.gif)

**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](http://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**
    
    [Share](https://paragraph.xyz/@kazani/M19tZdpVX4L2JFUWM2Ln)
    

* * *

2.  **Subscribe to my newsletter**
    
    [Subscribe](https://paragraph.xyz/@kazani/subscribe)
    

* * *

3.  **Collect this post (only 100 mints available)**
    
    [Connect Wallet](https://paragraph.xyz/@kazani/M19tZdpVX4L2JFUWM2Ln)
    
    [Collect](https://paragraph.xyz/@kazani/M19tZdpVX4L2JFUWM2Ln)
    

* * *

**I hope this was helpful!**

**Thank you for reading!**

**Let’s bust some more in next article.**

* * *

**If you want more, be sure to**

[FOLLOW ME](https://owl.link/kazani.btc)

---

*Originally published on [The BlogChain Newsletter](https://paragraph.com/@kazani/enforce-privacy-and-security-best-practices-on-macos-using-terminal)*
