## 1. Project Overview & Quickstart (drduh/macOS-Security-and-Privacy-Guide)

This guide is a collection of techniques for improving the security and privacy of macOS on [Apple silicon](https://support.apple.com/116943) Macs. It targets experienced users who want security practices commonly used by organizations, but is also suitable for novice users with an interest in privacy and security.

For organization-managed Macs, see the [macOS Security Compliance Project](https://github.com/usnistgov/macos_security), maintained by the [U.S. National Institute of Standards and Technology](https://en.wikipedia.org/wiki/National_Institute_of_Standards_and_Technology).

This guide is provided "as is" - without warranties of any kind. You are solely responsible for any consequences of following it.

- [Basics](#basics)
- [Threat modeling](#threat-modeling)
  - [Assets](#assets)
  - [Adversaries](#adversaries)
  - [Capabilities](#capabilities)
  - [Mitigations](#mitigations)
  - [Example model](#example-model)
- [Hardware](#hardware)
- [Installing macOS](#installing-macos)
  - [System activation](#system-activation)
  - [Apple Account](#apple-account)
  - [App Store](#app-store)
  - [Virtualization](#virtualization)
    - [Apple containers](#apple-containers)
- [First boot](#first-boot)
- [Admin and user accounts](#admin-and-user-accounts)
  - [Caveats](#caveats)
  - [Setup](#setup)
- [Firmware](#firmware)
- [FileVault](#filevault)
- [Lockdown Mode](#lockdown-mode)
- [Firewall](#firewall)
  - [Application layer firewall](#application-layer-firewall)
    - [Stealth mode](#stealth-mode)
    - [Signed apps](#signed-apps)
    - [Reload firewall](#reload-firewall)
    - [Get state](#get-state)
    - [AirDrop](#airdrop)
  - [Third-party firewalls](#third-party-firewalls)
  - [Packet filter](#packet-filter)
    - [Example pf config](#example-pf-config)
    - [Firewall commands](#firewall-commands)
    - [Block networks](#block-networks)
- [Services](#services)
- [Siri Suggestions and Spotlight](#siri-suggestions-and-spotlight)
- [Homebrew](#homebrew)
- [DNS](#dns)
  - [DNS profiles](#dns-profiles)
  - [Hosts file](#hosts-file)
  - [DNSCrypt](#dnscrypt)
  - [Dnsmasq](#dnsmasq)
- [Certificate authorities](#certificate-authorities)
- [Privoxy](#privoxy)
- [Browser](#browser)
  - [Firefox](#firefox)
  - [Chrome](#chrome)
  - [Safari](#safari)
  - [Web browser privacy](#web-browser-privacy)
- [Tor](#tor)
- [VPN](#vpn)
- [PGP/GPG](#pgpgpg)
- [Email](#email)
  - [Thunderbird](#thunderbird)
- [Messengers](#messengers)
  - [XMPP](#xmpp)
  - [Signal](#signal)
  - [iMessage](#imessage)
- [Viruses and malware](#viruses-and-malware)
  - [Downloading Software](#downloading-software)
  - [App Sandbox](#app-sandbox)
  - [Hardened Runtime](#hardened-runtime)
  - [Antivirus](#antivirus)
  - [Gatekeeper](#gatekeeper)
- [System Integrity Protection](#system-integrity-protection)
- [Metadata and artifacts](#metadata-and-artifacts)
- [Authentication](#authentication)
- [Backup](#backup)
- [Wi-Fi](#wi-fi)
- [SSH](#ssh)
- [Physical access](#physical-access)
- [Monitoring](#monitoring)
  - [Logs](#logs)
  - [DTrace](#dtrace)
  - [Processes](#processes)
  - [Network](#network)
- [Miscellaneous](#miscellaneous)
- [Related software](#related-software)
- [Additional resources](#additional-resources)

---

# Basics

Apply general security best practices:

- Create a [threat model](#threat-modeling)
  - Is your adversary a local eavesdropper, a criminal using common malware, or a well-funded and highly capable organization?
  - Define the threats or groups you are defending against and what they can realistically do.

- Keep the system and software up to date
  - Regularly install available updates for the operating system and all applications.
  - Updates are installed in [System Settings](https://support.apple.com/guide/mac-help/keep-your-mac-up-to-date-mchlpx1065) or with the [`softwareupdate`](https://ss64.com/mac/softwareupdate.html) command-line utility. Neither requires an Apple Account.
  - Subscribe to the [Apple security-announce](https://lists.apple.com/archives/list/security-announce@lists.apple.com/) mailing list or check [Apple security releases](https://support.apple.com/100100).

- Encrypt sensitive data
  - Enable [FileVault](https://support.apple.com/guide/mac-help/protect-data-on-your-mac-with-filevault-mh11785) to encrypt internal storage.
  - Use a [password manager](https://support.apple.com/105115) for account credentials and consider encrypting especially sensitive files separately.

- Ensure data availability
  - Create [regular backups](https://support.apple.com/104984) of critical data and be ready to [restore from a backup](https://support.apple.com/102551) in case of compromise.
  - [Encrypt backups](https://support.apple.com/guide/mac-help/keep-your-time-machine-backup-disk-secure-mh21241) before copying them to external media or third-party cloud storage. Alternatively, use a backup service that provides [end-to-end encryption](https://support.apple.com/guide/security/advanced-data-protection-for-icloud-sec973254c5f).
  - Verify backups by accessing them on a regular, scheduled basis.

- Click carefully
  - Ultimately, the security of a system depends on the capabilities and habits of its administrator.
  - Take care when installing new software: install it only from sources the developer identifies as official, such as their website or GitHub repository.

# Threat modeling

The most important step to meaningfully improve security and privacy is to create a [threat model](https://owasp.org/www-community/Threat_Modeling): a general description of what you want to protect, who might try to access it, how they could do so, and which controls are worth usability trade-offs. This creates an understanding of potential adversaries and their motivations, which leads to stronger defenses.

## Assets

Assets may include a phone, laptop, credentials, and personal information, such as browsing history.

List them in order of importance, starting with those most worth protecting.

## Adversaries

Define whom you are defending against. Start by defining the motivation each adversary might have to attack important assets. [Financial gain](https://www.verizon.com/business/resources/reports/dbir/) is a big motivator for many attackers, for example.

## Capabilities

For each adversary, list what they can and cannot do, ranking them from least to most capable. For example, a casual thief operates opportunistically: they will likely be defeated by basic controls, such as screen lock and encrypted storage with strong passwords. A more sophisticated and determined adversary may require fully powering off a device when not in use to clear credentials from memory and stronger authentication mechanisms.

## Mitigations

Choose the best mitigation for each threat. For example, avoid writing passwords on paper if a roommate might find them, or encrypt storage to protect its data if it is stolen.

Security should be balanced with usability: every mitigation should counter some adversarial capability to justify any inconvenience. Stop adding defenses when the remaining risks are acceptable for a situation. Revisit the model when devices, data, travel, work, or adversaries change.

## Example model

The following table is an example of a simple threat model:

Adversary | Motivation | Capabilities | Mitigation
:-: | :-: | :-: | :-:
Roommate | See private chats or browsing history | Close proximity; can see screen or observe credentials | Use biometric (fingerprint or face) authentication, use privacy screen, keep phone locked when not using it
Thief | Unlock phone and steal personal info and drain bank accounts, sell phone for money | Observe password being entered, steal logged-in device left unattended | Maintain physical custody of device at all times, lock devices when not in use, avoid typing password in public view, use Find My or similar services to track or remotely disable stolen devices
Criminal | Financial gain | Social engineering (tricking a user into revealing information or taking unsafe actions), readily-available malware, password reuse, exploiting vulnerabilities | Sandbox software, enable OS security features, maintain software updates automatically
Corporation | Marketing based on user data | Telemetry and behavioral data collection | Block network connections, reset device-specific identifiers, avoid adding payment data
Nation State/APT | Targeted surveillance | Passive surveillance of internet infrastructure, advanced encryption analysis | Use open-source software, strong diceware credentials, hardware with secure element, shut down devices when not in use, tripwire/honeypot/[canary tokens](https://canarytokens.org/) alerts

Read more about [threat modeling](https://www.netmeister.org/blog/threat-model-101.html).

# Hardware

[Apple silicon hardware](https://support.apple.com/guide/security/hardware-security-overview-secf020d1074/1/web/1) provide hardware-backed security features, including Secure Enclave-based key protection and stronger boot security options. They are generally the preferred platform for the protections discussed in this guide.

Some Intel-based Macs, especially models with vulnerable [T2-era hardware](https://en.wikipedia.org/wiki/Apple_T2), are affected by hardware vulnerabilities that cannot be fully fixed by a macOS update.

Avoid non-Apple hardware running macOS and systems that do not support the latest macOS release, as Apple does not [patch all vulnerabilities](https://support.apple.com/guide/deployment/about-software-updates-depc4c80847a) in legacy versions.

Apple accessories generally receive firmware updates through macOS and support current [Bluetooth security features](https://support.apple.com/guide/security/bluetooth-security-sec82597d97e/web). For example, [Bluetooth Low Energy](https://en.wikipedia.org/wiki/Bluetooth_Low_Energy) (BLE) Privacy uses rotating device addresses to reduce tracking; third-party accessories may not support this feature.

# Installing macOS

There are several ways to [install macOS](https://support.apple.com/102662).

Install the latest supported version of macOS; newer versions of macOS include security fixes and other improvements not available in previous releases.

## System activation

During installation, Apple silicon Macs contact Apple activation service to confirm that the device is not reported [lost or stolen](https://support.apple.com/102541). Read about [how this process works](https://support.apple.com/guide/security/localpolicy-signing-key-creation-management-sec1f90fbad1).

## Apple Account

An [Apple Account](https://www.apple.com/legal/privacy/data/en/apple-id/) is optional for basic macOS use but required for the App Store and many Apple services. Review [data privacy settings](https://support.apple.com/102651) before enabling features.

Enable [end-to-end encryption](https://support.apple.com/guide/security/advanced-data-protection-for-icloud-sec973254c5f/web) for iCloud and review [Apple Account data](https://support.apple.com/102283).

## App Store

The [App Store](https://en.wikipedia.org/wiki/Mac_app_store) is a software distribution platform where applications are [reviewed](https://developer.apple.com/app-store/review/guidelines) by Apple.

App Store applications are required to use [App Sandbox](https://developer.apple.com/documentation/security/app_sandbox/protecting_user_data_with_app_sandbox) and [Hardened Runtime](https://developer.apple.com/documentation/security/hardened_runtime) (security features restricting what apps can do, making some attacks more difficult). It also offers automatic software updates.

Using the App Store requires an Apple Account, which can pose a privacy risk.

## Virtualization

Virtualization enables another operating system to run in an isolated virtual machine. On [Apple silicon](https://developer.apple.com/documentation/virtualization), macOS can run supported macOS guests and Windows 11 for ARM using apps such as the following:

- [UTM](https://mac.getutm.app/) - Follow the [documentation](https://docs.getutm.app/guest-support/macos) to create macOS and other virtual machines.
- [VirtualBuddy](https://github.com/insidegui/VirtualBuddy) - Application for virtualizing macOS 12+ on Apple silicon.
- [Bushel](https://getbushel.app/) - A lightweight, free app. On first launch, select "Ask App Not to Track".
- [VMware Fusion](https://knowledge.broadcom.com/external/article/315638/download-and-install-vmware-fusion.html) - Now free under Broadcom. Clean UI, easy macOS setup, and supports Windows 11 ARM.
- [tart (CLI)](https://tart.run/) - Command‑line application installed with Homebrew.
- [Parallels](https://www.parallels.com/) - Paid option with strong integration.

> [!WARNING]
> VMware requires a Broadcom account and acceptance of agreements before download.
> Parallels requires an account, payment details, and other data - see the [privacy notice](https://my.parallels.com/data_reminder).

### Apple containers

[Apple Container](https://github.com/apple/container) is a command-line tool for running Linux containers on macOS. Unlike container runtimes that share a single Linux virtual machine, Apple Container runs each container in an isolated, lightweight virtual machine using macOS virtualization capabilities. This provides a stronger isolation boundary between workloads and the host operating system.

# First boot

When macOS starts for the first time, **Setup Assistant** requires the creation of a primary account.

Set a [long and unique password](https://www.eff.org/dice). Leave the password hint field blank.

Avoid personally identifiable names: the computer name (such as "John Appleseed's MacBook") is broadcast over local networks and visible to other devices.

The system name can be configured in **System Settings > About** or with the commands:

```bash
sudo scutil --set ComputerName MacBook
sudo scutil --set HostName MacBook
sudo scutil --set LocalHostName MacBook
```

# Admin and user accounts

The first account created is an administrator account. Administrators can change system-wide settings and run commands with [sudo](https://en.wikipedia.org/wiki/Sudo), which temporarily grants elevated privileges. Any program the administrator runs could obtain the same access; sudo may also have [vulnerabilities](https://bogner.sh/2014/03/another-mac-os-x-sudo-password-bypass/).

It is considered a [best practice](https://help.apple.com/machelp/mac/10.12/index.html#/mh11389) to use a dedicated standard account for regular, daily work and only use the administrator account for software and system installation, configuration and updates.

It is not required to ever log in with the admin account via the macOS login screen. When a Terminal command requires administrator privileges, the system will prompt for authentication and Terminal continues using those privileges. To that end, Apple provides [recommendations](https://support.apple.com/102099) for hiding the admin account and its home directory.

## Caveats

- Only administrators can install applications in the system-wide `/Applications` directory. Finder and Installer ask a standard user to enter an administrator's credentials when approval is required. Some applications can instead be installed in `~/Applications`; applications which do not require admin access should be installed in the user directory. App Store applications are still installed in `/Applications` and require no additional authentication.
- A standard user usually is not authorized to use `sudo`. When administrator privileges are required, macOS prompts for an administrator's credentials, or the task can be run from an administrator account.
- System Settings and several system utilities (e.g., Wi-Fi Diagnostics) require administrator permission for full functionality. Some System Settings need to be unlocked by selecting the lock icon. Some applications will simply prompt for authentication upon opening, others must be opened by an admin account directly to access all functions (e.g., Console).
- Some third-party applications assume the current user is an administrator and will not work from a standard account.
- See [issue 167](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/167) for additional considerations.

## Setup

Accounts be created and managed in System Settings. On existing systems, it is generally easier to create a second admin account and then change the original account from an administrator account to a standard account. Newly-installed systems should instead add a standard account after setup.

Demoting an account can be done from the new admin account in System Settings.

See also [this post](https://superuser.com/a/395738) for more information about how macOS determines group membership.

# Firmware

Verify that firmware security is set to [Full Security](https://support.apple.com/guide/mac-help/mchl768f7291/mac) to prevent tampering with the system. This is the default setting.

# FileVault

Apple silicon Macs use hardware-backed storage encryption by default. [FileVault](https://support.apple.com/guide/mac-help/protect-data-on-your-mac-with-filevault-mh11785/mac) additionally requires an authorized user's password to unlock the startup volume after restart.

On Apple silicon, FileVault authorization also protects the [firmware](https://support.apple.com/102384), which prevents booting from anything other than the designated startup disk, accessing [Recovery](https://support.apple.com/guide/mac-help/macos-recovery-a-mac-apple-silicon-mchl82829c17/15.0/mac/15.0#mchl5abfbb29), and [reviving](https://support.apple.com/108900) it with device firmware update (DFU) mode.

FileVault will prompt to set a recovery key, which should be stored in a safe location if used. FileVault also offers an option to use iCloud for recovery.

Confirm FileVault state:

```bash
fdesetup status
```

# Lockdown Mode

[Lockdown Mode](https://support.apple.com/105120) significantly reduces attack surface by disabling system and application features commonly exploited in sophisticated attacks.

When Lockdown Mode is enabled, Safari has an option to [exclude trusted websites](https://ssd.eff.org/module/how-to-enable-lockdown-mode-on-iphone) from restrictions.

# Firewall

There are several types of firewalls available for macOS.

> [!NOTE]
> If malware gains administrator control, it may disable or bypass firewall policies; do not rely on a local firewall as strong protection against a full system compromise.

## Application layer firewall

The built-in firewall provides basic protection and blocks incoming connections only. It can neither monitor nor block outgoing connections.

It can be controlled by the **Firewall** tab of **Network** in **System Settings**, or with the following commands.

Attackers frequently scan networks to identify systems to target. When [stealth mode](https://support.apple.com/guide/mac-help/use-stealth-mode-to-keep-your-mac-more-secure-mh17133/mac) is enabled, responses are not sent to connection attempts from closed ports, making the system more difficult to detect.

### Stealth mode

Enable the firewall and stealth mode:

```bash
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on
```

### Signed apps

By default, the firewall allows incoming connections for software signed by Apple or by an identified developer. Disabling these rules makes macOS ask before allowing an application to accept incoming connections:

```bash
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off
```

### Reload firewall

After changing settings with `socketfilterfw`, reload the firewall service to apply the new configuration:

```bash
sudo pkill -HUP socketfilterfw
```

### Get state

Confirm firewall state:

```console
for firewallFlag in \
  --getglobalstate \
  --getblockall \
  --getallowsigned \
  --getstealthmode \
  --listapps
do /usr/libexec/ApplicationFirewall/socketfilterfw "$firewallFlag"
done
```

### AirDrop

Enabling the application layer firewall and disabling incoming connections for built-in software prevents [AirDrop](https://support.apple.com/119857) from functioning correctly. For AirDrop to work, both `sharingd` and `rapportd` require firewall exceptions:

```bash
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /usr/libexec/sharingd
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp /usr/libexec/sharingd
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /usr/libexec/rapportd
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp /usr/libexec/rapportd
```

## Third-party firewalls

Applications such as [Little Snitch](https://www.obdev.at/products/littlesnitch/index.html), [Radio Silence](https://radiosilenceapp.com/), and [LuLu](https://objective-see.com/products/lulu.html) provide a balance between usability and security.

These programs are capable of monitoring and blocking both incoming and outgoing connections. However, they may require a closed-source [system extension](https://support.apple.com/HT210999).

If frequent allow-or-block prompts are overwhelming, temporarily allow connections while also recording them ([Silent Allow mode](https://help.obdev.at/littlesnitch6/concepts-opmodes) in Little Snitch). Review the configuration to understand and control network activity.

## Packet filter

macOS also includes [pf](https://en.wikipedia.org/wiki/PF_(firewall)), a packet-filtering firewall configured from the command line. It is powerful but considerably more complex than the built-in application firewall.

pf can also be controlled with a graphical application such as [Murus](https://www.murusfirewall.com/).

Many [books](https://nostarch.com/book-of-pf-4e) and [guides](https://www.openbsd.org/faq/pf/) cover the pf firewall. The following example shows how to configure a basic policy.

### Example pf config

Add the following rules to a file named `pf.rules`:

```console
# Define interface
wifi = "en0"

# Global options
set block-policy drop
set skip on lo0
set state-policy if-bound
set ruleset-optimization basic
scrub in on $wifi all fragment reassemble

# Define tables
table  persist

# Default deny both directions and log
block log all
block quick from no-route to any
antispoof quick for $wifi

# Blocklist enforcement
block log quick on $wifi from {  } to any
block log quick on $wifi from any to {  }

# DHCP
pass out on $wifi proto udp from any port 68 to any port 67 keep state
pass in  on $wifi proto udp from any port 67 to any port 68 keep state

# Outbound TCP
pass out on $wifi proto tcp from ($wifi) to any flags S/SA keep state

# Outbound UDP
pass out on $wifi proto udp from ($wifi) to any keep state

# Outbound ICMP (ping)
pass out on $wifi proto icmp from ($wifi) to any keep state
```

### Firewall commands

To control the firewall:

Command | Task
-: | :-
`sudo pfctl -e -f pf.rules` | enable firewall with configuration file
`sudo pfctl -t blocklist -T add 1.2.3.4` | add an address to the blocklist
`sudo pfctl -d` | disable firewall

To monitor the firewall:

Command | Task
-: | :-
`sudo pfctl -t blocklist -T show` | show blocklist
`sudo pfctl -sr` | show active rules
`sudo pfctl -ss` | show state table
`sudo ifconfig pflog0 create` | create packet log interface
`sudo tcpdump -ni pflog0` | monitor blocked packets

### Block networks

pf can block ranges of network addresses, for example to an entire organization. Query [Merit RADb](https://www.radb.net/) for the list of networks in use by an [autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (a large network operated by a single organization), such as [Facebook](https://ipinfo.io/AS32934):

```bash
whois -h whois.radb.net '!gAS32934'
```

Copy and paste the list of networks returned into the blocklist command:

```bash
sudo pfctl -t blocklist -T add 31.13.24.0/21 31.13.64.0/24 157.240.0.0/16
```

Confirm the addresses were added:

```console
$ sudo pfctl -t blocklist -T show
No ALTQ support in kernel
ALTQ related functions disabled
   31.13.24.0/21
   31.13.64.0/24
   157.240.0.0/16
```

Confirm network traffic is blocked to those addresses (DNS requests will still work):

```console
$ dig a +short facebook.com
157.240.2.35

$ curl --connect-timeout 5 -I https://facebook.com/
*   Trying 157.240.2.35...
* TCP_NODELAY set
* Connection timed out after 5002 milliseconds
* Closing connection 0
curl: (28) Connection timed out after 5002 milliseconds

$ sudo tcpdump -tqni pflog0 'host 157.240.2.35'
IP 192.168.1.1.62771 > 157.240.2.35.443: tcp 0
IP 192.168.1.1.62771 > 157.240.2.35.443: tcp 0
IP 192.168.1.1.62771 > 157.240.2.35.443: tcp 0
```

The firewall drops the initial packets needed to start the [TCP connection](https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment), so the connection times out.

See [drduh/config/scripts/pf-blocklist.sh](https://github.com/drduh/config/blob/main/scripts/pf-blocklist.sh) for more inspiration.

# Services

Many system and user background services are managed by [launchd](https://en.wikipedia.org/wiki/Launchd).

Administrator accounts can modify services and extensions in [System Settings](https://support.apple.com/guide/mac-help/change-login-items-settings-mtusr003).

Command | Task
-: | :-
`launchctl list` | view user jobs
`sudo launchctl list` | view system jobs
`launchctl list com.apple.Finder` | examine a service
`systemextensionsctl list` | list system extensions
`ls /System/Library/LaunchDaemons` | list system daemons
`ls /System/Library/LaunchAgents` | list system agents

To read a service configuration:

```bash
defaults read /System/Library/LaunchAgents/com.apple.Finder
```

> [!IMPORTANT]
> System services are protected by [SIP](https://github.com/drduh/macOS-Security-and-Privacy-Guide#system-integrity-protection); disabling SIP to modify system services can compromise security and cause system instability.

To view the status of services:

```bash
find /var/db/com.apple.xpc.launchd \
  -type f -print -exec defaults read {} \; 2>/dev/null
```

See [script management with launchd](https://support.apple.com/guide/terminal/script-management-with-launchd-apdc6c1077b-5d5d-4d35-9c19-60f2397b2369) and [launchd.info](https://launchd.info/) for more information.

# Siri Suggestions and Spotlight

Siri Suggestions and Spotlight may send some queries or usage information to Apple, depending on the enabled features. In System Settings, search for Siri and Spotlight, then disable online suggestions and configure categories to exclude from indexing or suggestion. Review Apple's [Search & Privacy](https://www.apple.com/legal/privacy/data/en/siri-suggestions-search/) policy for more information.

# Homebrew

If a program is not available through the App Store, consider using [Homebrew](https://brew.sh/).

> [!IMPORTANT]
> Some Homebrew installation or management workflows may prompt for App Management or [Full Disk Access](https://eclecticlight.co/2025/11/08/explainer-permissions-privacy-and-tcc/). Grant these permissions only when they are fully understood and necessary.

Periodically run `brew upgrade` on trusted and secure networks to install software updates. To get information on a package before installation, run `brew info ` and review its formula online. Enable [additional security options](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/138), such as `HOMEBREW_NO_INSECURE_REDIRECT=1`

According to [Homebrew's Anonymous Analytics](https://docs.brew.sh/Analytics), Homebrew collects anonymous usage analytics and reports them to a self-hosted [InfluxDB](https://en.wikipedia.org/wiki/InfluxDB) instance.

To opt out of Homebrew analytics, run `brew analytics off` or set `HOMEBREW_NO_ANALYTICS=1` in the shell startup file.

# DNS

## DNS profiles

macOS features "DNS configuration profiles" for configuring encrypted DNS, filtering, and [DNSSEC](https://en.wikipedia.org/wiki/Domain_Name_System_Security_Extensions).

DNS profiles can be [created](https://dns.notjakob.com/) or obtained from providers such as [Quad9](https://docs.quad9.net/Setup_Guides/MacOS/Big_Sur_and_later_(Encrypted)/#download-profile), [AdGuard](https://adguard-dns.io/en/public-dns.html) and [NextDNS](https://nextdns.io/).

## Hosts file

Use the [hosts file](https://en.wikipedia.org/wiki/Hosts_(file)) to block domains associated with malware, advertising, and other unwanted services.

To block a domain by [A record](https://en.wikipedia.org/wiki/List_of_DNS_record_types), append any one of the following lines to `/etc/hosts`:

```
0 example.com
0.0.0.0 example.com
127.0.0.1 example.com
```

> [!NOTE]
> IPv6 uses AAAA records rather than A records: block IPv6 connections by including `::1 example.com` entries.

Many domain lists are available online. Before appending one to `/etc/hosts`, ensure each entry begins with `0`, `0.0.0.0`, or `127.0.0.1`, and retain the `127.0.0.1 localhost` entry.

Popular hosts lists include:
- [StevenBlack/hosts](https://github.com/StevenBlack/hosts)
- [Sinfonietta/hostfiles](https://github.com/Sinfonietta/hostfiles)
- [someonewhocares.org](https://someonewhocares.org/hosts/zero/hosts)

To download and append a list to the hosts file, use the [tee](https://man7.org/linux/man-pages/man1/tee.1.html) command:

```bash
curl https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts |
  sudo tee -a /etc/hosts
```

[Little Snitch](#third-party-firewalls) also supports [blocklists](https://help.obdev.at/littlesnitch6/lsc-blocklists).

## DNSCrypt

To encrypt DNS traffic, consider [DNSCrypt/dnscrypt-proxy](https://github.com/DNSCrypt/dnscrypt-proxy). When configured with a trusted resolver, DNSCrypt encrypts DNS queries. DNSSEC can additionally validate signed DNS responses where supported.

Install DNSCrypt from Homebrew and follow the instructions to configure and start `dnscrypt-proxy`:

```bash
brew install dnscrypt-proxy
```

When using DNSCrypt with Dnsmasq, locate the DNSCrypt configuration file by running:

```bash
brew info dnscrypt-proxy
```

This command should display a path such as `/usr/local/etc/dnscrypt-proxy.toml`.

By default, dnscrypt-proxy listens on `127.0.0.1:53` and sends queries to one or more configured DNS providers. Modify the configuration and change `listen_addresses` to use a port other than 53, such as 5355:

```toml
listen_addresses = ['127.0.0.1:5355', '[::1]:5355']
```

Start DNSCrypt:

```bash
sudo brew services restart dnscrypt-proxy
```

Confirm DNSCrypt is running:

```console
$ sudo lsof +c 15 -Pni UDP:5355
COMMAND          PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
dnscrypt-proxy 15244 nobody    7u  IPv4 0x1337f85ff9f8beef      0t0  UDP 127.0.0.1:5355
dnscrypt-proxy 15244 nobody   10u  IPv6 0x1337f85ff9f8beef      0t0  UDP [::1]:5355
dnscrypt-proxy 15244 nobody   12u  IPv4 0x1337f85ff9f8beef      0t0  UDP 127.0.0.1:5355
dnscrypt-proxy 15244 nobody   14u  IPv6 0x1337f85ff9f8beef      0t0  UDP [::1]:5355
```

Additionally, these pf rules block conventional DNS traffic to port 53 outside the loopback interface, to reduce the risk of [DNS leaks](https://dnsleaktest.com/):

```console
block drop quick on !lo0 proto udp from any to any port = 53
block drop quick on !lo0 proto tcp from any to any port = 53
```

## Dnsmasq

[dnsmasq](https://thekelleys.org.uk/dnsmasq/doc.html) can cache replies, prevent upstream queries for unqualified names, and block entire top-level domains.

Use it in combination with DNSCrypt to encrypt DNS traffic.

If you do not use DNSCrypt, at minimum choose a DNS resolver other than the one provided by the ISP. Two popular alternatives are [Google DNS](https://developers.google.com/speed/public-dns/) and [OpenDNS](https://www.opendns.com/home-internet-security/).

Install Dnsmasq:

```bash
brew install dnsmasq
```

Download and edit [drduh/config/dnsmasq.conf](https://github.com/drduh/config/blob/main/dnsmasq.conf) or the default configuration file.

See [drduh/config/domains](https://github.com/drduh/config/tree/main/domains) for example domain lists that can be added to block specific destinations.

Install and start the program (sudo is required to bind to [privileged port](https://unix.stackexchange.com/questions/16564/why-are-the-first-1024-ports-restricted-to-the-root-user-only) 53):

```bash
sudo brew services start dnsmasq
```

To set dnsmasq as the local DNS server, open **System Settings** > **Network** and select the network connection currently in use (such as Wi-Fi), then open the **DNS** tab, select **+**, and add `127.0.0.1`, or use:

```bash
sudo networksetup -setdnsservers "Wi-Fi" 127.0.0.1
```

Confirm Dnsmasq is configured:

```console
$ scutil --dns | head
DNS configuration

resolver #1
  search domain[0] : whatever
  nameserver[0] : 127.0.0.1
  flags    : Request A records, Request AAAA records
  reach    : 0x00030002 (Reachable,Local Address,Directly Reachable Address)

$ networksetup -getdnsservers "Wi-Fi"
127.0.0.1
```

> [!NOTE]
> Some VPN applications override DNS settings on connect. See [issue 24](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/24) and [drduh/config/scripts/macos-dns.sh](https://github.com/drduh/config/blob/main/scripts/macos-dns.sh).

# Certificate authorities

macOS includes a set of trusted root certificate authorities (CAs) operated by corporations, governments and other organizations from around the world. A trusted CA can issue certificates that macOS and browsers may accept for HTTPS connections, making the root CA store a critical part of the system's trust boundary.

Inspect **System Roots** to understand the Apple-provided trusted root store using [Keychain Access](https://support.apple.com/guide/keychain-access/welcome/mac) or the [`security`](https://ss64.com/mac/security.html) command-line tool and `/System/Library/Keychains/SystemRootCertificates.keychain` file. Keychain Access can also be launched with the command:

```bash
open "/System/Library/CoreServices/Applications/Keychain Access.app"
```

Also review any certificates that may have been added by a user, administrator, VPN client, security product, or mobile device management application in the **login**, **Local Items**, and **System** keychains.

To disable a selected certificate, modify its Trust setting to **Never Trust** and close the window to confirm. Doing so may reduce the risk of [MITM](https://wikipedia.org/wiki/Man-in-the-middle_attack) attacks, in which a fraudulent certificate is used to [silently intercept](https://en.wikipedia.org/wiki/DigiNotar#Issuance_of_fraudulent_certificates) encrypted traffic.

> [!WARNING]
> Removing or modifying certificate authority trust settings can break websites, software updates, enterprise networks, VPNs, captive portals, and other services.

See Apple's [available trusted certificates](https://support.apple.com/103723) and [blocked certificates](https://support.apple.com/103247#blocked) lists for current trust-store information.

# Privoxy

Consider using [Privoxy](https://www.privoxy.org/) as a local proxy to filter web traffic.

Install and start Privoxy using Homebrew:

```bash
brew install privoxy
brew services start privoxy
```

Alternatively, a signed installation package for Privoxy is available from [their website](https://www.privoxy.org/sf-download-mirror/Macintosh%20%28OS%20X%29/) or [Sourceforge](https://sourceforge.net/projects/ijbswa/files/Macintosh%20%28OS%20X%29/). The signed package is [more secure](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/65) than the Homebrew version and receives support from the Privoxy project.

By default, Privoxy listens on local TCP port 8118.

Set the system **HTTP** proxy for the active network interface to `127.0.0.1` and port `8118`:

```bash
sudo networksetup -setwebproxy "Wi-Fi" 127.0.0.1 8118
```

Set the system **HTTPS** proxy:

```bash
sudo networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 8118
```

The proxy can also be set in **System Settings** > **Network** > **Details** > **Proxies**.

Confirm the proxy is set:

```console
$ scutil --proxy
<dictionary> {
  ExceptionsList : <array> {
    0 : *.local
    1 : 169.254/16
  }
  FTPPassive : 1
  HTTPEnable : 1
  HTTPPort : 8118
  HTTPProxy : 127.0.0.1
}
```

Although most web traffic is encrypted, Privoxy can filter requests by hostname. For example, the following rules block all traffic except traffic to .net, github.com, and Apple domains:

```console
{ +block{all} }
.

{ -block }
.apple.
.github.com
.net
```

To block Facebook domains:

```console
{ +block{facebook} }
.cdninstagram.
.facebook*.
.fb.
.fbcdn*.
.fbinfra.
.fbsbx.
.fbstatic*.
.fbsv.
.fburl.
.instagr.am
.tfbnw.
.thefacebook.
fb*.akamaihd.net
```

See [drduh/config/privoxy/config](https://github.com/drduh/config/blob/main/privoxy/config) and [drduh/config/privoxy/user.action](https://github.com/drduh/config/blob/main/privoxy/user.action) for additional Privoxy examples. Privoxy does **not** need to be restarted after editing filter rules.

To verify traffic is blocked or redirected, use [curl](https://en.wikipedia.org/wiki/CURL) or open the Privoxy interface at <http://p.p> in a browser:

```console
$ ALL_PROXY=127.0.0.1:8118 curl example.com -IL | head
HTTP/1.1 403 Request blocked by Privoxy
Content-Length: 9001
Content-Type: text/html
Cache-Control: no-cache
Pragma: no-cache

$ ALL_PROXY=127.0.0.1:8118 curl github.com -IL | head
HTTP/1.1 302 Local Redirect from Privoxy
Location: https://github.com/
Content-Length: 0

HTTP/1.1 200 Connection established

HTTP/2 200
content-type: text/html; charset=utf-8
```

> [!NOTE]
> Applications and services can ignore the proxy settings. pf can redirect traffic through a proxy without configuring each application separately.

# Browser

Web browsers create significant security and privacy risks because they download and execute untrusted Internet content.

A key browser security boundary is the [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy) (SOP), which prevents one website from reading another website's data. A bypass can expose data or actions from other sites in the same browser profile.

Some browser attacks rely on convincing the user to install software, grant permissions, or use a malicious extension. Be especially careful with unexpected downloads, extension prompts, and requests to run commands in Terminal.

Browser extensions also pose a significant security risk: a malicious or poorly-made extension can compromise everything in the browser, including credentials. The use of browser extensions should be limited to critically necessary ones, published by trustworthy developers only.

Use separate browser profiles for different identities and purposes. If practical, disable JavaScript and only allow it on trusted sites using browser site permissions.

[Mozilla Firefox](https://www.firefox.com/), [Google Chrome](https://www.google.com/chrome), [Safari](https://www.apple.com/safari), and [Tor Browser](https://www.torproject.org/download) are popular browsers, each with unique features and individual purposes.

## Firefox

Firefox modernized major parts of its codebase through the [Quantum](https://wiki.mozilla.org/Quantum) and [Photon](https://wiki.mozilla.org/Firefox/Photon/Updates) projects. Quantum includes moving some components from C++ to [Rust](https://rust-lang.org/), a programming language designed to improve memory safety and concurrency safety.

Firefox offers a comparable security model to Chrome, including a [bug bounty program](https://www.mozilla.org/security/bug-bounty/) for responsible disclosure of vulnerabilities. Firefox follows a four-week release cycle.

See [drduh/config/firefox.user.js](https://github.com/drduh/config/blob/main/firefox.user.js) and [arkenfox/user.js](https://github.com/arkenfox/user.js) for recommended configurations. Also see [NoScript](https://noscript.net/), an extension which allows selective script blocking.

Firefox [focuses on user privacy](https://www.mozilla.org/firefox/privacy). It supports [tracking protection](https://developer.mozilla.org/docs/Web/Privacy/Firefox_tracking_protection) in Private Browsing mode. The tracking protection can be enabled for the default account, although it may break the browsing experience on some websites. Firefox in Strict tracking protection mode will [randomize fingerprints](https://support.mozilla.org/kb/firefox-protection-against-fingerprinting) to defend against tracking. Firefox offers separate user [profiles](https://support.mozilla.org/kb/profile-manager-create-remove-switch-firefox-profiles). Browsing can also be delineated with [Multi-Account Containers](https://support.mozilla.org/kb/containers).

Firefox only supports Web Extensions through the [WebExtension API](https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions), which is very similar to Chrome. Submission of Web Extensions in Firefox is free. Web Extensions in Firefox most of the time are open-source, although certain Web Extensions are proprietary.

## Chrome

[Google Chrome](https://www.google.com/chrome/) is based on the open-source [Chromium project](https://www.chromium.org/). Chrome includes some proprietary components, automatic updates, a PDF viewer, media-codec support, crash reporting, and Google account integration. Review Chrome privacy settings and Google privacy policies for more information.

Chrome offers account sync between multiple devices, including credentials; the data is encrypted with the account password.

Chrome has the largest share of global usage and is the preferred target platform for the majority of developers. Major technologies are based on Chrome's open-source components, such as [node.js](https://nodejs.org/) which uses [Chrome's V8](https://developers.google.com/v8) Engine and the [Electron](https://electron.atom.io/) framework, which is based on Chromium and node.js. Chrome's vast user base makes it the most attractive target for threat actors and security researchers. Despite constant attacks, Chrome has retained an impressive security track record over the years. This is not a small feat.

Chrome offers [separate profiles](https://www.chromium.org/user-experience/multi-profiles), [robust sandboxing](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/design/sandbox.md), [frequent updates](https://chromereleases.googleblog.com/), and carries [impressive credentials](https://www.chromium.org/Home/chromium-security/brag-sheet). In addition, Google offers a very lucrative [bounty program](https://bughunters.google.com/about/rules/5745167867576320/chrome-vulnerability-reward-program-rules) for reporting vulnerabilities, along with its own [Project Zero](https://googleprojectzero.blogspot.com/) team. This means that a large number of highly talented and motivated people are constantly auditing and securing Chrome code.

Consider disabling V8 optimization (JavaScript-engine performance features) in browser settings - see [this explanation](https://microsoftedge.github.io/edgevr/posts/Super-Duper-Secure-Mode) for the security trade-offs.

Block trackers with [uBlock Origin Lite](https://chromewebstore.google.com/detail/ublock-origin-lite/ddkjiahejlhfcafbddmgiahcphecmpfh).

Disable [DNS prefetching](https://www.chromium.org/developers/design-documents/dns-prefetching) (see [DNS Prefetching and Its Privacy Implications](https://www.usenix.org/legacy/event/leet10/tech/full_papers/Krishnan.pdf)). Chrome [may attempt](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/350) to resolve DNS using Google's `8.8.8.8` and `8.8.4.4` public nameservers.

See [Chromium Security](https://www.chromium.org/Home/chromium-security) and [Chromium Privacy](https://www.chromium.org/Home/chromium-privacy) for more information. Read [Google's privacy policy](https://policies.google.com/privacy) to understand how personal information is collected and used.

## Safari

[Safari](https://www.apple.com/safari) is Apple's built-in browser and is integrated with macOS, providing battery efficiency improvements on Apple hardware.

Safari has both open-source and proprietary components. Safari is based on the open-source Web Engine [WebKit](https://webkit.org/), which is ubiquitous among the macOS ecosystem. WebKit is used by Apple apps such as Mail, Books, and the App Store. Chrome's [Blink](https://www.chromium.org/blink) engine is a fork of WebKit and both engines share a number of similarities.

Safari supports certain unique features that benefit user security and privacy. [Content blockers](https://webkit.org/blog/3476/content-blockers-first-look) enable the creation of content blocking rules without using JavaScript. This rule based approach greatly improves memory use, security, and privacy. Safari 11 introduced [Intelligent Tracking Prevention](https://webkit.org/blog/7675/intelligent-tracking-prevention), which removes tracking data stored in Safari after a period of non-interaction by the user from the tracker's website. Safari can randomize the browser fingerprint to reduce tracking. Safari does not support certain features such as WebUSB or the Battery API intentionally for security and privacy reasons. Private tabs in Safari have isolated cookies and cache that is destroyed when you close the tab. Safari also support Profiles which are equivalent to Firefox's Multi-Account Containers for separating cookies and browsing. Safari can be made significantly more secure with [lockdown mode](#lockdown-mode), which can be disabled per-site. Read more about [tracking prevention](https://webkit.org/tracking-prevention/) in Safari.

Web Extensions in Safari have an additional option to use native code in Safari's sandbox environment, in addition to Web Extension APIs. Web Extensions in Safari are also distributed through Apple App Store. App Store submission comes with the added benefit of Web Extension code being audited by Apple. On the other hand App Store submission comes at a steep cost. Yearly [developer subscription](https://developer.apple.com/support/compare-memberships) fee costs 100 USD (in contrast to Chrome's 5 USD fee and Firefox's free submission). The high cost is prohibitive for the majority of open-source developers. As a result, Safari has very few extensions to choose from. However, keep the high cost in mind when installing extensions. It is expected that most Web Extensions will have some way of monetizing usage to cover development costs. Avoid Web Extensions without open-source code available for review.

Safari syncs user preferences and passwords with [iCloud Keychain](https://support.apple.com/HT202303). Viewing a saved password requires authentication with the current device account password or another configured authentication method.

Safari implements new web features more slowly than Chrome or Firefox, but security patches are delivered promptly through system updates.

See also [el1t/uBlock-Safari](https://github.com/el1t/uBlock-Safari/wiki/Disable-hyperlink-auditing-beacon) to disable hyperlink auditing beacons.

## Web browser privacy

Websites infer information about the [browser and device](https://developer.mozilla.org/docs/Web/API/Navigator) from settings, fonts, screen size, language, IP address, and browser behavior. This information contributes to [browser fingerprinting](https://en.wikipedia.org/wiki/Device_fingerprint).

For more information about security-conscious browsing and what data is sent by the browser, see [HowTo: Privacy & Security Conscious Browsing](https://gist.github.com/atcuno/3425484ac5cce5298932), [browserleaks.com](https://browserleaks.com/), [Am I Unique?](https://amiunique.org/fingerprint) and [EFF Cover Your Tracks](https://coveryourtracks.eff.org/) resources.

To reduce cross-site tracking, block [third-party cookies](https://en.wikipedia.org/wiki/Third-party_cookies).

Also be aware of [WebRTC](https://en.wikipedia.org/wiki/WebRTC#Concerns), which may reveal local or public (if connected to a VPN) IP address(es). In Firefox and Chrome/Chromium, this feature can be disabled with [uBlock Origin](https://github.com/gorhill/uBlock/wiki/Prevent-WebRTC-from-leaking-local-IP-address). [Lockdown mode](#lockdown-mode) also [disables WebRTC](https://www.sevarg.net/2022/07/20/ios16-lockdown-mode-browser-analysis) in Safari.

# Tor

[Tor](https://en.wikipedia.org/wiki/Tor_(network)) is an anonymity network that can provide additional privacy while browsing. Tor Browser is a modified Firefox-based browser configured to use the Tor network.

Download Tor Browser from [Tor Project](https://www.torproject.org/download/), both `dmg` and `asc` files for [verification](https://support.torproject.org/tor-browser/getting-started/verifying-tor-browser/):

```console
$ cd ~/Downloads

$ file tor-browser-macos-*
tor-browser-macos-15.0.17.dmg:     XZ compressed data, checksum NONE
tor-browser-macos-15.0.17.dmg.asc: PGP signature Signature (old)

$ gpg --verify tor-browser-macos-*.asc
[...]
gpg: Can't check signature: No public key

$ gpg --auto-key-locate nodefault,wkd --locate-keys torbrowser@torproject.org
gpg: key 0x4E2C6E8793298290: public key "Tor Browser Developers (signing key) <torbrowser@torproject.org>" imported
gpg: Total number processed: 1
gpg:               imported: 1
pub   rsa4096/0x4E2C6E8793298290 2014-12-15 [C] [expires: 2027-07-15]
      Key fingerprint = EF6E 286D DA85 EA2A 4BA7  DE68 4E2C 6E87 9329 8290
uid                   [ unknown] Tor Browser Developers (signing key) <torbrowser@torproject.org>
sub   rsa4096/0x157432CF78A65729 2024-07-15 [S] [expires: 2026-10-26]
      Key fingerprint = CAAE 408A EBE2 288E 96FC  5D5E 1574 32CF 78A6 5729

$ gpg --verify tor-browser-macos-*.asc
gpg: assuming signed data in 'tor-browser-macos-15.0.17.dmg'
gpg: Signature made Sun Jun 28 15:35:20 2026 PDT
gpg:                using RSA key CAAE408AEBE2288E96FC5D5E157432CF78A65729
gpg: Good signature from "Tor Browser Developers (signing key) <torbrowser@torproject.org>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: EF6E 286D DA85 EA2A 4BA7  DE68 4E2C 6E87 9329 8290
     Subkey fingerprint: CAAE 408A EBE2 288E 96FC  5D5E 1574 32CF 78A6 5729
```

Make sure `Good signature from "Tor Browser Developers (signing key) <torbrowser@torproject.org>"` appears in the output. The warning is expected, as the key has not been personally verified and added to a trusted keyring.

See [How can I verify Tor Browser's signature?](https://support.torproject.org/tbb/how-to-verify-signature/) for more information.

To finish installing Tor Browser, open the disk image and drag it to the Applications folder, or use the commands:

```bash
hdiutil mount tor-browser-macos-15.0.17.dmg
cp -r /Volumes/Tor\ Browser/Tor\ Browser.app/ ~/Applications/
```

Verify the application was signed by The Tor Project's Apple Developer ID `MADPSAYN6T` using the `spctl -a -v` or `pkgutil --check-signature` commands:

```console
$ spctl -a -vv ~/Applications/Tor\ Browser.app
/Users/user1/Applications/Tor Browser.app: accepted
source=Notarized Developer ID
origin=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)

$ pkgutil --check-signature ~/Applications/Tor\ Browser.app
Package "Tor Browser.app":
   Status: signed by a certificate trusted by macOS
   Certificate Chain:
    1. Developer ID Application: The Tor Project, Inc (MADPSAYN6T)
       Expires: 2028-10-11 17:57:46 +0000
       SHA256 Fingerprint:
           76 3C 89 02 ED CB AD 8E 59 86 1E 93 D3 05 5B 28 F9 04 0C 96 03 8B
           16 28 9F 38 64 ED 53 45 B4 DA
       ------------------------------------------------------------------------
    2. Developer ID Certification Authority
       Expires: 2031-09-17 00:00:00 +0000
       SHA256 Fingerprint:
           F1 6C D3 C5 4C 7F 83 CE A4 BF 1A 3E 6A 08 19 C8 AA A8 E4 A1 52 8F
           D1 44 71 5F 35 06 43 D2 DF 3A
       ------------------------------------------------------------------------
    3. Apple Root CA
       Expires: 2035-02-09 21:40:36 +0000
       SHA256 Fingerprint:
           B0 B1 73 0E CB C7 FF 45 05 14 2C 49 F1 29 5E 6E DA 6B CA ED 7E 2C
           68 C5 BE 91 B5 A1 10 01 F0 24
```

The command `codesign` can also be used to examine an application's code signature:

```console
$ codesign -dvv ~/Applications/Tor\ Browser.app
Executable=/Users/user1/Applications/Tor Browser.app/Contents/MacOS/firefox
Identifier=org.torproject.torbrowser
Format=app bundle with Mach-O universal (x86_64 arm64)
CodeDirectory v=20500 size=805 flags=0x10000(runtime) hashes=14+7 location=embedded
Signature size=9054
Authority=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=Jun 28, 2026 at 14:01:57
Notarization Ticket=stapled
Info.plist entries=27
TeamIdentifier=MADPSAYN6T
Runtime Version=15.5.0
Sealed Resources version=2 rules=13 files=208
Internal requirements count=1 size=188
```

To view full certificate details for a signed application, extract with `codesign` and decode with `openssl`:

```console
$ codesign -d --extract-certificates ~/Applications/Tor\ Browser.app
Executable=/Users/user1/Applications/Tor Browser.app/Contents/MacOS/firefox

$ file codesign*
codesign0: Certificate, Version=3
codesign1: Certificate, Version=3
codesign2: Certificate, Version=3 Certificate, Version=02

$ openssl x509 -inform der -in codesign0 -subject -issuer -startdate -enddate -noout
subject= /UID=MADPSAYN6T/CN=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)/OU=MADPSAYN6T/O=The Tor Project, Inc/C=US
issuer= /CN=Developer ID Certification Authority/OU=G2/O=Apple Inc./C=US
notBefore=Oct 11 17:57:47 2023 GMT
notAfter=Oct 11 17:57:46 2028 GMT

$ openssl x509 -inform der -in codesign0 -fingerprint -noout
SHA256 Fingerprint=76:3C:89:02:ED:CB:AD:8E:59:86:1E:93:D3:05:5B:28:F9:04:0C:96:03:8B:16:28:9F:38:64:ED:53:45:B4:DA
```

Tor Browser can use special connection methods called [pluggable transports](https://support.torproject.org/tor-browser/circumvention/) to make traffic harder to identify or block. This can be done by setting up a [relay](https://support.torproject.org/relays/) or using an existing [bridge](https://bridges.torproject.org/).

The Tor network provides [anonymity](https://www.privateinternetaccess.com/blog/2013/10/how-does-privacy-differ-from-anonymity-and-why-are-both-important/), which is not necessarily the same as privacy. The network does not defend against a global observer capable of traffic analysis and correlation. See also [Seeking Anonymity in an Internet Panopticon](https://bford.info/pub/net/panopticon-cacm.pdf) and [Traffic Correlation on Tor by Realistic Adversaries](https://www.ohmygodel.com/publications/usersrouted-ccs13.pdf).

See [Tor Protocol Specification](https://spec.torproject.org/tor-spec/) for more information.

Also see [Invisible Internet Project (I2P)](https://geti2p.net/en/about/intro) and its [Tor comparison](https://geti2p.net/en/comparison/tor).

# VPN

Choose a VPN provider or self-hosted setup with a documented, modern protocol and well-audited clients. Avoid obsolete protocols such as [PPTP](https://en.wikipedia.org/wiki/Point-to-Point_Tunneling_Protocol#Security) in favor of [OpenVPN](https://en.wikipedia.org/wiki/OpenVPN) or [WireGuard](https://www.wireguard.com/) [on a Linux VM](https://github.com/mrash/Wireguard-macOS-LinuxVM) or via a set of [cross platform tools](https://www.wireguard.com/xplatform/).

Some VPN clients may send traffic over the next available network interface when the connection is interrupted or disconnected. See [scy/8122924](https://gist.github.com/scy/8122924) for an example on how to allow traffic only over VPN.

See guides to set up an [IPsec](https://en.wikipedia.org/wiki/Ipsec) VPN on a virtual machine ([hwdsl2/setup-ipsec-vpn](https://github.com/hwdsl2/setup-ipsec-vpn)) or a Docker container ([hwdsl2/docker-ipsec-vpn-server](https://github.com/hwdsl2/docker-ipsec-vpn-server)).

It may be worthwhile to consider the geographical location of the VPN provider. See further discussion in [issue 114](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/114).

Also see this [technical overview](https://blog.timac.org/2018/0717-macos-vpn-architecture/) of the macOS built-in VPN L2TP/IPsec and [IKEv2](https://en.wikipedia.org/wiki/IKEv2) client.

# PGP/GPG

PGP is a standard for encrypting and signing data, especially email. It can protect message content between correspondents who correctly exchange and verify keys, but it does not protect metadata such as email recipients and subject lines.

GPG (GNU Privacy Guard) is a GPL-licensed, open-source program compliant with the PGP standard. It can verify software signatures and encrypt files [symmetrically](https://en.wikipedia.org/wiki/Symmetric-key_algorithm) or using [public keys](https://en.wikipedia.org/wiki/Public-key_cryptography).

Install GnuPG with Homebrew (`brew install gnupg`) or install [GPG Suite](https://gpgtools.org/).

Download [gpg.conf](https://github.com/drduh/YubiKey-Guide/blob/main/config/gpg.conf) to use recommended settings:

```bash
curl -o ~/.gnupg/gpg.conf \
  https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/config/gpg.conf
```

See [drduh/YubiKey-Guide](https://github.com/drduh/YubiKey-Guide) to generate and manage credentials.

# Email

Email is not designed to provide strong privacy by default: message content may be retained by service providers, copied to recipients' mailboxes, forwarded, or exposed through account compromise. Metadata (including recipient, subject, timestamps, and mail server information) generally remains visible even when message content is encrypted.

## Thunderbird

[Thunderbird](https://www.thunderbird.net/) is a free and open-source email client with standard [IMAP](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol), [POP](https://en.wikipedia.org/wiki/Post_Office_Protocol), [CalDAV](https://en.wikipedia.org/wiki/CalDAV), and [CardDAV](https://en.wikipedia.org/wiki/CardDAV) support. It is a suitable choice for accessing mail and retaining local copies rather than depending exclusively on a provider's remote server.

Thunderbird includes support for [OpenPGP](https://support.mozilla.org/kb/openpgp-thunderbird-howto-and-faq) email encryption, which can protect message content and provide cryptographic [signatures](https://www.gnupg.org/gph/en/manual/x135.html). Always verify public-key fingerprints through an independent channel before relying on a key for sensitive communication.

The [archived messages feature](https://support.mozilla.org/kb/archived-messages) can move messages out of remote mail servers to a **Local Folder**, improving privacy.

# Messengers

## XMPP

[XMPP](https://en.wikipedia.org/wiki/XMPP) is an [open protocol](https://xmpp.org/extensions/) developed by the [IETF](https://www.ietf.org/) that supports cross-platform, federated messaging. There are many [client options](https://xmpp.org/getting-started/). Consider using one of the browser-based clients to take advantage of the browser's sandbox.

Depending on the provider, you might not need anything other than a username and password to set up an account.

XMPP is not end-to-end encrypted (E2EE) by default; use [OMEMO](https://omemo.top/) with a compatible client.

## Signal

[Signal](https://signal.org/) is a popular E2EE messenger whose [double-ratchet](https://signal.org/docs/specifications/doubleratchet/) protocol is used by many other applications including WhatsApp, Google Messages, and Facebook Messenger.

To use the Signal desktop app, Signal must first be installed on a phone.

See EFF's [Signal guide](https://ssd.eff.org/module/how-to-use-signal) for additional guidance.

## iMessage

[iMessage](https://en.wikipedia.org/wiki/IMessage) is Apple's first-party messenger. It requires an [Apple Account](#apple-account) to use.

Enable [Contact Key Verification](https://support.apple.com/118246) and verify contacts.

iMessage can be used with either a [phone number or an email](https://support.apple.com/108758#help).

> [!WARNING]
> By default, iCloud backup is enabled, which stores copies of message encryption keys on [Apple's servers](https://support.apple.com/102651) without E2EE. Either [disable iCloud backup](https://support.apple.com/guide/icloud/view-and-manage-backups-mm122d3ef202/1.0/icloud/1.0) or enable [Advanced Data Protection](https://support.apple.com/guide/security/advanced-data-protection-for-icloud-sec973254c5f) to prevent this. Remind messaging recipients to do the same.

# Viruses and malware

See [Methods of malware persistence on Mac OS X](https://www.virusbtn.com/pdf/conference/vb2014/VB2014-Wardle.pdf) and [Malware Persistence on OS X Yosemite](https://www.rsaconference.com/events/us15/agenda/sessions/1591/malware-persistence-on-os-x-yosemite) to learn how common macOS malware persists.

For examples of advanced macOS malware capabilities, see the [Hacking Team material](https://www.schneier.com/blog/archives/2015/07/hacking_team_is.html). For further analysis, see [root installation for MacOS](https://github.com/hackedteam/vector-macos-root), [support driver for Mac Agent](https://github.com/hackedteam/driver-macos) and [RCS Agent for Mac](https://github.com/hackedteam/core-macos).

Also see [A Brief Analysis of an RCS Implant Installer](https://objective-see.com/blog/blog_0x0D.html) and [reverse.put.as](https://reverse.put.as/2016/02/29/the-italian-morons-are-back-what-are-they-up-to-this-time/).

## Downloading Software

Applications from the App Store or [notarized by Apple](https://support.apple.com/guide/security/app-code-signing-process-sec3ad8e6e53/web) may reduce malware risk, but neither process guarantees safety. Apple performs automated checks on notarized apps, and App Store apps [undergo review](https://developer.apple.com/app-store/review/guidelines/). Otherwise, obtain software from sources identified by the developer as official, and verify the website or command-line download uses HTTPS.

## App Sandbox

Check if a program uses [App Sandbox](https://developer.apple.com/documentation/security/app_sandbox/protecting_user_data_with_app_sandbox):

```bash
codesign -dvvv --entitlements - /path/to/application.app
```

With App Sandbox enabled, output will include:

```console
[Key] com.apple.security.app-sandbox
[Value]
    [Bool] true
```

**Activity Monitor** can also indicate whether it is enabled with the "Sandbox" column displayed:

```bash
defaults write com.apple.ActivityMonitor "UserColumnsPerTab v6.0" \
  -dict-add 0 '(Command, CPUUsage, CPUTime, Threads, IdleWakeUps, Architecture, GPUUsage, GPUTime, PID, UID, Sandbox, restricted)'
```

App Store software is required to use App Sandbox. Applications such as Google Chrome use their own [sandbox](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/design/sandbox.md) and might not use App Sandbox.

> [!NOTE]
> Sandboxing limits an application's default access, but entitlements and user-granted permissions can expand access.

## Hardened Runtime

Check if a program uses the [Hardened Runtime](https://developer.apple.com/documentation/security/hardened_runtime) before running it using the command:

```bash
codesign --display --verbose /path/to/application.app
```

If Hardened Runtime is enabled, `flags=0x10000(runtime)` will appear in output.

**Activity Monitor** has the option to display a "Restricted" column which indicates a program is restricted from injecting code via macOS's [dynamic linker](https://pewpewthespells.com/blog/blocking_code_injection_on_ios_and_os_x.html).

The Hardened Runtime is a prerequisite for notarization of distributed apps.

## Antivirus

To scan files and applications, consider uploading them to [VirusTotal](https://www.virustotal.com/gui/home/upload), keeping in mind this makes them publicly-viewable.

macOS includes built-in antivirus software called [XProtect](https://support.apple.com/guide/security/protecting-against-malware-sec469d47bd8), which runs in the background and updates signatures used to detect malware automatically. If malware is detected, XProtect attempts to remove and quarantine it.

Applications such as [BlockBlock](https://objective-see.com/products/blockblock.html) or [hazcod/maclaunch](https://github.com/hazcod/maclaunch) might help prevent or detect persistent malware.

Antivirus software can help detect common malware, but it may also increase attack surface because it often runs with extensive system privileges. Some products may also send telemetry or samples to the vendor.

See [Sophail: Applied attacks against Antivirus](https://lock.cmpxchg8b.com/sophailv2.pdf), [Analysis and Exploitation of an ESET Vulnerability](https://googleprojectzero.blogspot.ro/2015/06/analysis-and-exploitation-of-eset.html), [Popular Security Software Came Under Relentless NSA and GCHQ Attacks](https://theintercept.com/2015/06/22/nsa-gchq-targeted-kaspersky/), and [How Israel Caught Russian Hackers Scouring the World for U.S. Secrets](https://www.nytimes.com/2017/10/10/technology/kaspersky-lab-israel-russia-hacking.html).

## Gatekeeper

[Gatekeeper](https://support.apple.com/guide/security/gatekeeper-and-runtime-protection-sec5599b66df/web) verifies software notarization and provenance.

Gatekeeper warns when opening an application without notarization. It can be bypassed by selecting the application listed in **System Settings** > **Privacy & Security** after a failed attempt.

# System Integrity Protection

To verify System Integrity Protection is enabled, use the command `csrutil status`, which should return: `System Integrity Protection status: enabled.` Otherwise, [enable SIP](https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection) using [Recovery Mode](https://support.apple.com/102518).

# Metadata and artifacts

macOS attaches metadata ([APFS extended attributes](https://en.wikipedia.org/wiki/Extended_file_attributes#macOS)) to files.

Metadata attributes can be viewed and removed with the `mdls` and `xattr` commands.

Other metadata and artifacts may be found in the directories including, but not limited to, `~/Library/Preferences/`, `~/Library/Containers/<APP>/Data/Library/Preferences`, `/Library/Preferences`, some of which is detailed below.

`~/Library/Preferences/com.apple.sidebarlists.plist` contains historical list of volumes attached. To clear it, use the command `/usr/libexec/PlistBuddy -c "delete :systemitems:VolumesList" ~/Library/Preferences/com.apple.sidebarlists.plist`

`/Library/Preferences/com.apple.Bluetooth.plist` contains Bluetooth metadata, including device history. If Bluetooth is not used, the metadata can be cleared with:

```bash
sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist DeviceCache
sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist IDSPairedDevices
sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist PANDevices
sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist PANInterfaces
sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist SCOAudioDevices
```

`/var/spool/cups` contains the CUPS printer job cache. To clear it, use the commands:

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

To clear the list of iOS devices connected, use:

```bash
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/*
```

Quicklook thumbnail data can be cleared using the `qlmanage -r cache` command, but this writes to the file `resetreason` in the Quicklook directories, and states that the Quicklook cache was manually cleared. Disable the thumbnail cache with `qlmanage -r disablecache`

It can also be cleared by getting the directory names with `getconf DARWIN_USER_CACHE_DIR` and `sudo getconf DARWIN_USER_CACHE_DIR`, then removing them:

```bash
rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/exclusive
rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite
rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-shm
rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-wal
rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/resetreason
rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.data
```

Similarly, for the root user:

```bash
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.fraghandler
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/exclusive
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-shm
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-wal
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/resetreason
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.data
sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.fraghandler
```

Also see ['quicklook' cache may leak encrypted data](https://objective-see.com/blog/blog_0x30.html).

To clear Finder preferences:

```bash
defaults delete ~/Library/Preferences/com.apple.finder.plist FXDesktopVolumePositions
defaults delete ~/Library/Preferences/com.apple.finder.plist FXRecentFolders
defaults delete ~/Library/Preferences/com.apple.finder.plist RecentMoveAndCopyDestinations
defaults delete ~/Library/Preferences/com.apple.finder.plist RecentSearches
defaults delete ~/Library/Preferences/com.apple.finder.plist SGTRecentFileSearches
```

Additional diagnostic files may be found in the following directories - but caution should be taken before removing any, as it may break logging or cause other issues:

```
/var/db/CoreDuet/
/var/db/diagnostics/
/var/db/systemstats/
/var/db/uuidtext/
/var/log/DiagnosticMessages/
```

macOS may collect spelling and language suggestions. To list them and prevent them from being created again, use the commands:

```bash
ls ~/Library/LanguageModeling/ ~/Library/Spelling/ ~/Library/Suggestions/
chmod -R 000 ~/Library/LanguageModeling ~/Library/Spelling ~/Library/Suggestions
chflags -R uchg ~/Library/LanguageModeling ~/Library/Spelling ~/Library/Suggestions
```

QuickLook application support metadata can be cleared and locked with the commands:

```bash
rm -rfv "$HOME/Library/Application Support/Quick Look/*"
chmod -R 000 "$HOME/Library/Application Support/Quick Look"
chflags -R uchg "$HOME/Library/Application Support/Quick Look"
```

> [!WARNING]
> Clearing or locking this directory can break core macOS applications and prevent document-version recovery.

Document revision metadata can be cleared and disabled with the commands:

```bash
sudo rm -rfv /.DocumentRevisions-V100/*
sudo chmod -R 000 /.DocumentRevisions-V100
sudo chflags -R uchg /.DocumentRevisions-V100
```

Saved application state metadata can be listed and locked with the commands:

```bash
ls ~/Library/Saved\ Application\ State/*
ls ~/Library/Containers/<APPNAME>/Data/Library/Saved\ Application\ State
chmod -R 000 ~/Library/Saved\ Application\ State/
chmod -R 000 ~/Library/Containers/<APPNAME>/Data/Library/Saved\ Application\ State
chflags -R uchg ~/Library/Saved\ Application\ State/
chflags -R uchg ~/Library/Containers/<APPNAME>/Data/Library/Saved\ Application\ State
```

Autosave metadata can be listed and locked with the commands:

```bash
ls "$HOME/Library/Containers/<APP>/Data/Library/Autosave Information"
ls "$HOME/Library/Autosave Information"
chmod -R 000 "~/Library/Containers/<APP>/Data/Library/Autosave Information"
chmod -R 000 "~/Library/Autosave Information"
chflags -R uchg "~/Library/Containers/<APP>/Data/Library/Autosave Information"
chflags -R uchg "~/Library/Autosave Information"
```

The Siri analytics database, which is created even if the Siri launch agent is disabled, can be cleared and locked with the commands:

```bash
rm -rfv ~/Library/Assistant/SiriAnalytics.db
chmod -R 000 ~/Library/Assistant/SiriAnalytics.db
chflags -R uchg ~/Library/Assistant/SiriAnalytics.db
```

Media played in QuickTime Player can be found in:

```bash
~/Library/Containers/com.apple.QuickTimePlayerX/Data/Library/Preferences/com.apple.QuickTimePlayerX.plist
```

Additional metadata may exist in the following files:

```bash
~/Library/Containers/com.apple.appstore/Data/Library/Preferences/com.apple.commerce.knownclients.plist
~/Library/Preferences/com.apple.commerce.plist
~/Library/Preferences/com.apple.QuickTimePlayerX.plist
```

# Authentication

The [Passwords](https://support.apple.com/guide/passwords/the-passwords-app-mchl901b1b95/mac) app creates [secure credentials](https://support.apple.com/guide/security/automatic-strong-passwords-secc84c811c4/web). It supports [passkeys](https://fidoalliance.org/passkeys/), which are credentials designed to resist phishing when used with compatible services.

[KeePassXC](https://keepassxc.org/) is an open-source, cross-platform password manager to consider. It supports strong authentication with compatible hardware tokens and a browser extension for entering credentials automatically.

Memorable passwords can be created with [Diceware](https://secure.research.vt.edu/diceware/).

Ensure online accounts have [multi-factor authentication](https://en.wikipedia.org/wiki/Multi-factor_authentication) enabled. Prefer phishing-resistant authentication, such as hardware tokens or passkeys with supported services. Authenticator apps are preferable to SMS codes, but any MFA is better than password-only authentication.

[YubiKey](https://www.yubico.com/products/) is a popular hardware authentication token. It can also store keys for encryption, signing and authentication tasks - see [drduh/YubiKey-Guide](https://github.com/drduh/YubiKey-Guide).

GnuPG can also manage passwords and other encrypted files - see [drduh/Purse](https://github.com/drduh/Purse) and [drduh/pwd.sh](https://github.com/drduh/pwd.sh).

# Backup

Encrypt files locally before backing them up to external media or online services.

Follow the [3-2-1 backup model](https://www.cisa.gov/sites/default/files/publications/data_backup_options.pdf): keep three copies of important data, store them on at least two different types of media, and keep at least one copy in a separate physical location.

## Time Machine

[Time Machine](https://support.apple.com/104984) is the built-in tool for handling backups on macOS. Use an external drive or network storage to create [encrypted](https://support.apple.com/guide/mac-help/keep-your-time-machine-backup-disk-secure-mh21241) backups.

## GnuPG

GnuPG can be used with a password or public key, with the private key stored on [YubiKey](https://github.com/drduh/YubiKey-Guide).

Compress and encrypt a directory using a password:

```bash
tar zcvf - ~/Downloads | gpg -c > ~/Downloads/backup-$(date +%F-%H%M).tar.gz.gpg
```

Decrypt and decompress the directory:

```bash
gpg -o ~/Downloads/decrypted-backup.tar.gz -d ~/Downloads/backup-*.tar.gz.gpg
tar zxvf ~/Downloads/decrypted-backup.tar.gz
```

## Disk Utility

Encrypted volumes can be created using [Disk Utility](https://support.apple.com/guide/disk-utility/toc) or `hdiutil`:

```bash
hdiutil create ~/Downloads/encrypted.dmg -encryption -size 50M -volname "secretStuff"
hdiutil mount ~/Downloads/encrypted.dmg
cp -v ~/Documents/passwords.txt /Volumes/secretStuff
hdiutil eject /Volumes/secretStuff
```

## Other

[Tresorit](https://tresorit.com/) and [restic](https://restic.net/) may also be of interest.

# Wi-Fi

Wi-Fi network names, called SSIDs, and device probe behavior can reveal information about nearby and previously-used networks. [Hidden networks](https://support.apple.com/guide/security/wi-fi-privacy-with-apple-devices-sec31e483abf/web#sec059998a98) do not provide meaningful privacy and can cause devices to actively probe for them.

Set a [private Wi-Fi address](https://support.apple.com/guide/mac-help/use-a-private-wi-fi-address-on-mac-mchlb1cb3eb4/mac) to reduce network tracking.

Set wireless network security to [WPA3](https://en.wikipedia.org/wiki/WPA3#WPA3). Follow [Apple guidance](https://support.apple.com/102766) to set recommended settings for routers and access points.

# SSH

For remote SSH connections, use a unique SSH key protected by a passphrase or a hardware token, verify server host keys, and avoid password-based authentication. See [drduh/config/ssh_config](https://github.com/drduh/config/blob/main/ssh_config) for recommended client options.

An SSH tunnel can securely route traffic through another computer, similar to a VPN. To use Privoxy running on a remote host on port 8118:

```bash
ssh -C -L 5555:127.0.0.1:8118 you@remote-host.tld
sudo networksetup -setwebproxy "Wi-Fi" 127.0.0.1 5555
sudo networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 5555
```

Or to use an SSH connection as a [SOCKS proxy](https://www.mikeash.com/ssh_socks.html):

```bash
ssh -NCD 3000 you@remote-host.tld
```

By default, macOS does not have [Remote Login](https://support.apple.com/guide/mac-help/allow-a-remote-computer-to-access-your-mac-mchlp1066/mac) (SSH server) enabled.

To enable SSH and allow incoming connections, use **System Settings** > **General** > **Sharing** or the command:

```bash
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist
```

Disable password authentication and consider further [hardening](https://stribika.github.io/2015/01/04/secure-secure-shell.html) the SSH server configuration. See [drduh/config/sshd_config](https://github.com/drduh/config/blob/main/sshd_config) for recommended options.

Confirm the SSH server is running:

```bash
sudo lsof -Pni TCP:22
```

# Physical access

Do not leave the computer unattended in unsafe locations. A skilled attacker with unsupervised physical access could install a [hardware keylogger](https://trmm.net/Thunderstrike_31c3) to record keystrokes, including passwords. Using a Mac with a built-in keyboard or a bluetooth keyboard makes this more difficult as many off-the-shelf versions of this attack are designed to be plugged in between a USB keyboard and the computer.

To reduce the consequences of theft while a Mac is in use, consider using [buskill/buskill-app](https://github.com/buskill/buskill-app) or [Lennolium/swiftGuard](https://github.com/Lennolium/swiftGuard).

Consider purchasing a privacy screen/filter for use in public.

[Nail polish](https://trmm.net/Glitter) and tamper-evidence seals can be applied to components to detect tampering.

# Monitoring

## Logs

Monitor system logs with [Console](https://support.apple.com/guide/console/toc) or the `log stream` command.

Print all system logs from the last 5 minutes in classic syslog format:

```bash
log show --last 5m --style syslog
```

Output as JSON array:

```bash
log show --last 5m --style json
```

Output newline-delimited JSON (one JSON object per line); required for [jq](https://jqlang.org/download/):

```bash
log show --last 5m --style ndjson
```

Filter messages by subsystem, for example from `com.apple.SoftwareUpdate`:

```bash
log show --last 1h --style json \
  --predicate 'subsystem == "com.apple.SoftwareUpdate"'
```

Filter messages by content, for example containing `failed`:

```bash
log show --last 1h --predicate 'eventMessage CONTAINS "failed"'
```

Case-insensitive message filtering:

```bash
log show --last 1h --predicate 'eventMessage CONTAINS[c] "error"'
```

Count distinct error messages with jq:

```bash
log show --last 1h --style ndjson \
  --predicate 'eventMessage CONTAINS[c] "error"' |
  jq -r '.eventMessage' | sort | uniq -c | sort -nr | head -100
```

Export logs to an archive, which can be opened with Console:

```bash
log collect --last 1h --output ~/Downloads/logs-$(date +%F-%H%M).logarchive
```

## DTrace

[System Integrity Protection](https://github.com/drduh/macOS-Security-and-Privacy-Guide#system-integrity-protection) interferes with [DTrace](https://en.wikipedia.org/wiki/DTrace) and must be [partially disabled](https://eclecticlight.co/2024/08/21/controlling-system-integrity-protection-using-csrutil-a-reference/) before use.

- `iosnoop` monitors disk I/O
- `opensnoop` monitors file opens
- `execsnoop` monitors processes
- `errinfo` monitors failed system calls
- `dtruss` monitors all system calls

See `man -k dtrace` for more information.

## Processes

List running processes with [Activity Monitor](https://support.apple.com/guide/activity-monitor/toc) or the `ps` command.

## Network

List open network connections:

```bash
sudo lsof -Pni
```

List the contents of various network-related data structures:

```bash
sudo netstat -atln
```

[Wireshark](https://www.wireshark.org/) can be used from the command line with [`tshark`](https://www.wireshark.org/docs/man-pages/tshark.html).

Replace `en0` with the active interface shown by `networksetup -listallhardwareports`.

> [!IMPORTANT]
> Capture traffic only on networks and systems you are authorized to monitor.

Monitor DNS:

```bash
/Applications/Wireshark.app/Contents/MacOS/tshark -i en0 \
  -Y "dns.flags.response == 1" -Tfields \
  -e frame.time_delta \
  -e dns.qry.name \
  -e dns.a \
  -Eseparator=,
```

Monitor HTTP:

```bash
/Applications/Wireshark.app/Contents/MacOS/tshark -i en0 \
  -Y "http.request or http.response" -Tfields \
  -e ip.dst \
  -e http.request.full_uri \
  -e http.request.method \
  -e http.response.code \
  -e http.response.phrase \
  -Eseparator=/s
```

Monitor x509/TLS certificates:

```bash
/Applications/Wireshark.app/Contents/MacOS/tshark -i en0 \
  -Y "ssl.handshake.certificate" -Tfields \
  -e ip.src \
  -e x509sat.uTF8String \
  -e x509sat.printableString \
  -e x509sat.universalString \
  -e x509sat.IA5String \
  -e x509sat.teletexString \
  -Eseparator=/s -Equote=d
```

# Miscellaneous

## Diagnostic data

Disable [Diagnostics & Usage Data](https://support.apple.com/guide/mac-help/share-analytics-information-mac-apple-mh27990).

Disable crash reporter (the dialog which appears after an application crashes and prompts to report the problem to Apple):

```bash
defaults write com.apple.CrashReporter DialogType none
```

## Media player

Use [QuickTime Player](https://en.wikipedia.org/wiki/Quicktime_player), the built-in media application, for playing music and video files. It uses [App Sandbox](https://developer.apple.com/documentation/security/app_sandbox/protecting_user_data_with_app_sandbox), [Hardened Runtime](https://developer.apple.com/documentation/xcode/configuring-the-hardened-runtime), and benefits from the [Signed System Volume](https://support.apple.com/guide/security/signed-system-volume-security-secd698747c9/web) as part of the base system.

## File handlers

Manage [default file handlers](https://support.apple.com/guide/mac-help/choose-an-app-to-open-a-file-on-mac-mh35597) to reduce risk of opening certain file types.

Change the default app for script files so that opening them displays their contents instead of executing them.

In Finder, locate and select any .sh file, right-click on it and select Get Info or press <kbd>Command</kbd> + <kbd>I</kbd>. In the "Open with" section, select TextEdit from the dropdown menu. If it is not listed, select "Other..." and Applications > TextEdit.app. Select "Change All..." and confirm by selecting Continue.

## Screensaver

Set the screen to lock as soon as the screensaver starts:

```bash
defaults write com.apple.screensaver askForPassword -int 1
defaults write com.apple.screensaver askForPasswordDelay -int 0
```

## Finder options

Show hidden files and the Library folder in Finder:

```bash
defaults write com.apple.finder AppleShowAllFiles -bool true
chflags nohidden ~/Library
```

Show all filename extensions:

```bash
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
```

Do not default to saving documents to iCloud:

```bash
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
```

## umask

Set a [custom umask](https://support.apple.com/101914):

```bash
sudo launchctl config user umask 077
```

Reboot, then create a file/directory and verify permissions (macOS default allows 'group/other' read access):

```console
$ ls -ld umask*
drwx------@ 2 user1 staff  64 Jul 26 12:00 umask.dir
-rw-------@ 1 user1 staff  32 Jul 26 12:00 umask.txt
```

## Keyboard entry

Enable [secure keyboard entry](https://support.apple.com/guide/terminal/use-secure-keyboard-entry-trml109) in Terminal (this may interfere with applications such as [TextExpander](https://smilesoftware.com/textexpander/secure-input)).

## Networking

Disable [Bonjour multicast advertisements](https://www.tenable.com/audits/items/CIS_Apple_macOS_10.13_v1.1.0_Level_2.audit:d9dcee7e4d2b8d2ee54f437158992d88) (this also disables AirPlay and AirPrint features):

```bash
sudo defaults write /Library/Preferences/com.apple.mDNSResponder \
  NoMulticastAdvertisements -bool YES
```

[Disable Handoff](https://support.apple.com/guide/mac-help/change-airdrop-handoff-settings-mchl6a407f99) and [Bluetooth](https://support.apple.com/guide/mac-help/turn-bluetooth-on-or-off-blth1008) features.

## Sudoers

macOS comes with this line in `/etc/sudoers`:

```bash
Defaults env_keep += "HOME MAIL"
```

This prevents sudo from changing HOME when privileges are elevated. As a result, programs run with sudo may use configuration files from the invoking user's home directory. Consider removing `HOME` from `env_keep` unless this behavior is specifically required.

To retain the convenience of the root user having a non-root user's home directory, append an export line to `/var/root/.zshrc`, e.g.:

```bash
export HOME=/Users/user1
```

# Related software

Software | Category | Description
:-: | :-: | :-
[lynis](https://github.com/CISOfy/lynis) | Audit scanner | Cross-platform security-auditing tool that checks system configuration and suggests hardening improvements.
[zentral](https://github.com/zentralopensource/zentral) | Monitoring & configuration platform | Fleet-management server for macOS endpoints; collects inventory, events, audits, and osquery results. Best suited to managed environments.
[osquery](https://github.com/osquery/osquery) | Monitoring engine | Exposes operating-system state as SQL tables, enabling repeatable checks of processes, users, launch items, network connections, and more.
[pareto-mac](https://github.com/paretoSecurity/pareto-mac) | Audit scanner | Menu-bar application that checks a Mac against common baseline security recommendations.

# Additional resources

- [iCloud security and privacy overview](https://support.apple.com/102651)
- [EFF Surveillance Self-Defense Guide](https://ssd.eff.org/)
- [beerisgood/macOS_Hardening](https://github.com/beerisgood/macOS_Hardening)
- [Reverse Engineering macOS blog](https://reverse.put.as/)
- [Reverse Engineering Resources](http://samdmarshall.com/re.html)
- [Malwarebytes Blog](https://www.malwarebytes.com/blog)
- [Objective-See's Blog](https://objective-see.com/blog.html)
- [CIS Benchmarks](https://www.cisecurity.org/benchmark/apple_os/)
- [Apple Open Source](https://opensource.apple.com/)
- [iOS, The Future Of macOS, Freedom, Security And Privacy In An Increasingly Hostile Global Environment](https://gist.github.com/iosecure/357e724811fe04167332ef54e736670d)

## 2. Official Technical Reference & Guides (drduh/YubiKey-Guide)

This guide demonstrates how to store credentials on a [YubiKey](https://www.yubico.com/products/identifying-your-yubikey/). The private keys cannot be copied back out of the device; a separate offline "Certify" key is retained only to replace or renew them.

- [Purchase YubiKey](#purchase-yubikey)
- [Prepare setup environment](#prepare-setup-environment)
  - [Download and verify Debian](#download-and-verify-debian)
  - [Create bootable USB device](#create-bootable-usb-drive)
  - [Prepare hardware](#prepare-hardware)
- [Install software](#install-software)
- [Prepare GnuPG](#prepare-gnupg)
  - [Configuration](#configuration)
  - [Identity](#identity)
  - [Key algorithm](#key-algorithm)
  - [Expiration](#expiration)
  - [Passphrase](#passphrase)
- [Create Certify key](#create-certify-key)
- [Create Subkeys](#create-subkeys)
- [Verify keys](#verify-keys)
- [Backup keys](#backup-keys)
- [Export public key](#export-public-key)
- [Configure YubiKey](#configure-yubikey)
  - [Change PIN](#change-pin)
  - [Set attributes](#set-attributes)
- [Transfer Subkeys](#transfer-subkeys)
  - [Signature key](#signature-key)
  - [Encryption key](#encryption-key)
  - [Authentication key](#authentication-key)
- [Verify transfer](#verify-transfer)
- [Finish setup](#finish-setup)
- [Using YubiKey](#using-yubikey)
  - [Encryption](#encryption)
  - [Signature](#signature)
  - [Configure touch](#configure-touch)
  - [SSH](#ssh)
    - [Replace agents](#replace-agents)
    - [Copy public key](#copy-public-key)
    - [Import SSH keys](#import-ssh-keys)
    - [SSH agent forwarding](#ssh-agent-forwarding)
      - [Use ssh-agent](#use-ssh-agent)
      - [Use S.gpg-agent.ssh](#use-sgpg-agentssh)
      - [Chained forwarding](#chained-forwarding)
  - [GitHub](#github)
  - [GnuPG agent forwarding](#gnupg-agent-forwarding)
    - [Legacy distributions](#legacy-distributions)
    - [Chained GnuPG agent forwarding](#chained-gnupg-agent-forwarding)
  - [Using multiple YubiKeys](#using-multiple-yubikeys)
  - [Email](#email)
    - [Thunderbird](#thunderbird)
    - [Mailvelope](#mailvelope)
    - [Mutt](#mutt)
  - [Keyserver](#keyserver)
- [Updating keys](#updating-keys)
  - [Renew Subkeys](#renew-subkeys)
  - [Rotate Subkeys](#rotate-subkeys)
- [Reset YubiKey](#reset-yubikey)
- [Optional hardening](#optional-hardening)
  - [Improving entropy](#improving-entropy)
  - [Enable KDF](#enable-kdf)
  - [Network considerations](#network-considerations)
- [Notes](#notes)
- [Troubleshooting](#troubleshooting)
- [Alternative solutions](#alternative-solutions)
- [Additional resources](#additional-resources)

---

# Purchase YubiKey

Choose a [YubiKey model](https://www.yubico.com/store/compare/) that includes the OpenPGP application. YubiKey Security Key and YubiKey Bio models do not include OpenPGP support and cannot be used with this guide.

Verify the YubiKey at [yubico.com/genuine](https://www.yubico.com/genuine/). Select Verify Device, touch the key when prompted, and allow the site to identify the device model. This can help detect some [supply chain tampering](https://media.defcon.org/DEF%20CON%2025/DEF%20CON%2025%20presentations/DEF%20CON%2025%20-%20r00killah-and-securelyfitz-Secure-Tokin-and-Doobiekeys.pdf).

Have at least two USB drives or microSD cards for storing encrypted offline backups in different physical locations.

# Prepare setup environment

Use a dedicated, hardened environment to generate the keys and backups.

The following environments are ordered from least to most secure for this task:

1. Public, shared or other computer owned by someone else
1. Daily-use personal operating system with unrestricted network access
1. Virtualized system with limited capabilities (using [virt-manager](https://virt-manager.org/), VirtualBox or VMware, for example)
1. Dedicated and hardened [Debian](https://www.debian.org/) or [OpenBSD](https://www.openbsd.org/) installation
1. Ephemeral [Debian Live](https://www.debian.org/CD/live/) or [Tails](https://tails.boum.org/index.en.html) booted without primary storage attached
1. Hardened hardware and firmware (e.g., [Coreboot](https://www.coreboot.org/), [Intel ME removed](https://github.com/corna/me_cleaner))
1. Air-gapped system without network capabilities, preferably ARM-based Raspberry Pi or other architecturally diverse equivalent

Network isolation and dedicated hardware generally provide stronger protection than a daily-use online system. For most people, booting Debian Live from USB on a personal computer is a practical baseline.

## Download and verify Debian

Download the latest Debian Live image and signature files. These commands download the checksum file, its signature, and the current 64-bit XFCE Live ISO:

```bash
imageUrl="https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/"
curl -sfL -O "$imageUrl/SHA512SUMS" -O "$imageUrl/SHA512SUMS.sign"
curl -sfLO "$imageUrl/$(awk '/xfce\.iso$/ {print $NF}' SHA512SUMS)"
```

Download the Debian signing public key:

```bash
gpg --keyserver hkps://keyring.debian.org \
    --recv DF9B9C49EAA9298432589D76DA87E80D6294BE9B
```

If the public key cannot be received, use a different keyserver or DNS server:

```bash
gpg --keyserver hkps://keyserver.ubuntu.com:443 \
    --recv DF9B9C49EAA9298432589D76DA87E80D6294BE9B
```

The Debian Live signing public key is also available for import in [pubkeys](https://github.com/drduh/YubiKey-Guide/tree/main/pubkeys):

```bash
gpg --import pubkeys/debian-DA87E80D6294BE9B.asc
```

Verify the signature:

```bash
gpg --verify SHA512SUMS.sign SHA512SUMS
```

Confirm the fingerprint matches Debian's published fingerprint:

```console
gpg: Good signature from "Debian CD signing key <debian-cd@lists.debian.org>"
```

Verify the image hash matches the signed sums file:

```bash
grep $(sha512sum debian-live-*-amd64-xfce.iso) SHA512SUMS
```

See [Verifying authenticity of Debian CDs](https://www.debian.org/CD/verify) for more information.

## Create bootable USB device

Connect a storage device and identify the device path. This guide uses `/dev/sdc` throughout, but this value may differ on your system.

> [!WARNING]
> The following `dd` commands erase and overwrite the selected device. Check the device path before continuing!

**Linux**

```console
$ sudo dmesg | tail
usb-storage 3-2:1.0: USB Mass Storage device detected
sd 2:0:0:0: [sdc] Attached SCSI removable disk
```

Copy the Debian image to the device:

```bash
sudo dd if=debian-live-*-amd64-xfce.iso of=/dev/sdc bs=4M status=progress ; sync
```

**OpenBSD**

```console
$ dmesg | tail -n2
sd2 at scsibus4 targ 1 lun 0: <TS-RDF5, SD Transcend, TS3A> SCSI4 0/direct removable serial.0000000000000
sd2: 15193MB, 512 bytes/sector, 31116288 sectors

$ doas dd if=debian-live-*-amd64-xfce.iso of=/dev/rsd2c bs=4m
465+1 records in
465+1 records out
1951432704 bytes transferred in 139.125 secs (14026448 bytes/sec)
```

## Prepare hardware

Shut down the computer that will be used to generate keys.

Disconnect internal storage and unnecessary peripherals, such as the wireless card.

# Install software

Boot the computer from the Debian Live USB drive.

Configure networking to install the required software; see [Network considerations](#network-considerations) for optional restrictions.

> [!TIP]
> If the screen locks on Debian Live, unlock with `user` / `live`

Open a terminal and install the required software.

**Debian/Ubuntu**

```bash
sudo apt update
sudo apt -y upgrade
sudo apt -y install \
  wget gnupg2 gnupg-agent dirmngr \
  cryptsetup scdaemon pcscd \
  yubikey-personalization yubikey-manager
```

**OpenBSD**

```bash
doas pkg_add gnupg pcsc-tools
```

**macOS**

Download and install [Homebrew](https://brew.sh/) and the following packages:

```bash
brew install gnupg yubikey-personalization ykman pinentry-mac wget
```

Or using [MacPorts](https://www.macports.org/install.php), install the following packages:

```bash
sudo port install gnupg2 yubikey-manager pinentry wget
```

**NixOS**

Use this repository's purpose-built live ISO instead of Debian Live. Copy the resulting ISO to a USB drive, boot from it, and keep the system offline while generating keys.

```bash
ref=$(git ls-remote https://github.com/drduh/Yubikey-Guide refs/heads/main | awk '{print $1}')
nix build --experimental-features "nix-command flakes" \
  github:drduh/YubiKey-Guide/$ref?dir=nix#nixosConfigurations.yubikeyLive.x86_64-linux.config.system.build.isoImage
```

If you have this repository checked out:

Recommended, but optional: update `nixpkgs` and `drduh/config`:

```bash
nix flake update --commit-lock-file
```

Build the image:

```bash
nix build --experimental-features "nix-command flakes" nix#nixosConfigurations.yubikeyLive.x86_64-linux.config.system.build.isoImage
```

Copy to USB drive:

```bash
sudo cp -v result/iso/yubikeyLive.iso /dev/sdc ; sync
```

Skip steps to create a temporary working directory and a hardened configuration, as they are already part of the image.

Test builds using virtualization tools like QEMU. A virtual machine provides less isolation than a booted live system. To test the image in QEMU with 4 GiB of RAM, two CPUs, and KVM enabled:

```bash
qemu-system-x86_64 -enable-kvm -m 4G -smp 2 \
  -drive readonly=on,media=cdrom,format=raw,file=result/iso/yubikeyLive.iso
```

**Arch Linux**

```bash
sudo pacman -Syu --needed gnupg pcsclite ccid yubikey-personalization
```

**Red Hat Enterprise Linux (RHEL)**

```bash
sudo yum install -y gnupg2 pinentry pcsc-lite pcsc-lite-libs gnupg2-smime
```

**Fedora**

```bash
sudo dnf install --skip-unavailable \
  wget gnupg2 \
  cryptsetup gnupg2-scdaemon pcsc-lite \
  yubikey-personalization-gui yubikey-manager
```

# Prepare GnuPG

Create a temporary directory for [GnuPG configuration](https://www.gnupg.org/documentation/manuals/gnupg/Configuration-Options.html):

```bash
export GNUPGHOME=$(mktemp -d "${TMPDIR:-/tmp}/$(date +%Y.%m.%d)-XXXXXXXX")
printf "\nTemporary directory:\t%s\n\n" "$GNUPGHOME"
```

> [!NOTE]
> This directory is cleared by reboot only when it is stored on a memory-backed filesystem such as [tmpfs](https://en.wikipedia.org/wiki/Tmpfs).
>
> If it is stored on persistent disk, remove it after completing the guide with `rm -rf "$GNUPGHOME"` and then reboot.

## Configuration

Download the recommended [GnuPG configuration](https://github.com/drduh/YubiKey-Guide/blob/main/config/gpg.conf) into the temporary GnuPG directory.

```bash
wget https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/config/gpg.conf \
  -P $GNUPGHOME
```

Review the configuration before using it. It selects modern cryptographic defaults and privacy-oriented options, such as hiding recipient key IDs:

```console
$ grep -v "^#" $GNUPGHOME/gpg.conf
personal-cipher-preferences AES256 AES192 AES
personal-digest-preferences SHA512 SHA384 SHA256
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
cert-digest-algo SHA512
s2k-digest-algo SHA512
s2k-cipher-algo AES256
charset utf-8
no-comments
no-emit-version
no-greeting
keyid-format 0xlong
list-options show-uid-validity
verify-options show-uid-validity
with-fingerprint
require-cross-certification
require-secmem
no-symkey-cache
armor
use-agent
throw-keyids
```

> [!IMPORTANT]
> Networking should be disabled for the remainder of the setup.

## Identity

Create a user ID - the public label attached to the key.

Use a random label if the key does not need to be publicly identified:

```bash
export IDENTITY="yk.$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c 16)"
printf "\nIdentity:\t\t%s\n\n" "$IDENTITY"
```

If email encryption or Git verification use is anticipated, set the Identity label to a name and email address:

```bash
export IDENTITY="YubiKey User <yubikey@example.com>"
```

> [!TIP]
> Use single quotes to wrap double quote characters (`"`):
>
> `export IDENTITY='My Identity (a.k.a. "YubiKey User") <yubikey@example.com>'`

## Key algorithm

Set the key algorithm and size - RSA 4096 is recommended:

```bash
export KEY_TYPE=rsa4096
```

## Expiration

The Certify key is the offline primary key and should not have an expiration date.[^1]

The signing, encryption, and authentication Subkeys will be stored on YubiKey. Assign Subkeys an expiration date so a lost or obsolete YubiKey becomes inoperable after that date. A two-year expiration for Subkeys is recommended, balancing security and usability. Longer expiration durations reduce maintenance frequency.

> [!NOTE]
> After a Subkey expires, GnuPG can still use it to decrypt existing messages, and SSH may still use it for authentication. However, the expired Subkey cannot encrypt new data or create new signatures!

Subkeys are renewed or rotated using the Certify key. See [Updating keys](#updating-keys).

Set Subkeys to expire on a planned date:

```bash
export KEY_EXPIRATION=2028-08-01
```

The expiration date may also be relative, for example set to two years from today:

```bash
export KEY_EXPIRATION=2y
```

## Passphrase

Create a passphrase for the offline Certify key. This passphrase protects the backup copy of the Certify key and is required to manage Subkeys.

A passphrase consisting only of uppercase letters and numbers is recommended: the limited character set makes handwritten storage easier to write and read.

The following commands will generate and print a strong passphrase[^2]:

```bash
export CERTIFY_PASS=$(LC_ALL=C tr -dc "A-Z3-9" < /dev/urandom |
  tr -d "IOUS5" |
  head -c ${PASS_LENGTH:-24} |
  fold -w ${PASS_GROUPSIZE:-4} |
  paste -sd ${PASS_DELIMITER:--} -)
printf "\nCertify passphrase:\t%s\n\n" "$CERTIFY_PASS"
```

To change the passphrase length, delimiter character or group size, export the respective variable(s) prior to running the passphrase generation command, for example:

```bash
export PASS_GROUPSIZE=6
export PASS_DELIMITER=+
export PASS_LENGTH=48
```

Record the Certify key passphrase on durable media and store it separately from the encrypted backup containing the key material, or memorize it.

The included [passphrase.html](https://github.com/drduh/YubiKey-Guide/blob/main/templates/passphrase.html) and [passphrase.txt](https://github.com/drduh/YubiKey-Guide/blob/main/templates/passphrase.txt) templates can assist with accurate transcription.

Save the [html file](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.html), open in a browser to render and print. Mark the corresponding character on sequential rows for each passphrase character. [passphrase.txt](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.txt) can also be printed for use without a browser:

```bash
lp -d Printer-Name passphrase.txt
```

[Diceware](https://secure.research.vt.edu/diceware) is another popular method for creating memorable passphrases.

# Create Certify key

The Certify key is the primary OpenPGP key: it authorizes the signing, encryption, and authentication Subkeys. Keep it offline and use it only in a secure environment to create, renew, revoke, or replace Subkeys.

Generate the Certify key:

```bash
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --passphrase-fd 0 \
      --quick-generate-key "$IDENTITY" "$KEY_TYPE" cert never
```

Set and print `KEY_FP` (the full key fingerprint) and `KEY_ID` (the last 16 characters of the fingerprint - a shorter identifier commonly accepted by GnuPG):

```bash
export KEY_FP=$(gpg -k --with-colons $IDENTITY | awk -F: '/^fpr:/ { print $10; exit }')
export KEY_ID="${KEY_FP: -16}"
printf "\nKey ID/Fingerprint:\t%s\n%s\n\n" "$KEY_ID" "$KEY_FP"
```


Additional identities (optional)

Skip this section unless the OpenPGP key must have [multiple public identities](https://github.com/drduh/YubiKey-Guide/issues/445). Examples include addresses used for different languages or Git providers. Do not add both personal and professional addresses if linking those identities would reduce privacy - use separate YubiKeys instead.

Define a Bash array of additional user IDs. Put each complete user ID in quotes and separate array entries with spaces:

```bash
declare -a additional_uids
additional_uids=("Super Cool YubiKey 2026" "uid 1 ")
```

Add the additional UIDs to the Identity.

```bash
for uid in "${additional_uids[@]}" ; do \
  printf '%s' "$CERTIFY_PASS" |
  gpg --batch --passphrase-fd 0 \
      --pinentry-mode loopback --quick-add-uid "$KEY_FP" "$uid"
done
```

Set UID trust levels to *ultimate*:

```bash
gpg --command-fd 0 --pinentry-mode loopback --edit-key "$KEY_FP" <<EOF
uid *
trust
5
y
save
EOF
```


# Create Subkeys

Generate Signature and Encryption Subkeys:

```bash
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --pinentry-mode loopback --passphrase-fd 0 \
      --quick-add-key "$KEY_FP" "$KEY_TYPE" sign "$KEY_EXPIRATION"
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --pinentry-mode loopback --passphrase-fd 0 \
      --quick-add-key "$KEY_FP" "$KEY_TYPE" encrypt "$KEY_EXPIRATION"
```

Generate the Authentication Subkey:

> [!NOTE]
> Some SSH servers do not accept RSA authentication keys. To use [Ed25519](https://ed25519.cr.yp.to/) instead, run the following command before creating the Authentication Subkey:
>
> `export KEY_TYPE=ed25519`

```bash
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --pinentry-mode loopback --passphrase-fd 0 \
      --quick-add-key "$KEY_FP" "$KEY_TYPE" auth "$KEY_EXPIRATION"
```

# Verify keys

List available secret keys:

```bash
gpg -K
```

The output should display **[C]ertify, [S]ignature, [E]ncryption and [A]uthentication** keys:

```console
sec   rsa4096/0xF0F2CFEB04341FB5 2026-08-01 [C]
      Key fingerprint = 4E2C 1FA3 372C BA96 A06A  C34A F0F2 CFEB 0434 1FB5
uid                   [ultimate] yk.pn8wgfx67khlhext
ssb   rsa4096/0xB3CD10E502E19637 2026-08-01 [S] [expires: 2028-08-01]
ssb   rsa4096/0x30CBE8C4B085B9F7 2026-08-01 [E] [expires: 2028-08-01]
ssb   rsa4096/0xAD9E24E1B8CB9600 2026-08-01 [A] [expires: 2028-08-01]
```

# Backup keys

Export the public key:

```bash
gpg --output $GNUPGHOME/public-$KEY_ID-$(date +%F).asc \
    --armor --export $KEY_ID
```

Export the Certify key:

```bash
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --pinentry-mode loopback --passphrase-fd 0 \
      --output $GNUPGHOME/secret-$KEY_ID-Certify.key \
      --armor --export-secret-keys $KEY_ID
```

Export the Subkeys:

```bash
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --pinentry-mode loopback --passphrase-fd 0 \
      --output $GNUPGHOME/secret-$KEY_ID-Subkeys.key \
      --armor --export-secret-subkeys $KEY_ID
```

> [!IMPORTANT]
> The exported `.key` files contain secret keys. Anyone who obtains these files and the Certify key passphrase can create Subkeys and sign or decrypt data encrypted to those keys.

Create a backup on encrypted storage to be kept offline in a secure and durable location.

Repeat the process several times on multiple portable storage devices, as they may fail over time. As an additional backup measure, [Paperkey](https://www.jabberwocky.com/software/paperkey/) can create a physical copy of key materials for improved durability.

> [!TIP]
> [ext2](https://en.wikipedia.org/wiki/Ext2) file systems (without encryption) can be mounted on Linux and OpenBSD.
> Use [FAT32](https://en.wikipedia.org/wiki/Fat32) or [NTFS](https://en.wikipedia.org/wiki/Ntfs) file systems for macOS and Windows compatibility instead.

> [!WARNING]
> Confirm the destination (`of`) before issuing `dd` commands as they are destructive! This guide uses `/dev/sdc` - this value may be different on your system.

**Linux**

Attach a portable storage device and confirm its label - in this example `/dev/sdc`:

```console
$ sudo dmesg | tail
usb-storage 3-2:1.0: USB Mass Storage device detected
sd 2:0:0:0: [sdc] Attached SCSI removable disk

$ sudo fdisk -l /dev/sdc
Disk /dev/sdc: 14.9 GiB, 15931539456 bytes, 31116288 sectors
```

Clear the first 4 MiB so the operating system does not retain previous partition tables:

```bash
sudo dd if=/dev/zero of=/dev/sdc bs=4M count=1
```

Remove and reconnect the storage device so the operating system reads the cleared partition table before the next command.

Create a new GPT partition table:

```bash
sudo fdisk /dev/sdc <<EOF
g
w
EOF
```

Create a small partition (at least 20 MB, to account for the LUKS header) for storing backups:

```bash
sudo fdisk /dev/sdc <<EOF
n


+20M
w
EOF
```

Use [LUKS](https://dys2p.com/en/2023-05-luks-security.html) to encrypt the backup partition before storing the Certify key on it.

Generate another unique [passphrase](#passphrase) (different from the Certify key passphrase) to protect the encrypted volume:

```bash
export LUKS_PASS=$(LC_ALL=C tr -dc "A-Z3-9" < /dev/urandom |
  tr -d "IOUS5" |
  head -c ${PASS_LENGTH:-24} |
  fold -w ${PASS_GROUPSIZE:-4} |
  paste -sd ${PASS_DELIMITER:--} -)
printf "\nLUKS passphrase:\t%s\n\n" "$LUKS_PASS"
```

This passphrase unlocks the encrypted backup volume, which contains the Certify key. It is needed to renew, rotate, or recover Subkeys. Write the passphrase down or memorize it.

Confirm root privileges are available:

```bash
sudo -v
```

Format the partition:

```bash
printf '%s' "$LUKS_PASS" | sudo cryptsetup -q luksFormat /dev/sdc1
```

Unlock the encrypted partition and create the mapped device:

```bash
printf '%s' "$LUKS_PASS" | sudo cryptsetup -q luksOpen /dev/sdc1 gnupg-secrets
```

Create an ext2 filesystem:

```bash
sudo mkfs.ext2 /dev/mapper/gnupg-secrets -L gnupg-$(date +%F)
```

Mount the filesystem and copy the temporary GnuPG working directory with key materials:

```bash
sudo mkdir -p /mnt/encrypted-storage
sudo mount /dev/mapper/gnupg-secrets /mnt/encrypted-storage
sudo cp -av $GNUPGHOME /mnt/encrypted-storage/
```

Unmount and close the encrypted volume:

```bash
sudo umount /mnt/encrypted-storage
sudo cryptsetup luksClose gnupg-secrets
```

Repeat the process for any additional storage devices (at least two are recommended).

**OpenBSD**

Attach a USB disk and determine its label:

```console
$ dmesg | grep sd.\ at
sd2 at scsibus5 targ 1 lun 0: <TS-RDF5, SD Transcend, TS37> SCSI4 0/direct removable serial.00000000000000000000
```

Print the existing partitions to make sure it's the right device:

```bash
doas disklabel -h sd2
```

Create an `a` partition of FS type `RAID` and size of 25 Megabytes:

```console
$ doas fdisk -giy sd2
Writing MBR at offset 0.
Writing GPT.

$ doas disklabel -E sd2
Label editor (enter '?' for help at any prompt)
sd2> a a
offset: [64]
size: [31101776] 25M
FS type: [4.2BSD] RAID
sd2*> w
sd2> q
No label changes
```

Encrypt with bioctl using a unique [Passphrase](#passphrase):

```console
$ doas bioctl -c C -l sd2a softraid0
New passphrase:
Re-type passphrase:
softraid0: CRYPTO volume attached as sd3
```

Create an `i` partition on the new crypto volume and the filesystem:

```console
$ doas fdisk -giy sd3
Writing MBR at offset 0.
Writing GPT.

$ doas disklabel -E sd3
Label editor (enter '?' for help at any prompt)
sd3> a i
offset: [64]
size: [16001]
FS type: [4.2BSD]
sd3*> w
sd3> q
No label changes.

$ doas newfs sd3i
```

Mount the filesystem and copy the temporary directory with the keyring:

```bash
doas mkdir -p /mnt/encrypted-storage
doas mount /dev/sd3i /mnt/encrypted-storage
doas cp -av $GNUPGHOME /mnt/encrypted-storage
```

Unmount and remove the encrypted volume:

```bash
doas umount /mnt/encrypted-storage
doas bioctl -d sd3
```

See [OpenBSD FAQ#14](https://www.openbsd.org/faq/faq14.html#softraidCrypto) for more information.

# Export public key

> [!IMPORTANT]
> YubiKey stores the transferred private Subkeys. Each computer also needs the public key and its metadata to identify and use them with GnuPG. Without the public key, it is **not** be possible to use GnuPG to decrypt and sign. However, YubiKey can still be used for SSH authentication.

Connect another portable storage device or create a new partition on the existing one.

**Linux**

Using the same `/dev/sdc` device as in the previous step, create a small (at least 20 MB is recommended) partition for storing materials:

```bash
sudo fdisk /dev/sdc <<EOF
n


+20M
w
EOF
```

Create a filesystem and export the public key:

```bash
sudo mkfs.ext2 /dev/sdc2
sudo mkdir -p /mnt/public
sudo mount /dev/sdc2 /mnt/public
gpg --armor --export $KEY_ID | sudo tee /mnt/public/$KEY_ID-$(date +%F).asc
sudo chmod 0444 /mnt/public/*.asc
```

Unmount and remove the storage device:

```bash
sudo umount /mnt/public
```

**OpenBSD**

```console
$ doas disklabel -E sd2
Label editor (enter '?' for help at any prompt)
sd2> a b
offset: [32130]
size: [31069710] 25M
FS type: [swap] 4.2BSD
sd2*> w
sd2> q
No label changes.
```

Create a filesystem and export the public key to it:

```bash
doas newfs sd2b
doas mkdir -p /mnt/public
doas mount /dev/sd2b /mnt/public
gpg --armor --export $KEY_ID | doas tee /mnt/public/$KEY_ID-$(date +%F).asc
```

Unmount and remove the storage device:

```bash
doas umount /mnt/public
```

# Configure YubiKey

Connect YubiKey and confirm its status:

```bash
gpg --card-status
```

If the YubiKey is locked, follow [Reset YubiKey](#reset-yubikey) to permanently delete any existing keys stored on it.

## Change PIN

YubiKey contains several independent [applications](https://developers.yubico.com/). This guide uses the [OpenPGP application](https://developers.yubico.com/PGP/), whose PINs are separate from PINs used by [PIV](https://developers.yubico.com/PIV/), FIDO, and other card features.

Name | Default | Capability
:-: | :-: | -
User PIN | `123456` | routine key operations (decrypt, sign, authenticate)
Admin PIN | `12345678` | manage card settings (reset PIN, change Reset Code, add keys and owner information)
Reset Code | None | reset PIN ([more information](https://forum.yubico.com/viewtopicd01c.html?p=9055#p9055))

The *User PIN* must be at least 6 characters and the *Admin PIN* must be at least 8 characters. A maximum of 127 ASCII characters are allowed. See [Managing PINs](https://www.gnupg.org/howtos/card-howto/en/ch03s02.html) for more information.

YubiKey limits failed PIN attempts, which reduces guessing risk, allowing the User PIN to be short and convenient for regular use.

Generate convenient numeric PINs: an 8-digit Admin PIN and a 6-digit User PIN. These meet the minimum lengths but can be increased:

```bash
PINS=$(LC_ALL=C tr -dc '0-9' < /dev/urandom | head -c 14)
export ADMIN_PIN=${PINS:0:8}
export USER_PIN=${PINS:8:6}
printf "\nAdmin PIN:\t\t%s\nUser  PIN:\t\t%s\n\n" "$ADMIN_PIN" "$USER_PIN"
```

Change the Admin PIN:

```bash
gpg --command-fd 0 --pinentry-mode loopback --change-pin <<EOF
3
12345678
$ADMIN_PIN
$ADMIN_PIN
q
EOF
```

Change the User PIN:

```bash
gpg --command-fd 0 --pinentry-mode loopback --change-pin <<EOF
1
123456
$USER_PIN
$USER_PIN
q
EOF
```

Remove and reinsert YubiKey.

> [!CAUTION]
> Three incorrect *User PIN* entries will cause it to become blocked and must be unblocked with either the *Admin PIN* or *Reset Code*. Three incorrect *Admin PIN* or *Reset Code* entries will destroy data on YubiKey.

Increase PIN limits if the risk of accidental lockout outweighs the increased opportunity for guessing. This command sets five attempts for the User PIN, Reset Code, and Admin PIN:

```bash
ykman openpgp access set-retries 5 5 5 -f -a $ADMIN_PIN
```

## Set attributes

> [!IMPORTANT]
> OpenPGP card metadata is readable without authentication by anyone with physical access to the YubiKey. This includes the card serial number, key fingerprints, public-key data, and other card attributes. Do not store a name, email address, account name, or other personal identifier in Login data, except for deliberate lost-and-found or asset-management purposes.

Set the card Login attribute. The random label generated by the following command is intentionally non-identifying:

```bash
export CARD_ATTR_LOGIN="yk.$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c 16)"
printf "\nLogin attribute:\t%s\n\n" "$CARD_ATTR_LOGIN"
```

Apply the attribute:

```bash
gpg --command-fd 0 --pinentry-mode loopback --edit-card <<EOF
admin
login
$CARD_ATTR_LOGIN
$ADMIN_PIN
quit
EOF
```

Verify the attribute:

```console
$ gpg --card-status | grep Login
Login data .......: yk.3i568zcrib5f
```

[Smart card attributes](https://gnupg.org/howtos/card-howto/en/smartcard-howto-single.html) can also be set with `gpg --edit-card` and `admin` mode. Use `help` to see available options. The [login](https://www.gnupg.org/documentation/manuals/gnupg/gpg_002dcard.html) attribute is [required](https://github.com/drduh/YubiKey-Guide/issues/461) to transfer keys.

# Transfer Subkeys

> [!NOTE]
> After each transfer, GnuPG deletes its usable local copy of the private key and retains only a record that the Subkey is on this YubiKey. The Subkey cannot be copied back from the YubiKey. Confirm that offline backups exist before continuing.

The Certify key passphrase and Admin PIN are required to transfer keys.

## Signature key

Transfer the Signature key:

```bash
gpg --command-fd 0 --pinentry-mode loopback --edit-key $KEY_FP <<EOF
key 1
keytocard
1
$CERTIFY_PASS
$ADMIN_PIN
save
EOF
```

## Encryption key

Repeat the process for the Encryption key:

```bash
gpg --command-fd 0 --pinentry-mode loopback --edit-key $KEY_FP <<EOF
key 2
keytocard
2
$CERTIFY_PASS
$ADMIN_PIN
save
EOF
```

## Authentication key

Repeat the process for the Authentication key:

```bash
gpg --command-fd 0 --pinentry-mode loopback --edit-key $KEY_FP <<EOF
key 3
keytocard
3
$CERTIFY_PASS
$ADMIN_PIN
save
EOF
```

# Verify transfer

Verify Subkeys are on YubiKey:

```bash
gpg -K
```

All three Subkeys should appear as `ssb>` - the `>` indicates the private key is on the smart card:

```console
sec   rsa4096/0xF0F2CFEB04341FB5 2026-08-01 [C]
      Key fingerprint = 4E2C 1FA3 372C BA96 A06A  C34A F0F2 CFEB 0434 1FB5
uid                   [ultimate] yk.pn8wgfx67khlhext
ssb>  rsa4096/0xB3CD10E502E19637 2026-08-01 [S] [expires: 2028-08-01]
ssb>  rsa4096/0x30CBE8C4B085B9F7 2026-08-01 [E] [expires: 2028-08-01]
ssb>  rsa4096/0xAD9E24E1B8CB9600 2026-08-01 [A] [expires: 2028-08-01]
```

# Finish setup

Confirm that each of the following steps was successfully completed:

- [ ] Memorized or recorded the Certify key passphrase and stored it in a secure, durable location separate from the encrypted backup.
  - Run `echo $CERTIFY_PASS` to display it again.
  - Use [`passphrase.html`](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.html) or [`passphrase.txt`](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.txt) to record it.

- [ ] Memorized or recorded the passphrase for the encrypted backup volume and stored it separately from that volume.
  - Run `echo $LUKS_PASS` to display it again.
  - Use [`passphrase.html`](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.html) or [`passphrase.txt`](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.txt) to record it.

- [ ] Saved the Certify key and Subkeys to encrypted portable storage and stored the backups offline.
  - Keep at least two backups.
  - Store the backups in separate physical locations.

- [ ] Exported a copy of the public key to a location that is easy to access later.
  - Use a separate device or a non-encrypted partition.

- [ ] Memorized or recorded the unique User PIN and Admin PIN after changing them from their default values.
  - Run `echo $USER_PIN $ADMIN_PIN` to display them again.
  - Use [`passphrase.html`](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.html) or [`passphrase.txt`](https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/templates/passphrase.txt) to record them.

- [ ] Transferred the Encryption, Signature, and Authentication Subkeys to the YubiKey.
  - Confirm that `gpg -K` shows `ssb>` for all three Subkeys.

- [ ] Cleared the temporary GnuPG working directory by rebooting or by removing it.

# Using YubiKey

Create or inspect the local GnuPG keyring. This command lists public keys and initializes `~/.gnupg` if needed:

```bash
gpg -k
```

Import the [recommended configuration](https://github.com/drduh/YubiKey-Guide/blob/main/config/gpg.conf):

```bash
cd ~/.gnupg
wget https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/config/gpg.conf
```

Set the following option. This avoids the problem where GnuPG will repeatedly prompt for the insertion of an already-inserted YubiKey:

```bash
touch scdaemon.conf
echo "disable-ccid" >>scdaemon.conf
```

Install the required packages:

**Debian/Ubuntu**

```bash
sudo apt update
sudo apt install -y gnupg gnupg-agent scdaemon pcscd
```

**Arch**

```bash
sudo pacman -S --needed gnupg pcsc-tools
sudo systemctl enable --now pcscd.service
```

**macOS**

```bash
brew install gnupg
```

Or using MacPorts

```bash
sudo port install gnupg2 pcsc-tools
```

**OpenBSD**

```bash
doas pkg_add gnupg pcsc-tools
doas rcctl enable pcscd
doas reboot
```

Mount the non-encrypted volume with the public key:

**Debian/Ubuntu**

```bash
sudo mkdir -p /mnt/public
sudo mount /dev/sdc2 /mnt/public
```

**OpenBSD**

```bash
doas mkdir -p /mnt/public
doas mount /dev/sd3i /mnt/public
```

Import the public key:

```bash
gpg --import /mnt/public/public-*.asc
```

Or download the public key from a keyserver:

```bash
gpg --recv $KEY_ID
```

Or with the URL on YubiKey, retrieve the public key:

```bash
printf "fetch" | gpg --command-fd 0 --pinentry-mode loopback --card-edit
```

Determine the key ID:

```bash
gpg -k
export KEY_ID=0xF0F2CFEB04341FB5
```

Assign ultimate trust by typing `trust` and selecting option `5` then `quit`:

```bash
gpg --command-fd 0 --pinentry-mode loopback --edit-key $KEY_ID <<EOF
trust
5
y
save
EOF
```

Remove and reinsert YubiKey.

Verify the status with `gpg --card-status` which will list the available Subkeys:

```console
Reader ...........: Yubico YubiKey FIDO CCID
Application ID ...: D2760001240102010006055532110000
Application type .: OpenPGP
Version ..........: 3.4
Manufacturer .....: Yubico
Serial number ....: 05553211
Name of cardholder: [not set]
Language prefs ...: [not set]
Salutation .......:
URL of public key : [not set]
Login data .......: yk.3i568zcrib5f
Signature PIN ....: not forced
Key attributes ...: rsa4096 rsa4096 rsa4096
Max. PIN lengths .: 127 127 127
PIN retry counter : 3 3 3
Signature counter : 0
KDF setting ......: off
UIF setting ......: Sign=off Decrypt=off Auth=off
Signature key ....: CF5A 305B 808B 7A0F 230D  A064 B3CD 10E5 02E1 9637
      created ....: 2026-08-01 12:00:00
Encryption key....: A5FA A005 5BED 4DC9 889D  38BC 30CB E8C4 B085 B9F7
      created ....: 2026-08-01 12:00:00
Authentication key: 570E 1355 6D01 4C04 8B6D  E2A3 AD9E 24E1 B8CB 9600
      created ....: 2026-08-01 12:00:00
General key info..: sub  rsa4096/0xB3CD10E502E19637 2026-08-01 yk.pn8wgfx67khlhext
sec#  rsa4096/0xF0F2CFEB04341FB5  created: 2026-08-01  expires: never
ssb>  rsa4096/0xB3CD10E502E19637  created: 2026-08-01  expires: 2028-08-01
                                  card-no: 0006 05553211
ssb>  rsa4096/0x30CBE8C4B085B9F7  created: 2026-08-01  expires: 2028-08-01
                                  card-no: 0006 05553211
ssb>  rsa4096/0xAD9E24E1B8CB9600  created: 2026-08-01  expires: 2028-08-01
                                  card-no: 0006 05553211
```

`sec#` indicates the corresponding key is not available (the Certify key is offline).

YubiKey is now ready for use!

## Encryption

Encrypt a message to yourself (useful for storing credentials or protecting backups):

```bash
printf "test message string\n" |
  gpg --encrypt --armor \
      --recipient $KEY_ID --output encrypted.txt
```

Decrypt the message - a prompt for the User PIN will appear:

```bash
gpg --decrypt --armor encrypted.txt
```

To encrypt to multiple recipients/keys, set the preferred key ID last:

```bash
printf "test message string\n" |
  gpg --encrypt --armor \
      --recipient $KEY_ID3 \
      --recipient $KEY_ID2 \
      --recipient $KEY_ID1 \
      --output encrypted.txt
```

Use a [shell function](https://github.com/drduh/config/blob/main/zshrc) to make encrypting files easier:

```bash
secret() {
  local file="${1}"
  local output="${file}.$(date +%s).enc"
  gpg --encrypt --armor --recipient "${KEY_ID}" \
      --output "${output}" -- "${file}" &&
    printf '%s -> %s' "${file}" "${output}"
}

reveal() {
  local file="${1}"
  local output="${file%.[0-9]*.enc}"
  gpg --decrypt --output "${output}" -- "${file}" &&
    printf '%s -> %s' "${file}" "${output}"
}
```

Example output:

```console
$ secret document.pdf
document.pdf -> document.pdf.1780000000.enc

$ reveal document.pdf.1780000000.enc
gpg: encrypted with RSA key, ID 0x0000000000000000
gpg: anonymous recipient; trying secret key 0xF0F2CFEB04341FB5 ...
gpg: okay, we are the anonymous recipient.
document.pdf.1780000000.enc -> document.pdf
```

[drduh/Purse](https://github.com/drduh/Purse) is a secrets manager implemented with GnuPG and YubiKey.

## Signature

Sign a message:

```bash
printf "test message string\n" |
  gpg --armor --clearsign > signed.txt
```

Verify the signature:

```bash
gpg --verify signed.txt
```

The output will be similar to:

```console
gpg: Signature made Sat 01 Aug 2026 12:00:00 PM UTC
gpg:                using RSA key CF5A305B808B7A0F230DA064B3CD10E502E19637
gpg: Good signature from "yk.pn8wgfx67khlhext" [ultimate]
Primary key fingerprint: 4E2C 1FA3 372C BA96 A06A  C34A F0F2 CFEB 0434 1FB5
     Subkey fingerprint: CF5A 305B 808B 7A0F 230D  A064 B3CD 10E5 02E1 9637
```

## Configure touch

By default, cryptographic operations do not require any action from the user after YubiKey is unlocked with the User PIN.

To require a touch for each operation, use [YubiKey Manager](https://developers.yubico.com/yubikey-manager/) and the Admin PIN to set key policy.

Encryption:

```bash
ykman openpgp keys set-touch dec on
```

> [!NOTE]
> YubiKey Manager prior to version 5.1.0 uses `enc` instead of `dec` for encryption:

```bash
ykman openpgp keys set-touch enc on
```

> [!NOTE]
> Legacy versions of YubiKey Manager use `touch` instead of `set-touch`.

Signature:

```bash
ykman openpgp keys set-touch sig on
```

Authentication:

```bash
ykman openpgp keys set-touch aut on
```

To view the configured touch policy:

```bash
ykman openpgp info
```

To adjust the policy, see available options with:

```bash
ykman openpgp keys set-touch --help
```

`Cached` or `Cached-Fixed` may be desirable for YubiKey use with email clients.

YubiKey blinks when waiting for a touch. On Linux, [maximbaz/yubikey-touch-detector](https://github.com/maximbaz/yubikey-touch-detector) can also be used for indication.

## SSH

Create or import a [hardened configuration](https://github.com/drduh/YubiKey-Guide/blob/main/config/gpg-agent.conf):

```bash
cd ~/.gnupg
wget https://raw.githubusercontent.com/drduh/YubiKey-Guide/main/config/gpg-agent.conf
```

> [!NOTE]
> `cache-ttl` options do **not** apply when using YubiKey as a smart card, because the PIN is [cached by the smart card itself](https://dev.gnupg.org/T3362). To clear the PIN from cache (equivalent to `default-cache-ttl` and `max-cache-ttl`), remove YubiKey, or set `forcesig` when editing the card to be prompted for the PIN each time.

> [!TIP]
> Set `pinentry-program` to `/usr/bin/pinentry-gnome3` for a GUI-based prompt.

**macOS**

Install pinentry with `brew install pinentry-mac` or `sudo port install pinentry` then edit `gpg-agent.conf` to set the `pinentry-program` path to:

- Apple Silicon Macs: `/opt/homebrew/bin/pinentry-mac`
- Intel Macs: `/usr/local/bin/pinentry-mac` or `/opt/local/bin/pinentry` (MacPorts)
- MacGPG Suite: `/usr/local/MacGPG2/libexec/pinentry-mac.app/Contents/MacOS/pinentry-mac`

Then run `gpgconf --kill gpg-agent` for the change to take effect.

To use graphical applications on macOS, [additional setup is required](https://jms1.net/yubikey/make-ssh-use-gpg-agent.md).

Create `$HOME/Library/LaunchAgents/gnupg.gpg-agent.plist` with the following contents:

```xml
<?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">

    <dict>
        <key>Label</key>
        <string>gnupg.gpg-agent</string>
        <key>RunAtLoad</key>
        
        <key>KeepAlive</key>
        <false/>
        <key>EnvironmentVariables</key>
        <dict>
            <key>PATH</key>
            <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/usr/local/MacGPG2/bin:/bin</string>
        </dict>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/bin/env</string>
            <string>gpg-connect-agent</string>
            <string>/bye</string>
        </array>
    </dict>

```

Load it:

```bash
launchctl load $HOME/Library/LaunchAgents/gnupg.gpg-agent.plist
```

Create `$HOME/Library/LaunchAgents/gnupg.gpg-agent-symlink.plist` with the following contents:

```xml
<?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">

    <dict>
        <key>Label</key>
        <string>gnupg.gpg-agent-symlink</string>
        <key>ProgramArguments</key>
        <array>
            <string>/bin/sh</string>
            <string>-c</string>
            <string>/bin/ln -sf $HOME/.gnupg/S.gpg-agent.ssh $SSH_AUTH_SOCK</string>
        </array>
        <key>RunAtLoad</key>
        
    </dict>

```

Load it:

```bash
launchctl load $HOME/Library/LaunchAgents/gnupg.gpg-agent-symlink.plist
```

Reboot to activate changes.

**Windows**

Windows can already have some virtual smart card readers installed, like the one provided for Windows Hello. To verify YubiKey is the correct one used by scdaemon, add it to its configuration.

Find the YubiKey label using PowerShell:

```powershell
PS C:\WINDOWS\system32> Get-PnpDevice -Class SoftwareDevice | Where-Object {$_.FriendlyName -like "*YubiKey*"} | Select-Object -ExpandProperty FriendlyName
Yubico YubiKey OTP+FIDO+CCID 0
```

See [How to setup Signed Git Commits with a YubiKey NEO and GPG and Keybase on Windows (2018)](https://www.hanselman.com/blog/HowToSetupSignedGitCommitsWithAYubiKeyNEOAndGPGAndKeybaseOnWindows.aspx) for more information.

Edit `%APPDATA%/gnupg/scdaemon.conf` to add:

```console
reader-port <device name, e.g. Yubico YubiKey OTP+FIDO+CCID 0>
```

Edit `%APPDATA%/gnupg/gpg-agent.conf` to add:

```console
enable-ssh-support
enable-putty-support
```

Restart the agent:

```bash
gpg-connect-agent killagent /bye
gpg-connect-agent /bye
```

Verify YubiKey details:

```bash
gpg --card-status
```

Import the public key and set ultimate trust:

```bash
gpg --import 
```

Retrieve the public key id:

```bash
gpg --list-public-keys
```

Export the SSH public key:

```bash
gpg --export-ssh-key 
```

Copy the public SSH key to a file - it corresponds to the secret key on YubiKey and can be copied to SSH destination hosts.

Create a shortcut that points to `gpg-connect-agent /bye` and place it in the startup folder `shell:startup` to make sure the agent starts after reboot. Modify the shortcut properties so it starts in a "Minimized" window.

PuTTY can now be used for public-key SSH authentication. When the server asks for public-key verification, PuTTY will forward the request to GnuPG, which will prompt for a PIN to authorize the operation.

**WSL**

The goal is to configure SSH client inside WSL work together with the Windows agent, such as gpg-agent.exe.

See the [WSL agent architecture](media/schema_gpg.png) illustration for an overview.

GnuPG forwarding for cryptographic operations is not supported. See [vuori/weasel-pageant](https://github.com/vuori/weasel-pageant) for more information.

One way to forward is just `ssh -A` (still need to eval weasel to setup local ssh-agent), and only relies on OpenSSH. In this track, `ForwardAgent` and `AllowAgentForwarding` in ssh/sshd config may be involved. However, when using ssh socket forwarding, do not enable `ForwardAgent` in ssh config. See [SSH Agent Forwarding](#ssh-agent-forwarding) for more information. This requires Ubuntu 16.04 or newer for WSL and Kleopatra.

Download [vuori/weasel-pageant](https://github.com/vuori/weasel-pageant).

Add `eval $(/mnt/c//weasel-pageant -r -a /tmp/S.weasel-pageant)` to the shell rc file. Use a named socket here so it can be used in the `RemoteForward` directive of `~/.ssh/config`. Source it with `source ~/.bashrc`.

Display the SSH key with `ssh-add -l`.

Edit `~/.ssh/config` to add the following for each agent forwarding host:

```console
RemoteForward <remote SSH socket path> /tmp/S.weasel-pageant
```

The remote SSH socket path can be found with `gpgconf --list-dirs agent-ssh-socket`

Add the following to the shell rc file:

```bash
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
```

Add the following to `/etc/ssh/sshd_config`:

```console
StreamLocalBindUnlink yes
```

Reload SSH daemon:

```bash
sudo service sshd reload
```

Remove YubiKey and reboot. Log back into Windows, open a WSL console and enter `ssh-add -l` - no output should appear.

Plug in YubiKey, enter the same command to display the SSH key.

Connect to the remote host and use `ssh-add -l` to confirm forwarding works.

Agent forwarding may be chained through multiple hosts. Follow the same [protocol](#remote-host-configuration) to configure each host.

An alternate method is the [usbipd-win](https://github.com/dorssel/usbipd-win) library. If you encounter issues with accessing the YubiKey in WSL after configuring usbipd-win, you may need to add custom polkit rules to ensure proper permissions for the pcscd service. Here's an example configuration using a scard group (the group logic is optional):

Create a new rule file at /etc/polkit-1/rules.d/99-pcscd.rules:

```bash
polkit.addRule(function(action, subject) {
    if (action.id == "org.debian.pcsc-lite.access_card" &&
        subject.isInGroup("scard")) {
        return polkit.Result.YES;
    }
});

polkit.addRule(function(action, subject) {
    if (action.id == "org.debian.pcsc-lite.access_pcsc" &&
        subject.isInGroup("scard")) {
        return polkit.Result.YES;
    }
});
```

### Replace agents

To launch `gpg-agent` for SSH, use `gpg-connect-agent /bye` or `gpgconf --launch gpg-agent` commands.

Add the following to the shell rc file:

```bash
export GPG_TTY=$(tty)
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
gpgconf --launch gpg-agent
gpg-connect-agent updatestartuptty /bye > /dev/null
```

For fish, `config.fish` should look like this (consider putting them into the `is-interactive` block):

```fish
set -x GPG_TTY (tty)
set -x SSH_AUTH_SOCK (gpgconf --list-dirs agent-ssh-socket)
gpgconf --launch gpg-agent
```

When using `ForwardAgent` for ssh-agent forwarding, `SSH_AUTH_SOCK` only needs to be set on the *local* host, where YubiKey is connected. On the *remote* host, `ssh` will set `SSH_AUTH_SOCK` to something like `/tmp/ssh-mXzCzYT2Np/agent.7541` upon connection. Do **not** set `SSH_AUTH_SOCK` on the remote host - doing so will break [SSH Agent Forwarding](#ssh-agent-forwarding).

For `S.gpg-agent.ssh` (see [SSH Agent Forwarding](#ssh-agent-forwarding) for more info), `SSH_AUTH_SOCK` should also be set on the *remote*. However, `GPG_TTY` should not be set on the *remote*, explanation specified in that section.

### Copy public key

> [!TIP]
> It is **not** necessary to import the GnuPG public key in order to use SSH only.

Copy and paste the output from `ssh-add` to the server's `authorized_keys` file:

```console
$ ssh-add -L
ssh-rsa AAAAB4NzaC1yc2EAAAADAQABAAACAz[...]zreOKM+HwpkHzcy9DQcVG2Nw== cardno:000605553211
```

**Optional** Save the public key for identity file configuration. By default, SSH attempts to use all the identities available via the agent. It's often a good idea to manage exactly which keys SSH will use to connect to a server, for example to separate different roles or [to avoid being fingerprinted by untrusted ssh servers](https://words.filippo.io/ssh-whoami-filippo-io/). To do this you'll need to use the command line argument `-i [identity_file]` or the `IdentityFile` and `IdentitiesOnly` options in `.ssh/config`.

The argument provided to `IdentityFile` is traditionally the path to the _private_ key file (for example `IdentityFile ~/.ssh/id_rsa`). For YubiKey, `IdentityFile` must point to the _public_ key file, and `ssh` will select the appropriate private key from those available via ssh-agent. To prevent `ssh` from trying all keys in the agent, use `IdentitiesOnly yes` along with one or more `-i` or `IdentityFile` options for the target host.

To reiterate, with `IdentitiesOnly yes`, `ssh` will not enumerate public keys loaded into `ssh-agent` or `gpg-agent`. This means public-key authentication will not proceed unless explicitly named by `ssh -i [identity_file]` or in `.ssh/config` on a per-host basis.

In the case of YubiKey usage, to extract the public key from the ssh agent:

```bash
ssh-add -L | grep "cardno:000605553211" > ~/.ssh/id_rsa_yubikey.pub
```

Then explicitly associate this YubiKey-stored key for use with a host - `github.com` for example, as follows:

```console
$ cat << EOF >> ~/.ssh/config
Host github.com
  IdentitiesOnly yes
  IdentityFile ~/.ssh/id_rsa_yubikey.pub
EOF
```

Connect with public key authentication:

```console
$ ssh git@github.com -vvv
[...]
debug2: key: cardno:000605553211 (0x1234567890),
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: cardno:000605553211
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug2: input_userauth_pk_ok: fp e5:de:a5:74:b1:3e:96:9b:85:46:e7:28:53:b4:82:c3
debug3: sign_and_send_pubkey: RSA e5:de:a5:74:b1:3e:96:9b:85:46:e7:28:53:b4:82:c3
debug1: Authentication succeeded (publickey).
[...]
```

> [!TIP]
> To enable multiple SSH connections, use the [ControlMaster](https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing) option.

### Import SSH keys

If there are existing SSH keys to make available via `gpg-agent`, they will need to be imported. Then, remove the original private keys. When importing the key, `gpg-agent` uses the key filename as the label - this makes it easier to follow where the key originated from. In this example, we're starting with just the YubiKey in place and importing `~/.ssh/id_rsa`:

```console
$ ssh-add -l
4096 SHA256:... cardno:00060123456 (RSA)

$ ssh-add ~/.ssh/id_rsa && rm ~/.ssh/id_rsa
```

When invoking `ssh-add`, a prompt for the SSH key passphrase will appear, then the `pinentry` program will prompt and confirm a new passphrase to encrypt the converted key within the GnuPG key store.

The migrated key will be listed in `ssh-add -l`:

```console
$ ssh-add -l
4096 SHA256:... cardno:00060123456 (RSA)
2048 SHA256:... /Users/username/.ssh/id_rsa (RSA)
```

To show MD5 fingerprints, as used by `gpg-connect-agent`'s `KEYINFO` and `DELETE_KEY` commands:

```console
$ ssh-add -E md5 -l
4096 MD5:... cardno:00060123456 (RSA)
2048 MD5:... /Users/username/.ssh/id_rsa (RSA)
```

When using the key `pinentry` will be invoked to request the key passphrase. The passphrase will be cached for up to 10 idle minutes between uses, up to a maximum of 2 hours.

### SSH agent forwarding

> [!CAUTION]
> SSH Agent Forwarding can [add additional risk](https://matrix.org/blog/2019/05/08/post-mortem-and-remediations-for-apr-11-security-incident/#ssh-agent-forwarding-should-be-disabled) - proceed with caution!

There are two methods for ssh-agent forwarding, one is provided by OpenSSH and the other is provided by GnuPG.

The latter one may be more insecure as raw socket is just forwarded (not like `S.gpg-agent.extra` with only limited functionality; if `ForwardAgent` implemented by OpenSSH is just forwarding the raw socket, then they are insecure to the same degree). But for the latter one, one convenience is that one may forward once and use this agent everywhere in the remote. So again, proceed with caution!

For example, tmux does not have environment variables such as `$SSH_AUTH_SOCK` when connecting to remote hosts and attaching an existing session. For each shell, find the socket and `export SSH_AUTH_SOCK=/tmp/ssh-agent-xxx/xxxx.socket`. However, with `S.gpg-agent.ssh` in a fixed place, it can be used as the ssh-agent in shell rc files.

#### Use ssh-agent

Run `ssh -A remote` from the local host. On the remote host, `ssh-add -l` should list the public key from the YubiKey as a `cardno:` entry. Enable `ForwardAgent yes` only for explicitly trusted hosts!

#### Use S.gpg-agent.ssh

Before continuing, configure [GnuPG agent forwarding](gnupg-agent-forwarding) and record the local and remote values of `gpgconf --list-dirs agent-ssh-socket`.

Edit `~/.ssh/config` to add the remote host:

```console
Host
  Hostname remote-host.tld
  StreamLocalBindUnlink yes
  RemoteForward /run/user/1000/gnupg/S.gpg-agent.ssh /run/user/1000/gnupg/S.gpg-agent.ssh
  #RemoteForward [remote socket] [local socket]
  #Note that ForwardAgent is not wanted here!
```

After successfully connecting to the remote host, confirm `/run/user/1000/gnupg/S.gpg-agent.ssh` exists and configure `SSH_AUTH_SOCK`:

```bash
export SSH_AUTH_SOCK="/run/user/$UID/gnupg/S.gpg-agent.ssh"
```

`ssh-add -l` should now return the correct public key.

In this process no gpg-agent in the remote is involved, hence `gpg-agent.conf` in the remote is of no use. Also pinentry is invoked locally.

#### Chained forwarding

To use `ssh-agent` provided by OpenSSH to forward into a *third* host, use `ssh -A third` on the *remote* host.

If you use `S.gpg-agent.ssh`, assume you have gone through the steps above and have `S.gpg-agent.ssh` on the *remote*, and you would like to forward this agent into a *third* box, first configure `sshd_config` and `SSH_AUTH_SOCK` of *third* in the same way as *remote*, then configure SSH of *remote* by adding the following lines:

```console
Host third
  Hostname third-host.tld
  StreamLocalBindUnlink yes
  RemoteForward /run/user/1000/gnupg/S.gpg-agent.ssh /run/user/1000/gnupg/S.gpg-agent.ssh
  #RemoteForward [remote socket] [local socket]
  #Note that ForwardAgent is not wanted here!
```

The path must be set according to `gpgconf --list-dirs agent-ssh-socket` on *remote* and *third* hosts.

## GitHub

Use YubiKey to sign Git commits and tags and to authenticate to GitHub over SSH. To authenticate, first add the exported SSH public key to [GitHub SSH keys](https://github.com/settings/keys).

Configure the signing key:

```bash
git config --global user.signingkey $KEY_ID
```

Alternatively, if you are using the aforementioned `IdentityFile` (SSH key) for signing:

```bash
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_rsa_yubikey.pub
```

Configure the `user.name` and `user.email` options to match the identity associated with this key:

```bash
git config --global user.name 'YubiKey User'
git config --global user.email yubikey@example.com
```

To sign commits or tags, use the `-S` option, or consider enabling commit and tag signing by default:

```bash
git config --global commit.gpgsign true
git config --global tag.gpgSign true
```

**Windows**

Configure authentication:

```bash
git config --global core.sshcommand "plink -agent"
git config --global gpg.program 'C:\Program Files (x86)\GnuPG\bin\gpg.exe'
```

Then update the repository URL to `git@github.com:USERNAME/repository`

## GnuPG agent forwarding

YubiKey can sign Git commits and decrypt files on remote hosts by forwarding GnuPG agent operations. To connect through an intermediate host and then access GitHub over SSH, see [SSH agent forwarding](#ssh-agent-forwarding).

After forwarding is configured, GnuPG on the remote host communicates through a forwarded socket to gpg-agent on the local host. The local agent accesses the YubiKey and displays any PIN prompt locally.

On the remote host, edit `/etc/ssh/sshd_config` to set `StreamLocalBindUnlink yes`.

**Optional** Without root access on the remote host to edit `/etc/ssh/sshd_config`, socket located at `gpgconf --list-dir agent-socket` on the remote host will need to be removed before forwarding works. See [AgentForwarding GNUPG wiki page](https://wiki.gnupg.org/AgentForwarding) for more information.

Import the public key on the remote host. On the local host, copy the public keyring to the remote host:

```bash
scp ~/.gnupg/pubring.kbx remote:~/.gnupg/
```

On modern distributions, such as Fedora 30, there is no need to set `RemoteForward` in `~/.ssh/config`

### Legacy distributions

On the local host, run:

```bash
gpgconf --list-dirs agent-extra-socket
```

This should return a path to agent-extra-socket - `/run/user/1000/gnupg/S.gpg-agent.extra` - though on some Linux distros (and macOS) it may be `/home//.gnupg/S.gpg-agent.extra`

Find the agent socket on the **remote** host:

```bash
gpgconf --list-dirs agent-socket
```

This should return a path such as `/run/user/1000/gnupg/S.gpg-agent`

Finally, enable agent forwarding for a given host by adding the following to the local host's `~/.ssh/config` (agent sockets may differ):

```
Host
  Hostname remote-host.tld
  StreamLocalBindUnlink yes
  RemoteForward /run/user/1000/gnupg/S.gpg-agent /run/user/1000/gnupg/S.gpg-agent.extra
  #RemoteForward [remote socket] [local socket]
```

It may be necessary to edit `gpg-agent.conf` on the *local* host to add the following information:

```
pinentry-program /usr/bin/pinentry-gtk-2
extra-socket /run/user/1000/gnupg/S.gpg-agent.extra
```

> [!IMPORTANT]
> The pinentry program starts on the *local* host, not remote.

Any pinentry program except `pinentry-tty` or `pinentry-curses` may be used. This is because local `gpg-agent` may start headlessly (by systemd without `$GPG_TTY` set locally telling which tty it is on), thus failed to obtain the pin. Errors on the remote may be misleading saying that there is *IO Error*. (Yes, internally there is actually an *IO Error* since it happens when writing to/reading from tty while finding no tty to use, but for end users this is not friendly.)

See [Issue 85](https://github.com/drduh/YubiKey-Guide/issues/85) for more information and troubleshooting.

### Chained GnuPG agent forwarding

Assume you have gone through the steps above and have `S.gpg-agent` on the *remote*, and you would like to forward this agent into a *third* box, first you may need to configure `sshd_config` of *third* in the same way as *remote*, then in the ssh config of *remote*, add the following lines:

```console
Host third
  Hostname third-host.tld
  StreamLocalBindUnlink yes
  RemoteForward /run/user/1000/gnupg/S.gpg-agent /run/user/1000/gnupg/S.gpg-agent
  #RemoteForward [remote socket] [local socket]
```

You should change the path according to `gpgconf --list-dirs agent-socket` on *remote* and *third*.

On *local* you have `S.gpg-agent.extra` whereas on *remote* and *third*, you only have `S.gpg-agent`.

## Using multiple YubiKeys

When a GnuPG key is added to YubiKey using `keytocard`, the credential is deleted from the keyring and a local reference ('stub') pointing to the card is added. The stub identifies the GnuPG key ID and YubiKey serial number.

When a Subkey is added to an additional YubiKey, the stub is overwritten and will now point to the latest YubiKey. GnuPG will request a specific YubiKey by serial number, as referenced by the stub, and will not recognize another YubiKey with a different serial number.

To scan an additional YubiKey and recreate the correct stub:

```bash
gpg-connect-agent "scd serialno" "learn --force" /bye
```

Alternatively, use a script to delete the GnuPG shadowed key, where the serial number is stored (see [GnuPG #T2291](https://dev.gnupg.org/T2291)):

```bash
mkdir -p ~/scripts && cat >> ~/scripts/remove-keygrips.sh <<EOF
#!/usr/bin/env bash
(( $# )) || { echo "Specify a key." >&2; exit 1; }
KEYGRIPS=$(gpg --with-keygrip --list-secret-keys "$@" | awk '/Keygrip/ { print $3 }')
for keygrip in $KEYGRIPS
do
  rm "$HOME/.gnupg/private-keys-v1.d/$keygrip.key" 2> /dev/null
done

gpg --card-status
EOF

chmod +x ~/scripts/remove-keygrips.sh

~/scripts/remove-keygrips.sh $KEY_ID
```

See discussion in [#19](https://github.com/drduh/YubiKey-Guide/issues/19) and [#112](https://github.com/drduh/YubiKey-Guide/issues/112) for more information.

## Email

YubiKey can decrypt and sign emails and attachments using [Thunderbird](https://www.thunderbird.net/) and [Mutt](http://www.mutt.org/). Thunderbird supports OAuth and can be used with Gmail. See [this EFF guide](https://ssd.eff.org/en/module/how-use-pgp-linux) for more information.

### Thunderbird

Follow [Mozilla instructions](https://wiki.mozilla.org/Thunderbird:OpenPGP:Smartcards#Configure_an_email_account_to_use_an_external_GnuPG_key) to setup YubiKey with Thunderbird using the external GPG provider.

> [!NOTE]
> Thunderbird will [fail to decrypt](https://github.com/drduh/YubiKey-Guide/issues/448) messages if the `armor` option is configured.
> If you see the error `gpg: [don't know]: invalid packet (ctb=2d)` or `message cannot be decrypted (there are unknown problems with this encrypted message)`, remove `armor` from `~/.gnupg/gpg.conf`, then restart Thunderbird.

### Mailvelope

[Mailvelope](https://www.mailvelope.com/en) allows YubiKey to be used with Gmail and others.

> [!NOTE]
> Mailvelope [does not work](https://github.com/drduh/YubiKey-Guide/issues/178) with the `throw-keyids` option set in `gpg.conf`

On macOS, install gpgme using Homebrew:

```bash
brew install gpgme
```

To allow Chrome to run gpgme, edit `~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/gpgmejson.json` to add:

```json
{
    "name": "gpgmejson",
    "description": "Integration with GnuPG",
    "path": "/usr/local/bin/gpgme-json",
    "type": "stdio",
    "allowed_origins": [
        "chrome-extension://kajibbejlbohfaggdiogboambcijhkke/"
    ]
}
```

Edit the default path to allow Chrome to find GnuPG:

```bash
sudo launchctl config user path /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
```

Finally, install the [Mailvelope extension](https://chromewebstore.google.com/detail/mailvelope/kajibbejlbohfaggdiogboambcijhkke) from the Chrome web store.

### Mutt

Mutt can be used from the command line or its text-based interface. To enable OpenPGP support, copy the sample GnuPG configuration file (`/usr/share/doc/mutt/samples/gpg.rc`), set `pgp_default_key`, `pgp_sign_as`, and `pgp_autosign` in that file, then add a source line for it in the Mutt configuration file (`~/.muttrc`).

> [!NOTE]
> `pinentry-tty` set as the pinentry program in `gpg-agent.conf` may cause problems with Mutt because it uses curses; use `pinentry-curses` or other graphic pinentry program instead.

## Keyserver

Optionally, publish the public key to a keyserver so others can find it.

Select a server to send it to:

```bash
gpg --send-key $KEY_ID
gpg --keyserver keys.gnupg.net --send-key $KEY_ID
gpg --keyserver hkps://keyserver.ubuntu.com:443 --send-key $KEY_ID
```

Or if [uploading to keys.openpgp.org](https://keys.openpgp.org/about/usage):

```bash
gpg --export $KEY_ID | curl -T - https://keys.openpgp.org
```

A retrieval URL can also be stored on YubiKey:

```bash
URL="hkps://keyserver.ubuntu.com:443/pks/lookup?op=get&search=${KEY_ID}"
```

Edit YubiKey with `gpg --edit-card` and the Admin PIN:

```console
gpg/card> admin

gpg/card> url
URL to retrieve public key: hkps://keyserver.ubuntu.com:443/pks/lookup?op=get&search=0xFF00000000000000

gpg/card> quit
```

# Updating keys

OpenPGP does not provide [forward secrecy](https://en.wikipedia.org/wiki/Forward_secrecy): if an encryption key is compromised, an attacker may be able to decrypt messages encrypted to that key in the past. Renewing or replacing Subkeys limits future use of a lost or obsolete key, but it may not protect previously encrypted data. Choose an expiration and renewal schedule to meet individual risk tolerance and maintenance capacity preferences.

When a Subkey expires, it can either be renewed or replaced. Both actions require access to the Certify key.

- Renewal preserves existing Subkeys and is generally simpler to operate.
- Replacement creates new Subkeys and may be more secure: new Subkeys will **not** be able to decrypt previous data, authenticate with SSH, etc. The public key will need to be updated and any encrypted data must be decrypted and re-encrypted to new Subkeys. This process is functionally equivalent to provisioning a new YubiKey.

Neither rotation method is superior and it is up to personal philosophy on identity management and individual threat modeling to decide which one to use, or whether to expire Subkeys at all. Ideally, Subkeys would be ephemeral: used only once for each unique encryption, signature and authentication event, however in practice that is not really practical nor worthwhile with YubiKey. Advanced users may dedicate an air-gapped machine for frequent credential rotation.

To renew or rotate Subkeys, follow the same process as generating keys: boot to a secure environment, install required software and disable networking.

Connect the portable storage device with the Certify key and identify the device path.

Decrypt and mount the encrypted volume:

```bash
sudo cryptsetup luksOpen /dev/sdc1 gnupg-secrets
sudo mkdir -p /mnt/encrypted-storage
sudo mount /dev/mapper/gnupg-secrets /mnt/encrypted-storage
```

Mount the non-encrypted public partition:

```bash
sudo mkdir -p /mnt/public
sudo mount /dev/sdc2 /mnt/public
```

Copy the original private key materials (after updating the encrypted storage directory name) to a temporary working directory:

```bash
export GNUPGHOME=$(mktemp -d "${TMPDIR:-/tmp}/$(date +%Y.%m.%d)-XXXXXXXX")
cp -avi /mnt/encrypted-storage/2026.*/* $GNUPGHOME/
```

Confirm the identity is available, set the key ID and fingerprint values:

```bash
gpg -K
export KEY_FP=$(gpg -k --with-colons $IDENTITY | awk -F: '/^fpr:/ { print $10; exit }')
export KEY_ID="${KEY_FP: -16}"
printf "\nKey ID/Fingerprint:\t%s\n%s\n\n" "$KEY_ID" "$KEY_FP"
```

Recall the Certify key passphrase and set it, for example:

```bash
export CERTIFY_PASS="ABCD-0123-IJKL-4567-QRST-UVWX"
```

## Renew Subkeys

Set the updated expiration date:

```bash
export KEY_EXPIRATION=2028-09-01
```

Renew the Subkeys:

```bash
printf '%s' "$CERTIFY_PASS" |
  gpg --batch --pinentry-mode loopback \
      --passphrase-fd 0 --quick-set-expire "$KEY_FP" "$KEY_EXPIRATION" \
    $(gpg -K --with-colons |
      awk -F: '$1=="fpr" { if (++n > 1) printf "%s ", $10 } END { print "" }')
```

Export the updated public key:

```bash
gpg --armor --export $KEY_ID |
  sudo tee /mnt/public/public-$KEY_ID-$(date +%F).asc
```

Transfer the public key to the destination host and import it:

```bash
gpg --import /mnt/public/*.asc
```

Alternatively, publish to a public key server and download it:

```bash
gpg --send-key $KEY_ID
gpg --recv $KEY_ID
```

The validity of the GnuPG identity will be extended, enabling encryption and signature operations.

The SSH public key does **not** need to be updated on remote hosts.

## Rotate Subkeys

Follow the original procedure to [Create Subkeys](#create-subkeys).

Previous Subkeys can be deleted from the identity.

Finish by transferring new Subkeys to YubiKey.

Copy the **new** temporary working directory to encrypted storage, which is still mounted:

```bash
sudo cp -avi $GNUPGHOME /mnt/encrypted-storage
```

Unmount and close the encrypted volume:

```bash
sudo umount /mnt/encrypted-storage
sudo cryptsetup luksClose gnupg-secrets
```

Export the updated public key:

```bash
sudo mkdir -p /mnt/public
sudo mount /dev/sdc2 /mnt/public
gpg --armor --export $KEY_ID | sudo tee /mnt/public/$KEY_ID-$(date +%F).asc
sudo umount /mnt/public
```

Remove the storage device and follow the original steps to transfer new Subkeys (`4`, `5` and `6`) to YubiKey, replacing existing ones.

Reboot or securely erase the temporary working directory.

# Reset YubiKey

If PIN attempts are exceeded, the YubiKey is locked and must be [Reset](https://developers.yubico.com/ykneo-openpgp/ResetApplet.html) and set up again using the encrypted backup.

Use YubiKey Manager to reset the OpenPGP application:

```bash
ykman openpgp reset
```

YubiKey can also be reset with [scripts/resetCard.sh](https://github.com/drduh/YubiKey-Guide/blob/main/scripts/resetCard.sh), or by copying the following commands to a file and running `gpg-connect-agent -r <filename>`:

```console
/hex
scd serialno
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 e6 00 00
scd apdu 00 44 00 00
/echo Card has been successfully reset.
/bye
```

Remove and reinsert the YubiKey to complete reset.

# Optional hardening

The following steps may improve the security and privacy of YubiKey.

## Improving entropy

Generating cryptographic keys requires high-quality [randomness](https://www.random.org/randomness/), measured as entropy. Most operating systems use software-based pseudorandom number generators or CPU-based hardware random number generators (HRNG).

Optionally, a device such as [OneRNG](https://onerng.info/onerng/) may be used to [increase the speed](https://lwn.net/Articles/648550/) and possibly the quality of available entropy.

Before creating keys, configure [rng-tools](https://wiki.archlinux.org/title/Rng-tools):

```bash
sudo apt -y install at rng-tools python3-gnupg openssl
wget https://github.com/OneRNG/onerng.github.io/raw/master/sw/onerng_3.7-1_all.deb
```

Verify the package:

```bash
sha256sum onerng_3.7-1_all.deb
```

The value must match:

```console
b7cda2fe07dce219a95dfeabeb5ee0f662f64ba1474f6b9dddacc3e8734d8f57
```

Install the package:

```bash
sudo dpkg -i onerng_3.7-1_all.deb
echo "HRNGDEVICE=/dev/ttyACM0" | sudo tee /etc/default/rng-tools
```

Insert the device and restart rng-tools:

```bash
sudo atd
sudo service rng-tools restart
```

## Enable KDF

> [!IMPORTANT]
> This feature is not compatible with legacy GnuPG versions, especially mobile clients, and may cause the PIN to always be rejected.

This step must be completed before changing PINs or moving keys or an error will occur: `gpg: error for setup KDF: Conditions of use not satisfied`

A key derivation function (KDF) derives a value from the PIN before it is sent to the card, reducing its exposure.

Enable KDF using the default Admin PIN of `12345678`:

```bash
gpg --command-fd 0 --pinentry-mode loopback --card-edit <<EOF
admin
kdf-setup
12345678
EOF
```

## Network considerations

This section is primarily focused on Debian/Ubuntu systems, but the concepts apply to any system connected to a network.

Whether using a virtual machine, installing on dedicated hardware, or running a Live OS temporarily, start *without* a network connection and disable any unnecessary services listening on all interfaces before connecting to the network.

Services such as cups and avahi may listen on the network by default, increasing potential attack surface. For this workflow, treat every network as untrusted.

**Disable listening services**

Ensure only essential network services are running. If a service does not exist, a "Failed to stop" warning may appear:

```bash
sudo systemctl stop bluetooth exim4 cups avahi avahi-daemon sshd
```

**Firewall**

Enable a basic firewall policy of *deny inbound, allow outbound*.

Debian does not enable a default host-firewall policy by default.

On Ubuntu, [ufw](https://ubuntu.com/server/docs/how-to/security/firewalls/) is built-in and can be enabled with:

```bash
sudo ufw enable
```

On systems without `ufw`, `nftables` is replacing `iptables`. The [nftables wiki has examples](https://wiki.nftables.org/wiki-nftables/index.php/Simple_ruleset_for_a_workstation) for a baseline *deny inbound, allow outbound* policy. The `fw.inet.basic` policy covers both IPv4 and IPv6.

Download this README and any other resources to another external drive when creating the bootable media, to have this information ready to use offline.

Regardless of which policy is configured, write the contents to a file (e.g., `nftables.conf`) and apply the policy with the following command:

```bash
sudo nft -f ./nftables.conf
```

**Review system state**

`NetworkManager` should be the only listening service on port 68/udp to obtain a DHCP lease (and 58/icmp6 if you have IPv6).

To examine a process's command line arguments, use `ps axjf` to print a process tree.

```bash
# Dump network state information
sudo ss -anp -A inet

# List all processes in a process tree
ps axjf

# BSD syntax, list all processes but no process tree
ps aux
```

If you find any additional processes listening on the network that aren't needed, take note and disable them with one of the following:

```bash
# Stop services managed by systemctl
sudo systemctl stop 

# Terminate the process by matching its command line string
sudo pkill -f ''

# Obtain the process ID
pgrep -f ''

# Terminate the process ID
sudo kill 
```

After reviewing the system state and applying any desired restrictions, connect to the network only to download required software. Disconnect again before generating keys.

# Notes

1. YubiKey has two USB configurations selected by a short or long touch. By default, a short touch may type a one-time-password string beginning with `cccccccc`. This behavior is separate from the OpenPGP workflow and can be moved to the second configuration or disabled with `ykman config usb -d OTP`.

1. Using YubiKey for GnuPG does not prevent use of [other features](https://developers.yubico.com/), such as [WebAuthn](https://developers.yubico.com/WebAuthn/) and [OTP](https://developers.yubico.com/OTP/).

1. To switch between YubiKeys, remove the first YubiKey and restart gpg-agent, ssh-agent and pinentry with `pkill "gpg-agent|ssh-agent|pinentry" ; eval $(gpg-agent --daemon --enable-ssh-support)` then insert the other YubiKey and run `gpg-connect-agent updatestartuptty /bye`.

1. To use YubiKey on multiple computers, import the corresponding public keys, then confirm YubiKey is visible with `gpg --card-status`. Trust the imported public keys ultimately with `trust` and `5`, then `gpg --list-secret-keys` will show the correct and trusted key.

1. To [participate in keysigning parties](https://www.gnupg.org/gph/en/manual/x334.html), signing [imported public keys](https://gist.github.com/F21/b0e8c62c49dfab267ff1d0c6af39ab84) requires first setting up a secure ephemeral environment and importing the Certify key into that enclave; a signing Subkey cannot be used to sign [imported public keys](https://security.stackexchange.com/questions/153057/possible-to-sign-an-imported-key-with-a-subkey-using-gpg).

# Troubleshooting

Symptom or error | Recommended action
--- | ---
General GnuPG questions or unfamiliar options | Use `man gpg` to review GnuPG options and command-line flags.
Need more diagnostic detail | Restart `gpg-agent` with verbose debug output: `pkill gpg-agent; gpg-agent --daemon --no-detach -v -v --debug-level advanced --homedir ~/.gnupg`
General YubiKey or GnuPG issue | Remove and reinsert the YubiKey, or restart `gpg-agent`.
`Yubikey core error: no yubikey present` | Confirm that the YubiKey is inserted correctly. It should blink once when plugged in.
`Yubikey core error: no yubikey present` persists | Install a newer version of `yubikey-personalization`, as described in [Install software](#install-software).
`General key info..: [none]` in card-status output | Import the public key.
The public key is lost | Follow [Recovering lost GPG public keys from your YubiKey](https://www.nicksherlock.com/2021/08/recovering-lost-gpg-public-keys-from-your-yubikey/).
`gpg: decryption failed: secret key not available` | Install GnuPG 2.x. Also verify that the PIN is correct and that the required private Subkey is available on the YubiKey.
`Yubikey core error: write error` | The YubiKey may be locked. Install and run `yubikey-personalization-gui` to unlock it.
`Key does not match the card's capability` | Use 2048-bit RSA key sizes.
`sign_and_send_pubkey: signing failed: agent refused operation` | Verify that `ssh-agent` has been replaced with `gpg-agent`, as described in [Replace agents](#replace-agents).
`sign_and_send_pubkey: signing failed: agent refused operation` persists | Run `gpg-connect-agent updatestartuptty /bye`.
`sign_and_send_pubkey: signing failed: agent refused operation` persists after updating the startup TTY | Set a valid `pinentry` program path in `~/.gnupg/gpg-agent.conf`. A related error may be `gpg: decryption failed: No secret key`.
`sign_and_send_pubkey: signing failed: agent refused operation` with OpenSSH 8.9p1 or later | This may be a known OpenSSH issue. Review the linked [Arch Linux discussion](https://bbs.archlinux.org/viewtopic.php?id=274571).
`The agent has no identities` from `ssh-add -L` | Install and start `scdaemon`.
`Error connecting to agent: No such file or directory` from `ssh-add -L` | Ensure that the agent's UNIX socket is configured and available. Review [Replace agents](#replace-agents).
`Permission denied (publickey)` | Run SSH with verbosity, for example `ssh -v host`, and confirm that the card's public key is offered: `Offering public key: RSA SHA256:... cardno:00060123456`. Also verify the user exists on the target system (different from the user on the local system).
SSH authentication still fails | Increase SSH verbosity with up to three flags: `ssh -vvv host`.
SSH authentication still fails after reviewing verbose client output | On the server, stop the background SSH service, for example with `sudo systemctl stop sshd`, then run `/usr/sbin/sshd -eddd` in the foreground with extensive debug logging to inspect the authentication attempt. Note that the server will not fork and will only process one connection and has to be restarted after every SSH connection test.
`Please insert the card with serial number ...` | See [Using multiple YubiKeys](#using-multiple-yubikeys).
`There is no assurance this key belongs to the named user`, `encryption failed: Unusable public key`, or `No public key` | Run `gpg --edit-key` and set owner trust to `5 = I trust ultimately`.
`Need the secret key to do this` while setting trust | Specify trust for the identity with the `trust-key [key ID]` directive.
`pass insert` reports `There is no assurance this key belongs to the named user` and `encryption failed: Unusable public key` | Adjust the identity's trust level as described above.
`gpg: ... skipped: Unusable public key`, `signing failed: Unusable secret key`, or `encryption failed: Unusable public key` | The Subkey may have expired. Follow [Updating keys](#updating-keys) to renew or rotate the Subkeys.
The pinentry dialog does not appear and SSH signing fails with `agent refused operation` | Install the `dbus-user-session` package, then restart the session or system.
Unexpected PIN prompts during SSH authentication | Add `disable-application piv` to `~/.gnupg/scdaemon.conf`.
`gpg: selecting card failed: No such device` or `gpg: OpenPGP card not available: No such device` | The local `pcscd` service may lack permission to access the card. Create the Polkit rule shown below, replacing `wheel` if the system uses a different administrative group.

Create `/etc/polkit-1/rules.d/99-pcscd.rules` with the following contents:

```console
polkit.addRule(function(action, subject) {
        if (action.id == "org.debian.pcsc-lite.access_card" &&
                subject.isInGroup("wheel")) {
                return polkit.Result.YES;
        }
});

polkit.addRule(function(action, subject) {
        if (action.id == "org.debian.pcsc-lite.access_pcsc" &&
                subject.isInGroup("wheel")) {
                return polkit.Result.YES;
        }
});
```

# Alternative solutions

- [vorburger/ed25519-sk.md](https://github.com/vorburger/blog/blob/main/security/ed25519-sk.md) - use YubiKey for SSH without GnuPG
- [smlx/piv-agent](https://github.com/smlx/piv-agent) - SSH and GnuPG agent which can be used with PIV devices
- [keytotpm](https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Key-Management.html) - use GnuPG with TPM systems

# Additional resources

- [Yubico - PGP](https://developers.yubico.com/PGP/)
- [Yubico - YubiKey Personalization](https://developers.yubico.com/yubikey-personalization/)
- [A Visual Explanation of GPG Subkeys (2022)](https://rgoulter.com/blog/posts/programming/2022-06-10-a-visual-explanation-of-gpg-subkeys.html)
- [lsasolutions/makegpg](https://gitlab.com/lsasolutions/makegpg)
- [Trammell Hudson - Yubikey (2020)](https://trmm.net/Yubikey)
- [Yubikey forwarding SSH keys (2019)](https://blog.onefellow.com/post/180065697833/yubikey-forwarding-ssh-keys)
- [GPG Agent Forwarding (2018)](https://mlohr.com/gpg-agent-forwarding/)
- [Stick with security: YubiKey, SSH, GnuPG, macOS (2018)](https://evilmartians.com/chronicles/stick-with-security-yubikey-ssh-gnupg-macos)
- [PGP and SSH keys on a Yubikey NEO (2015)](https://www.esev.com/blog/post/2015-01-pgp-ssh-key-on-yubikey-neo/)
- [Offline GnuPG Master Key and Subkeys on YubiKey NEO Smartcard (2014)](https://blog.josefsson.org/2014/06/23/offline-gnupg-master-key-and-subkeys-on-yubikey-neo-smartcard/)
- [Creating the perfect GPG keypair (2013)](https://alexcabal.com/creating-the-perfect-gpg-keypair/)

[^1]: [Revocation certificates](https://security.stackexchange.com/questions/14718/does-openpgp-key-expiration-add-to-security/79386#79386) should be used to revoke an identity.
[^2]: See [issue 477](https://github.com/drduh/YubiKey-Guide/issues/477) for NIST guideline discussion.