TIL: macOS keychain command line

Today I learned about the macOS utility security, which is used to interact with keychains from the command line. I’m having a look at neomutt as a means to give me access to my mail from a trusted shell on my iMac. One of the tools in the Rube-Goldberg machine I’m assembling to get mail into neomutt is mbsync, which grabs a copy of your IMAP mail and stores it locally. You then point neomutt at that. neomutt can speak IMAP natively, but having a local copy of your mail is good for when you’re under siege from shadow company and they’ve cut your hardline, but you still want to read your email.

mbsync is nice enough not to force you to store your email passwords in its config file in plain text. Instead, it will cheerfully call a command to provide it, should you have something available that’ll securely store such things and give them to you on command. In steps security, the interface for keychain.

It’s as simple as:

# add a password
security add-generic-password -a {Account} -s {Service} -w {Password}
# retrieve a password
security find-generic-password -a {Account} -s {Service} -w

That adds a password to your keychain, and retrieves just the plaintext (by default, security returns a keychain object that’s holding the password, not the password itself). There’s a lot more to it of course, so check out the security(1) manpage for more details.

So in my .mbsyncrc, I have a PassCmd like PassCmd "security find-generic-password -a mbsync -s rys@sommefeldt.com -w".

Edit: as I work through it, turns out you can have neomutt use the same mechanism for the SMTP passwords:

set smtp_pass = `security find-generic-password -a mbsync -s rys@sommefeldt.com -w`