Mac OS X Mojave and SSH-AGENT notifications

For work (this time around), I have been given a new Macbook Pro 12″ running Mac OS X version 10.14.1, also known as Mojave.

I was missing my ssh-agent notifications on this new mac (see links below), so it’s time to replay my recipe wherein I patch Apple’s OpenSSH to integrate support for Notification Center.

Original article:
Update to original:
Further update to original:

However, things have changed slightly in Mojave, so we’ll explore a new set of instructions to simplify the process.

How to patch Apple’s OpenSSH on Mojave to support native Notification Center in 17 steps (Mojave specific changes highlighted in red):

REMINDER: You can browse Apple’s open source repository at

  1. Open
  2. Mac OS X 10.14.1:
    curl -LO
    Mac OS X 10.14.3:
    curl -LO
  3. tar zxf !$:t
  4. INC=`pwd`/!$:r:r/include
  5. curl -LO
  6. tar zxf !$:t
  7. cd !$:r:r/openssh
  8. curl -L -o patch.txt
  9. patch -N < !$
  10. CC=clang CFLAGS="-I/Applications/ -I$INC" LDFLAGS="-isysroot / -L/Applications/" ./configure --with-pam --with-audit=bsm
  11. make TARGETS=ssh-agent
  12. Disable System Integrity Protection using Apple SIP Guide
  13. sudo cp -avf /usr/bin/ssh-agent{,.orig}
    Note: This step requires SIP to be disabled
  14. sudo cp ssh-agent /usr/bin/ssh-agent
    Note: This step requires SIP to be disabled
  15. Optional: Re-enable SIP using Apple SIP Guide
  16. killall ssh-agent
  17. ssh some-host
    Note: If you’re just using ~/.ssh/id_rsa and haven’t added the key to your keychain, no notification will appear and you will have to execute “ssh-add -K ~/.ssh/id_rsa” (without quotes; make sure to use capital-K) to add the key to your keychain.

Now every subsequent ssh request that uses a key stored in your keychain will cause a notification to appear in Apple’s built-in Notification Center. Cheers!

Multi-Factor (4FA and 5FA) Authentication with FreeBSD and SSH

I was asked on twitter today to explain some recent work I have done in the multi-factor authentication department. I can write this article because I have recently released my work under the title “secure_thumb.”

While many 2FA and beyond methodologies implement SMS as a factor in authentication, I was uncomfortable sending factors over the wire. Over the years I have had one actual instance where a machine got rooted and the SSH private key (although passphrase protected) was stolen from said machine. At the time, I did not have PGP set up, so I had no way of getting a new key trusted by the FreeBSD community. We quickly blacklisted the stolen key and a review of recent commits was performed to check for any malicious activity. Another developer was sent to my house to verify government-issued ID before a new key was generated offline and injected into the cluster through a trusted channel.

From that incident many years ago, I vowed to never let a single factor stand between me and the FreeBSD cluster again (that factor being a passphrase typed at a command-prompt to load an SSH private key that gave access to the FreeBSD cluster and commit access to change any FreeBSD source code).

Since I was actively writing and maintaining the FreeBSD boot loader at the time, there was some mild concern that malicious code could have been injected into places that few others understood (the loader code that I write/maintain is in a language called Forth; a language which causes most to run the opposite direction and is known for being quite unreadable). I did a top-down review of every line of Forth at that time to put minds at-ease (added benefit, I then shortly after rewrote several of the inefficient structures and solved some inherited issues that were long-in-the-tooth as they say).

Post-incident, my SSH private key to the cluster remained secured on a thumb drive encrypted by GELI — an in-kernel FreeBSD system that allows for the encryption of entire filesystems with a myriad of options. We went from a single-factor to 3-factor in a single day, but we will see how a scare later resulted in the development of 4- and 5-factor authentication that is used today.

For many years I used 3FA implemented as a physical USB thumb drive kept in a secure location, offline, encrypted, holding SSH private keys protected with a unique passphrase. One day, it was believed that I lost this key. When it became obvious that we were not going to find it in any time soon, I had the cluster revoke my keys. This time, however, I had PGP properly set up and could quickly re-establish trust by sending a new public key in a PGP encrypted message to the cluster admin team.

Every time I regenerate my private keys (years apart) I take the opportunity to think about security. This time I had an entire framework built around my 3FA solution, and I envisioned a scenario where the person that may have found my thumb drive would not be able to decrypt the contents even if they had stolen the passphrase through keystroke logging. My 4FA solution was born.

Since FreeBSD GELI allows you to have multiple keys (which are essentially concatenated together to form one ginormous key), I built a new framework which creates a key (we’ll call this a trust certificate) for the host or hosts that you want to allow decryption. Thus, only if an attacker were able to purloin both my GELI passphrase using a keystroke logger and steal the GELI keyfile from trusted host will they be able to mount the volume. Those 2 factors plus the physical locality of the thumb drive (and being mostly offline), plus the passphrase required to use the SSH private key, altogether form 4FA.

Where does the fifth factor come into play?

Physically locking USB thumb drives that require a code to unlock before they will yield their plug to a computer. I have seen 3 such mechanical devices (e.g., the Cryptex Round Compass Lock by SDI) and a couple digital ones with a keypad/LCD on the thumb drive.

The secure_thumb framework for managing 4FA using securely-stored and encrypted SSH private keys, see

As an added bonus, the framework creates one unencrypted partition to contain trust-management software (*cough* shell scripts that make sure the host is trusted and is not sniffing keystrokes ala DTrace for example) and scripts to automate the mounting of the GELI partition. But wait, there’s more …

The framework creates a FreeBSD slice to allow the creation of multiple encrypted partitions each with a different key and trust certificate. You can make a USB thumb drive that has 7 encrypted partitions, each with a different passphrase, and with the trust certificates for each partition sent to different people. The net effect would be a thumb drive that can be used by 7 people but each person can only open their partition.

There are other hidden features, such as the ability to dynamically resize the encrypted slice (both grow and shrink) but you can also add 2 additional partitions to it for making it look like it’s just a drive for another OS with some random unencrypted data on it for TSA to peruse.

FreeBSD Nginx Performance

At $work, we have been looking at Nginx Plus because unlike the free open-source version of Nginx, Plus has load-balancing features. We’re pretty excited about that because it means we could potentially replace our reliance on HAProxy. Below is a simple graphic showing the potential infrastructure change.

With an nginx plus license, you can eliminate the need for haproxy

The next thing we had to do was determine which platform we would be using for our test of Nginx Plus. That ended up being limited to just two choices based on our constraints — must be physical hardware and must support HTTP/2 and ALPN.

While the system requirements page doesn’t say this directly, we were informed that the only configuration currently supporting HTTP/2 and ALPN on physical hardware is FreeBSD 11.0 and Ubuntu 16.04 LTS. Others such as CentOS were disqualified because, for example, the OpenSSL version was too old to support ALPN.

With a little bit of work in massaging our PXE server (resulting in a complete rewrite of pxe-config for FreeBSD deployment automation), we had the FreeBSD systems deployed in a matter of days. The generation of a Debian Installer preseed for Ubuntu proved to be far more time-consuming and challenging, but after a week we had the Ubuntu systems deployed as well.

We then registered for a free 30-day trial of Nginx Plus and went through the installation instructions for each Operating System. The steps for FreeBSD and Ubuntu are similar wherein you configure your system to add their package server and use the standard package utilities (pkg on FreeBSD and apt-get on Ubuntu) to install a binary package.

With FreeBSD 11.0-RELEASE-p1 and Ubuntu 16.04 LTS on identical servers in the same rack/switch, we were ready to do some benchmarking to help us determine whether Nginx Plus can deliver equitable performance in a load-balanced array compared with an haproxy cluster sitting in front of the free and open-source version of Nginx.

To generate the right type of load for our performance benchmark, we are using hey by Jaana B. Dogan. Below is the usage statement from hey -h:

Usage: hey [options...] <url>

  -n  Number of requests to run. Default is 200.
  -c  Number of requests to run concurrently. Total number of requests cannot
      be smaller than the concurrency level. Default is 50.
  -q  Rate limit, in seconds (QPS).
  -o  Output type. If none provided, a summary is printed.
      "csv" is the only supported alternative. Dumps the response
      metrics in comma-separated values format.

  -m  HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS.
  -H  Custom HTTP header. You can specify as many as needed by repeating the flag.
      For example, -H "Accept: text/html" -H "Content-Type: application/xml" .
  -t  Timeout for each request in seconds. Default is 20, use 0 for infinite.
  -A  HTTP Accept header.
  -d  HTTP request body.
  -D  HTTP request body from file. For example, /home/user/file.txt or ./file.txt.
  -T  Content-type, defaults to "text/html".
  -a  Basic authentication, username:password.
  -x  HTTP Proxy address as host:port.
  -h2 Enable HTTP/2.

  -host	HTTP Host header.

  -disable-compression  Disable compression.
  -disable-keepalive    Disable keep-alive, prevents re-use of TCP
                        connections between different HTTP requests.
  -cpus                 Number of used cpu cores.
                        (default for current machine is 8 cores)
  -more                 Provides information on DNS lookup, dialup, request and
                        response timings.

NOTE: Although our requirements include HTTP/2 and hey has the -h2 flag to enable HTTP/2, our performance benchmarks will be using HTTP/1[.1] because our current edge infrastructure to which we can make comparisons does not yet support HTTP/2.

The command that we used to test the performance of our setup is as follows:

hey -n 3000 -c 300 -m GET -disable-keepalive <url>

This asks hey to perform a total of 3000 HTTP/1[.1] GET requests for <url> with up to 300 concurrent requests.

When <url> points to our vanilla Ubuntu 16.04 LTS test box running Nginx Plus, the results are as follows:

Nginx Plus and Ubuntu
The hey command, hammering a vanilla Ubuntu 16.04 LTS server running Nginx Plus

When <url> points instead to our vanilla FreeBSD 11.0-RELEASE-p1 test box, the results are as follows:

Nginx Plus and FreeBSD
The hey command, hammering a vanilla FreeBSD 11.0-RELEASE-p1 server running Nginx Plus

Focusing on the Summary Total, we can see that vanilla FreeBSD takes 3x longer than Ubuntu and something is causing high response times in FreeBSD.

SPOILER: After much digging, it was discovered that the nginx binary for Nginx Plus was linking against an OpenSSL that was compiled from ports without the ASM optimizers (highly optimized Assembly routines for speeding up calculations on supported CPU architectures).

The instructions for installing Nginx Plus on FreeBSD include “pkg install nginx-plus” and this brings in security/openssl from ports instead of using the OpenSSL that comes with the FreeBSD base Operating System. This is generally a good thing because ports are updated more frequently than base which helps keep Nginx Plus up-to-date with the latest OpenSSL.

The standard UNIX utility ldd shows us that /usr/local/sbin/nginx (as-installed by the nginx-plus package) links not against the system’s /usr/lib/ but instead the non-base (read: ports) version located at /usr/local/lib/

However, as we will see in the below photo, both the system OpenSSL in /usr/bin and the ports OpenSSL in /usr/local/bin are the same version compiled on the same calendar day (despite having different shared library suffixes).

Command Line
Nginx Plus links to the ports OpenSSL

Though the two versions of OpenSSL appear to be the same, they are actually quite different. When OpenSSL is compiled with ASM optimizations, it can take full advantage of AES-NI and PCLMULQDQ, two important CPU instructions that increase the efficiency of cryptographic calculations.

Command Line
Testing OpenSSL for AES-NI and PCLMULQDQ to ensure ASM optimizations in support of CPU based crypto

The OPENSSL_ia32cap environment variable is a bit-mask of OpenSSL capabilities which allows us to disable AES-NI and PCLMULQDQ. Combining the values of ~0x200000000000000 (disable AES-NI) and ~0x200000000 (disable PCLMULQDQ) to get ~0x200000200000000, we can disable both AES-NI and PCLMULQDQ for individual runs of “openssl speed“.

In the below two commands, if your CPU supports AES-NI and your OpenSSL has been compiled with ASM optimizations, the first command will be many times faster than the second (wherein optimizations are disabled if available).

% openssl speed -elapsed -evp aes-256-cbc
% env OPENSSL_ia32cap="~0x2000002000000000" openssl speed -elapsed -evp aes-256-cbc

NOTE: See for additional details.

As one might expect, the OpenSSL in /usr/bin shows a huge performance increase when AES-NI is not disabled. It was quite the shock to find that the ports OpenSSL in /usr/local/bin showed no differences in performance between the two commands.

We, the FreeBSD committers, took a look at the security/openssl port and discovered that it did not enable ASM optimizations by default at the time the binary packages were last compiled for FreeBSD 11. So I worked with the maintainer of port to fix that for the next time the packages get recompiled.

Review: D9480: security/openssl: Enable ASM by default
Submitted: rP433671

The next step is to determine the impact that an un-optimized OpenSSL has on our hey tests. The FreeBSD dynamic linker supports configurable dynamic object mapping through libmap.conf(5), so it is a fairly simple matter of telling /usr/local/sbin/nginx to use a different OpenSSL.

Creating /usr/local/etc/libmap.d/nginx.conf with the following contents will cause nginx to use the OpenSSL libraries that came with the base Operating System:

# origin		target

After creating this file and restarting nginx with “service nginx restart“, the hey performance tests now show FreeBSD ahead of Ubuntu in a head-to-head test.

To better illustrate the effects that the unoptimized OpenSSL had on the hey benchmarks, I wrote a utility that generates JSON from the output.

NOTE: While there are many ways to benchmark, this test focused on “time to completion” for 3000 requests with up-to 300 concurrent. The JSON generated depicts the non-linear approach toward completion.

Wrapper script for hey named hey_genlog for generating a log capable of being converted into JSON:

############################################################ IDENT(1)
# $Title: Script to generate statistics from hey against a host $
# $Copyright: 2017 Devin Teske. All rights reserved. $
# $Smule$
############################################################ INFORMATION
# Statistics are logged to stdout. Use hey2graph to generate JSON.
# JSON is designed for highcharts/highstock API.
############################################################ CONFIGURATION

# hey utility from

# File to request

# Total number of requests to perform

# Maximum number of concurrent requests

# QoS rate limiting
# NB: Set to NULL to disable rate limiting
#RATE_LIMIT=1 # seconds
RATE_LIMIT= # seconds

# Should we use Secure-HTTP (https)?
# NB: Set to NULL to disable https

############################################################ GLOBALS

pgm="${0##*/}" # Program basename

# Global exit status

# Command-line arguments

############################################################ FUNCTIONS

	exec >&2
	printf "Usage: %s HOST\n" "$pgm"
	exit $FAILURE

############################################################ MAIN

case "$HOST" in
"") usage ;; # NOTREACHED
*:*) : fall through ;;
	if [ "$SECURE" ]; then
echo "Performing $TOTAL total requests"
echo "Maximum $CONCURRENT concurrent requests"
set -x
$HEY \
	-n $TOTAL \
	-m GET \
	-disable-keepalive \
	http${SECURE:+s}://$HOST$FILE |
	awk -v cmd="date +%s.%N" '
			cmd | getline start
		/requests done/ {
			cmd | getline date
			date = sprintf("%0.4f", date - start)
			sub(/^/, date " ")


Sample output:

[ ~]# ./hey_genlog | tee hey.freebsdbase.log
Performing 3000 total requests
Maximum 300 concurrent requests
0.5026 51 requests done.
1.0026 235 requests done.
1.5028 429 requests done.
2.0029 610 requests done.
2.5028 832 requests done.
3.0033 1025 requests done.
3.5031 1224 requests done.
4.0033 1427 requests done.
4.5038 1617 requests done.
5.0037 1816 requests done.
5.5039 2015 requests done.
6.0039 2240 requests done.
6.5041 2431 requests done.
7.0041 2639 requests done.
7.5041 2874 requests done.
7.7668 All requests done.

  Total:	7.7650 secs
  Slowest:	4.9109 secs
  Fastest:	0.0157 secs
  Average:	0.6898 secs
  Requests/sec:	386.3489
  Total data:	8580021000 bytes
  Size/request:	2860007 bytes

Status code distribution:
  [200]	3000 responses

Response time histogram:
  0.016 [1]	|
  0.505 [1253]	|∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
  0.995 [1174]	|∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
  1.484 [360]	|∎∎∎∎∎∎∎∎∎∎∎
  1.974 [140]	|∎∎∎∎
  2.463 [52]	|∎∎
  2.953 [13]	|
  3.442 [5]	|
  3.932 [0]	|
  4.421 [1]	|
  4.911 [1]	|

Latency distribution:
  10% in 0.2235 secs
  25% in 0.3667 secs
  50% in 0.5729 secs
  75% in 0.8668 secs
  90% in 1.3381 secs
  95% in 1.6279 secs
  99% in 2.3221 secs

Script for converting output from hey_genlog into JSON, hey2graph:

#!/usr/bin/awk -f
BEGIN { fmt = "[%0.4f, %u],\n"; printf fmt, 0, 0 }
/total requests/ { total = $2 }
/Total:/ { time = $2 }
/requests done/ && $2 ~ /^[0-9]+$/ { printf fmt, $1, $2 - y; y = $2 }
END { printf fmt, time, total - y }

Sample output:

[ ~]# ./hey2graph hey.freebsdbase.log
[0.0000, 0],
[0.5026, 51],
[1.0026, 184],
[1.5028, 194],
[2.0029, 181],
[2.5028, 222],
[3.0033, 193],
[3.5031, 199],
[4.0033, 203],
[4.5038, 190],
[5.0037, 199],
[5.5039, 199],
[6.0039, 225],
[6.5041, 191],
[7.0041, 208],
[7.5041, 235],
[7.7650, 126],

The process of generating JSON graph data was performed for Ubuntu, FreeBSD with ports OpenSSL, and FreeBSD with base OpenSSL. As you can see in the below graph, FreeBSD with base OpenSSL is the fastest with Ubuntu very close behind, and FreeBSD with an unoptimized ports OpenSSL coming in at 3x slower.

Satisfied that we had eliminated the performance issue causing FreeBSD to be 3x slower, we now asked why is Ubuntu slower than FreeBSD?

Intensive throughput benchmarks showed that FreeBSD is capable of reaching 87.1% line-rate while Ubuntu was only capable of 86.5%. Both systems given an Intel 10GE network interface, FreeBSD appears to be utilizing the hardware more efficiently. At the switch, we can see that FreeBSD is 99.1% efficient on 10GE, resulting in a measured 10.3% TCP overhead at the time of testing.

Switch Graph
FreeBSD line rate test on Intel 10GE, switch-level throughput graph

The result of our testing is that FreeBSD running Nginx Plus is a suitable replacement for our HaProxy and Nginx topology. You and everyone reading this won’t have to worry about the documented issue with OpenSSL because I worked with Bernard Spil and Allan Jude to get it fixed in the FreeBSD ports tree. The security/openssl port has been updated to enable ASM optimizations by default and fairly soon the binary packages will be rebuilt — until then, you can use the above /usr/local/etc/libmap.d/nginx.conf file to temporarily use the base OpenSSL if you’re unable to update /usr/ports/security/openssl/Makefile and recompile it yourself.


Mac OS X El Capitan and Native ssh-agent Notifications

For work, I have been given a new Macbook Pro 13″ running Mac OS X version 10.11.6, also known as El Capitan.

I was missing my ssh-agent notifications on this new mac (see links below), so it’s time to replay my recipe wherein I patch Apple’s OpenSSH to integrate support for Notification Center.

Original article:
Update to original:

However, things have changed slightly in El Capitan, so we’ll explore a new set of instructions to simplify the process.

How to patch Apple’s OpenSSH on El Capitan to support native Notification Center in 16 steps (El Capitan specific changes highlighted in red):

REMINDER: You can browse Apple’s open source repository at

  1. Disable System Integrity Protection using Apple SIP Guide
  2. Open
  3. curl -LO
  4. tar zxf !$:t
  5. sudo cp -R !$:r:r/src/include/openssl /usr/local/include/
  6. curl -LO
  7. tar zxf !$:t
  8. cd !$:r:r/openssh
  9. curl -L -o patch.txt
  10. patch -N < !$
  11. ./configure --with-pam --with-audit=bsm
  12. make
  13. sudo cp -avf /usr/bin/ssh-agent{,.orig}
    Note: This step requires SIP to be disabled
  14. sudo cp ssh-agent /usr/bin/ssh-agent
    Note: This step requires SIP to be disabled
  15. killall ssh-agent
  16. ssh some-host
    Note: If you’re just using ~/.ssh/id_rsa and haven’t added the key to your keychain, no notification will appear and you will have to execute “ssh-add -K ~/.ssh/id_rsa” (without quotes; make sure to use capital-K) to add the key to your keychain.
  17. Optional: Re-enable SIP using Apple SIP Guide

Now every subsequent ssh request that uses a key stored in your keychain will cause a notification to appear in Apple’s built-in Notification Center. Cheers!

Write Images to USB with AppleScript

As the only release engineer at $work, I have been tasked with creating the bootable USB devices of our FreeBSD-based product to send to the Contract Manufacturer. Every time a new release made it to General Availability (GA) status, Sabine would drop off a couple USB sticks and tell me which build to load onto them.

Wanting to empower her, I set out to create a better approach; one that did not involve dropping to the command-line and tapping-out a “dd” command. Meet a new AppleScript, named “WriteImage” written to take the guess-work out of the process.

With WriteImage you can now take the USB image file (*.img or *.img.gz) and drop it on the AppleScript droplet. It automates the process of generating the necessary commands to image the file onto hardware USB. Tell the app through a series of clicks or drag/drop actions which image to write, it then prompts you to insert a USB device, and then asks for confirmation (twice) before launching Terminal to do the dirty work.

Let’s see it in action (photo tour):

Selecting an Image file for WriteImage
WriteImage initial dialog when double-clicked.
Prompt to insert USB device
WriteImage prompt, waiting for you to insert a USB device to image.
Last chance before proceeding
WriteImage displays a Last Chance dialog before proceeding to do anything.
Writing the Image to USB
WriteImage runs a shell script that does the dirty work.
Imaging the USB Drive
WriteImage ultimately results in an automatically crafted “dd” command run via Terminal
Get progress with Ctrl-T
When “dd” is running, press Ctrl-T on the keyboard to see how much data has been written and how fast
As-is the case with FreeBSD images, when the process is complete, your Mac will give this error. Success in disguise.
Initializing a Drive
If you need to image a drive that is not currently readable by Mac OS X, click “Initialize…” and use Erase


REPLAY: Mac OS X and Native SSH-Agent Notifications

Having recently updated my 2014 Macbook Air 11″ from Mac OS X 10.10 to 10.10.4, I lost my customizations to Apple’s OpenSSH and no longer was I receiving anything in the Notification Center for SSH logins using my keychain. Looks like it’s time to rehash the steps necessary to reload support for the Notification Center for those going through the same ordeal.

For reference here’s the original blog post where I introduced the customizations required to get Apple Notification Center support for OpenSSH on Mac OS X:

Step-by-step we’ll go through the motions of re-obtaining the latest copy of Apple’s modified OpenSSH, to be patched.

NOTE: Make sure you’ve updated Xcode in Apple Software Update, else you’ll get the error "configure: error: Your OpenSSL headers do not match your library" during compilation steps below.

ASIDE: You can browse Apple’s opensource repository at (obtaining the latest copy of OpenSSH with Apple’s customizations couldn’t be easier). Rather than documenting how to navigate said page, below steps will instead use direct links to the software we’re recompiling (for brevity).

How to patch Apple’s OpenSSH to support native Mac OS X Notification Center (in 13 easy steps):

  1. Open
  2. curl -LO
  3. tar zxf !$:t
  4. cd !$:r:r/openssh
  5. curl -L -o patch.txt
  6. patch -N < !$
  7. ./configure --with-pam --with-audit=bsm
  8. make
  9. sudo cp -avf /usr/bin/ssh-agent{,.orig}
  10. sudo cp ssh-agent /usr/bin/ssh-agent
  11. killall ssh-agent
  12. ssh some-host
  13. Click "Always Allow" to confirm access from new ssh-agent to Keychain

Now every subsequent ssh request will give you a notification in Apple's built-in Notification Center. Cheers!

Mac OS X and Native ssh-agent Notifications

Apple Mac OS X makes working with SSH private keys easy and convenient. Things that you can safely forget and drop from your routine when using Mac OS X are:

  • How and when to launch ssh-agent(1)
  • Continuously loading your private key

Apple has integrated launchd(8) and Keychain support into ssh-agent(1) so it launches automatically on-demand and can interact with keys stored in Keychain Access.

First, a brief look at the above integration before we go improving things using new features introduced in Mac OS X 10.8 and higher.

EDIT: If you’re reading this thinking “Mac OS X has had Keychain and launchd integration for a while,” skip on ahead to “That being said…” below).

Traditionally when using an agent you would first manually launch an instance of ssh-agent(1) and then follow that up with:

ssh-add ~/.ssh/id_dsa

while on Mac OS X there is:

ssh-add -K ~/.ssh/id_dsa

which both loads your key into the running ssh-agent(1) and imports it into your Keychain. So you’ll find that quite untraditionally if you kill the running agent and then try to ssh(1) to a remote host, a new agent is launched on-demand and it loads the private key through the Keychain (login succeeds despite conventional logic about agents).

In the following picture, we can see previously loaded key(s) if we filter on the word “ssh” in Apple’s Keychain Access application (provided in the Utilities folder accessible via Command-Shift-U keyboard shortcut while in the Finder application):

View SSH private keys loaded with `ssh-add -K' in Keychain Access
View SSH private keys loaded with “ssh-add -K” in Keychain Access

If you delete this key from Keychain Access application then ssh(1) logins requiring that key no longer succeed as the running agent immediately loses access to said key. So the Keychain can be thought of as a persistent store for the agent; one that is tied to your Mac’s login account.

The automatic re-launching of ssh-agent(1) through launchd(8) means that if you kill the running agent it will be re-launched not immediately but only when access is attempted to a launchd(8)-provided default $SSH_AUTH_SOCK value as-configured in /System/Library/LaunchAgents/org.openbsd.ssh-agent.plist.

Initially when Mac OS X boots, ssh-agent(1) is not started. It is only when you perform your first ssh(1) (or related) command that launchd(8) invokes the following command:

/usr/bin/ssh-agent -l

You can see launchd(8)‘s integration in-action by opening a Terminal immediately after booting your Mac and first executing:

ps axwww | grep ssh-agent

You’ll see there are no instances of ssh-agent(1), yet. Meanwhile, if you execute:


You’ll see launchd(8) provided a default value (similar to the following):


When any ssh(1) command attempts to access this launchd(8) provided $SSH_AUTH_SOCK listener, launchd(8) invokes the previously mentioned “ssh-agent -l” instance which then accesses private keys stored in your keychain. For example, assuming Remote Login is enabled in the Sharing section of System Preferences (which enables sshd), execute:

ssh localhost

After which, re-execute:

ps axwww | grep ssh-agent

To find a running instance of “/usr/bin/ssh-agent -l” (the “-l” indicating it was launched on-demand by launchd(8)).

This is all very slick integration that quintessentially eases your SSH life. In a nut-shell, it’s private keys provided from your Keychain on-the-fly whenever you use an ssh utility.



That being said, we can certainly improve upon this integration by adding new code to Apple’s version of OpenSSH. Primarily, since ssh-agent(1) can now be loaded on-demand and access data in my Keychain, I would like to get a notification every time someone uses the running agent (for security reasons and also coolness factor).

In Mac OS X Mountain Lion (10.8) and Mavericks (10.9) we are blessed with the new Notification Center API ( This built-in functionality replaces the need for 3rd-party software such as Growl ( required to perform notifications in previous releases of Mac OS X (10.7 and older).

RESOURCE: Apple’s custom version of OpenSSH (available from — specifically for Mavericks

I first tested integration of the NSNotificationCenter API on a non-Apple version of OpenSSH after failing to get my friend’s Growl-based notification patches to work (I didn’t want to pay $3.99 for Growl in the Mac App Store). Prior to Mac OS X 10.8, my friend @kang had produced the following work for getting notifications out of ssh-agent(1):

EDIT: My friend just made a patched version of Simon G. Tatham’s Pageant that provides native Windows notifications — — available in both Source ( and binary release (

However, my good friend’s work was on the non-Apple version of OpenSSH and thus my resulting agent binary lacked launchd(8) integration and Keychain support. This meant that if I were to replace the existing /usr/bin/ssh-agent binary in Mavericks with the patched non-Apple version, I would lose those features previously discussed above, let alone that his patches were for an external notification system versus the new built-in Notification Center.

So I set out to build a drop-in replacement for Mavericks’ /usr/bin/ssh-agent carrying all the integration of the original.

EDIT: Keep reading toward the end for GitHub source link and link to Mavericks binary.

After unpacking Apple’s OpenSSH-186.tar.gz (link above) and applying my patches to add support for NSNotificationCenter, I quickly learned that some additional non-standard configure arguments were required.

Within the top-level openssh directory (of the unpacked OpenSSH-186.tar.gz archive) I executed the following to produce a binary truly worthy of replacing the stock /usr/bin/ssh-agent:

./configure --with-pam --with-audit=bsm

After which I had a patched ssh-agent binary in the current working directory, suitable for doing the following:

sudo cp -avn /usr/bin/ssh-agent{,.orig}
sudo cp ssh-agent /usr/bin/ssh-agent
killall ssh-agent

The very next ssh(1) command I execute causes a new fresh instance of my patched ssh-agent(1) to be invoked. The first time my patched agent attempts to access my Keychain, I get the following audit request (image below):

Granting patched ssh-agent(1) access to Keychain for the first time.
Granting patched ssh-agent(1) access to Keychain for the first time.

I choose the “Always Allow” option, knowing that if I want to change it later I can locate the private key in Keychain Access (HINT: Filter on “ssh”) and press the Command-I keyboard shortcut to edit Access Controls for that key.

My patched agent is programmed to hook into the new Notification Center and send you a notification when signing requests (image below).

Notification Center message from ssh-agent(1)
Notification Center message from ssh-agent(1)

Now every time I authenticate by way of private key, regardless of whether that key was loaded once with “ssh-add” or from the Keychain imported via “ssh-add -K“, I get a message from the Notification Center.

EDIT: The primary concern that inspired this work is when you enable agent forwarding to remote hosts. Logging into a compromised host with agent forwarding, a hacker can use your agent to log into yet uncompromised systems to which you have access via your agent. While notifications won’t prevent the use of your agent to reach new machines should you enable forwarding through a compromised system, the notifications will let you know when to (a) shut down your agent (b) take inventory of active connections where agent forwarding was enabled and (c) cull the logs for machines you were forwarding through in an effort to find suspicious activity indicating either a malicious hacker or black-hat administrator on the system. For a corporate laptop that primarily only ever connects to corporate networks (where such activity is never to be expected), a notification is more than adequate to quell the problem (versus a public network where it may be more advantageous to use an ask-pass utility to confirm key usage rather than notify after open usage).

How those messages appear are configured in the System Preferences for Notifications (easily accessible via the gear icon at bottom-right of the Notification Center Drawer). Only after you’ve received your initial message from the patched ssh-agent(1) can you then configure the specifics of how its messages appear. The patched agent pretends to be Keychain Access when talking to the Notification Center, so configuring the style and attributes for Keychain Access notifications will allow you to customize how these agent notifications appear.

As notifications are delivered, they stack up in the pull-out drawer of the Notification Center. I like to clear the log of ssh-agent(1) notifications before I go to bed and check for any when I wake up (perhaps indicating that my agent signed a login request when I wasn’t looking).

By default, I’ve made the agent play the “Submarine” sound during notifications. This can be changed by making your own build from the source code I’ve branched into Git offered below:

But you don’t have to modify the code if all you want to do is disable the notification sound. Within the Notifications section of System Preferences you can state that you don’t want the Keychain Access notifications to play a sound.

Last, but not least, I have made a precompiled binary with my modifications so you can simply download and copy into place (using the below command-line instructions):

curl -OL
tar jxf !$:t
sudo cp -avn /usr/bin/ssh-agent{,.orig}
sudo cp -fv ssh-agent /usr/bin/
killall ssh-agent

Executing these 5 commands and then logging into a remote machine with ssh(1) using private keys should generate a notification from Keychain Access (pictured above). Cheers!

If you need to rollback to the original ssh-agent for any reason, the above steps made a backup that can be restored typing the following commands:

sudo mv -f /usr/bin/ssh-agent{.orig,}
killall ssh-agent

Wherein your next ssh(1) command will cause the original ssh-agent(1) to be loaded (which doesn’t support NSNotificationCenter API).

Debugging FreeNAS 9.2.0 System

I recently found my FreeNAS box rebooting itself in the middle of the night (every night) and I wanted to know what was going on. I first tried enabling the debug kernel (see below picture) but that didn’t work nor did it get me any closer to understanding the issue at-hand.

"Enabling the FreeNAS Debug Kernel from the WebUI"
Enabling the FreeNAS Debug Kernel from the WebUI

The idea behind enabling the debug kernel was that it would drop me into the kernel debugger rather than rebooting 15 seconds after an unattended fatal error (leaving zero logs to analyze). But much to my surprise, the system rebooted anyway.

The next step was to set up remote syslog to allow FreeNAS to log to an external box. The first thing I did was connect my FreeNAS server directly to a FreeBSD system. The FreeNAS system will be configured to log everything to the FreeBSD system; so when FreeNAS reboots I will have a log of what lead up to that event.

I configured the secondary network interface on each server to talk on the same subnet. On the FreeNAS side, I went into the WebUI and configured the second interface of em1 to have IPv4 address with a /24 subnet ( When that was done, it looked like the below picture.

"Configuring a local second network interface in the FreeNAS WebUI"
Configuring a local second network interface in the FreeNAS WebUI

After that, I logged into my FreeBSD server and prepared it to receive remote syslog data.

ifconfig em1 inet
echo freenas >> /etc/hosts
sysrc syslogd_enable=YES
sysrc syslogd_flags="-a freenas -v -v"
echo "+freenas" >> /etc/syslog.conf
echo "*.* /var/log/freenas.log" >> /etc/syslog.conf
touch /var/log/freenas.log
service syslogd restart

Now SSH into your FreeNAS box and execute the following:

mount -uw /
echo freebsd >> /conf/base/etc/hosts
echo freebsd >> /etc/hosts
mount -ur /

Then perform the last final bit, which is to go into the FreeNAS WebUI and enter a value of “freebsd” for the syslog server (see below picture).

"Where to configure a remote syslog server fro within the FreeNAS WebUI"
Where to configure a remote syslog server fro within the FreeNAS WebUI

At this point, you should be able to execute via SSH on the FreeNAS system:

logger foo

And get the following entry in /var/log/freenas.log on your FreeBSD system:

Jan 26 04:42:37 freenas root: foo


Of course, the jury is still out on exactly why my system is crashing, but I suspect a failing hard disk (the logs being streamed to the FreeBSD system seam to indicate via smartd messages a prefail condition for the boot disk).

Recovering FreeNAS 9.2.0

If you should find that you have a FreeNAS system for which you have forgotten the root password, here’s an easy way to recover your system.

First, you’ll need to get shell access. If you’ve left the console menu enabled, then resetting the root password is as easy as 1, 2, 3. However if you have disabled the console menu for security reasons, keep reading for the prescribed recipe.

If you are lucky enough to have a user on the system that has sudo privileges, the first step is to log in as that user. If you do not have such a user, the first step is instead to boot into single-user mode.

TIP: Since FreeNAS has a 1-second timeout on the boot menu, you’ll have to repeatedly tap the space bar when you see it starting to load the kernel; with perseverance you will be able to abort the 1-second timeout to interact with the boot menu wherein single-user mode can be enabled.

Once you’re on the shell (either as root in single-user mode or as a secondary user with sudo access), the first task at-hand is to make the root filesystem read/write by executing:

mount -a         # Only required if running single-user
mount -uw /

Once this is completed, we can then perform the first of a two-step process to set a new password for the root account (restoring access to both SSH and the WebUI). Execute:

passwd root

This is only the first step on a FreeNAS system. The work done by the above command will be undone by the /etc/ix.rc.d/ix-passwd boot script every time the machine boots. We need to take the temporary work performed by the above command and make it permanent by copying the information into the FreeNAS SQLite accounting database.

This can be performed by executing:

sqlite3 /data/freenas-v1.db \
    "UPDATE account_bsdusers SET bsdusr_unixhash=\"$( \
        awk -F: '$1=="root"{print $2;exit}' /etc/master.passwd \
    )\" WHERE bsdusr_username=\"root\""

If you are running as a user with sudo privilege (instead of running as root in single-user mode), here is a sudo endowed version of the above command:

sudo sqlite3 /data/freenas-v1.db \
    "UPDATE account_bsdusers SET bsdusr_unixhash=\"$( \
        sudo awk -F: '$1=="root"{print $2;exit}' /etc/master.passwd \
    )\" WHERE bsdusr_username=\"root\""

To check your work, here’s a command to extract the hash from the SQLite database:

sqlite3 /data/freenas-v1.db "SELECT bsdusr_unixhash \
    FROM account_bsdusers WHERE bsdusr_username=\"root\""

At this point, if you are running in single-user mode, type…


…to continue booting. If instead you used a sudo capable user to make the change, there is no need to reboot as the system accounting table in the FreeNAS SQLite database is in-sync with the FreeBSD system accounting files (/etc/master.passwd; /etc/spwd.db; etc.).

You should now be able to log into the FreeNAS WebUI with the updated password. Cheers!