html> MAC OS X security keychains and ceryificates

security

Command line interface to keychains and Security framework

security [-hilqv] [-p prompt] [command] [command_options] [command_args]

administer keychains, manipulate keys and certificates, etc.

Interactive mode is entered by using -i or -p
-h no arguments : list commands.
-i interactive mode.
-l Before security exits, run
/usr/bin/leaks -nocontext

on itself to see if the command(s) you executed had any leaks.

Process:         security [95767]
Path:            /usr/bin/security
Load Address:    0x104404000
Identifier:      security
Version:         ???
Code Type:       X86-64
Parent Process:  bash [1183]

Date/Time:       2016-11-04 18:15:26.149 -0400
Launch Time:     2016-11-04 18:15:22.436 -0400
OS Version:      Mac OS X 10.11.6 (15G1108)
Report Version:  7
Analysis Tool:   /Applications/Xcode.app/Contents/Developer/usr/bin/leaks
Analysis Tool Version:  Xcode 8.1 (8B62)
----

leaks Report Version:  2.0
Process 95767: 406 nodes malloced for 55 KB
Process 95767: 0 leaks for 0 total leaked bytes.
leaks: returned 1
-p prompt -i changes the default prompt to prompt
-q quiter
-v Verboser

SECURITY COMMAND SUMMARY

All commands accept -h for help.

help
list-keychains search list.
default-keychain
login-keychain
create-keychain
delete-keychain and remove them from the search list.
lock-keychain
unlock-keychain
set-keychain-settings
set-keychain-password
show-keychain-info
dump-keychain
create-keypair an asymmetric key pair.
add-generic-password
add-internet-password
add-certificates
find-generic-password
delete-generic-password
find-internet-password
delete-internet-password
find-certificate
find-identity
delete-certificate
set-identity-preference
get-identity-preference
create-db
export
import
cms Encode or decode CMS messages.
install-mds
add-trusted-cert
remove-trusted-cert
dump-trust-settings
user-trust-settings-enable
trust-settings-export
trust-settings-import
verify-cert
authorize
authorizationdb
execute-with-privileges
leaks Run /usr/bin/leaks on this process.
error Display a descriptive message for the given error code(s).
list-keychains
[-d dom]
[-s [keychain...]]
manipulate the keychain search list.
-d domdomain.
-s Set the search list
    "/Volumes/DATA/dgerman/Library/Keychains/login.keychain"
    "/Library/Keychains/System.keychain"
show-keychain-info [keychain]
 show-keychain-info  "/Library/Keychains/System.keychain"
Keychain "/Library/Keychains/System.keychain" lock-on-sleep timeout=300s

 show-keychain-info "/Volumes/DATA/dgerman/Library/Keychains/login.keychain"
Keychain "/Volumes/DATA/dgerman/Library/Keychains/login.keychain" no-timeout

dump-keychain [-adir]
-a access control list of items
-d (decrypted) data of items
-i Interactive access control list editing mode edited for tersity
> security -i
security> dump-keychain -i
keychain: "/Volumes/DATA/dger/Library/Keychains/login.keychain"
version: 256
class: 000F
attributes:
      00 =000F
      01 ="Apple ID dger key"
      02 =
      03 =1
      04 =0
      05 =0
      06 =0x3EF37CE6D9D13…  ">\363v\210\316m\235\020m\010v\334\375\263\31250\274\212\206"
      07 =
      08 =0x7B3837313931…  "{87191ca2-0fc9-11d4-849a-000502b52122}\000"
      09 =002A  "\000\000\000*"
      0A =0800
      0B =0800
      0C =000000000
      0D =000000000
      0E =0 0F =0 10 =1 11 =0 12 =1 13 =0 14 =1 15 =0
      16 =1 17 =0 18 =0 19 =0 1A =0
access: 2 entries
    entry 0:
        authorizations (1): any
        don't-require-password
        description: 
        applications: 
Remove this acl?n
    entry 1:
        authorizations (1): change_acl
        don't-require-password
        description: 
        applications: 
Remove this acl?n 
Update access? n

-r raw (encrypted) data of items
default-keychain
[-d dom] [-s [keychain]]
dom is one of user|system|common|dynamic
-ddomUse the specified preference domain.
-s Set
Unset it if no keychain is specified.
login-keychain [-d dom ][-s [keychain]]
-ddomUse the preference domain.
-s Set the login keychain .
Unset it if no keychain is specified.
create-keychain [-P] [-p password] [keychain...]
-P Prompt for password using the SecurityAgent.
-p password Use password for the keychains being created.
If neither -P or -p password are specified, the user is prompted for a password on the command line.
delete-keychain [keychain...] and remove them from the search list.
lock-keychain [-a|keychain] Lock the default keychain if none is specified. If the -a is specified, all keychains are locked.
unlock-keychain [-u] [-p password] [keychain]
set-keychain-settings [-lu] [-t timeout] [keychain]
-l Lock keychain when the system sleeps.
-u Lock keychain after timeout interval.
-t timeout seconds (omitting := "no timeout").
set-keychain-password [-o oldpassword] [-p newpassword] [keychain]
-o oldpassword Old keychain password (if not provided, will prompt)
-p newpassword N ew keychain password (if not provided, will prompt)
create-keypair [-a alg] [-s size] [-f date] [-t date] [-d days] [-k keychain] [-A|-T appPath] [name] Create an asymmetric key pair.
-a alg Use alg as the algorithm, can be rsa, dh, dsa or fee (default rsa)
-s size keysize in bits (default 512)
-f date key valid from date (ex: "13/11/10 3:30pm")
-t date key valid to date
-d days key valid for the number of days specified from today
-k keychain
-A Allow any application to access this key without warning (insecure, not recommended!)
-T appPath application which may access this key (multiple -T are allowed)
add-generic-password [-a account] [-s service] [-w password] [options...] [keychain]
-a account -s service (required)
-c creator optional four-character code)
-C type optional four-character code)
-D kind default : "application password")
-G value generic attribute value (optional)
-j comment (optional)
-l label (if omitted, service name is used as default label)
-p password
-w password
-A Allow any application to access this item without warning (insecure, not recommended!)
-T appPath application which may access this item (multiple -T are allowed)
-U Update item if it already exists (if omitted, the item cannot already exist)
By default, the application which creates an item is trusted to access its data without warning. Remove this default access by explicitly specifying an empty app pathname: -T "".
If no keychain is specified, the password is added to the default keychain.
 
add-internet-password [-a account] [-s server]
[-w password]
[options...] [keychain]
-a account (required)
-s server (required)
-c creator
-C type
-d domain
-D kind default is "application password")
-j comment
-l label
-p path
-P port
-r protocol SecProtocolType, e.g. "http", "ftp ")
-t authenticationType a s a four-character SecAuthenticationType, default is "dflt")
-w password
-A Allow any application to access this item without warning (insecure, not recommended!)
-T appPath an application which may access this item (multiple -T are allowed)
-U Update item if it already exists (if omitted, the item cannot already exist)
By default, the application which creates an item is trusted to access its data without warning. You can remove this default access by explicitly specifying an empty app pathname: -T "". If no keychain is specified, the pass- word is added to the default keychain.
find-generic-password [-a account] [-s service] [-options...] [-g] [-keychain...]
-a account
-c creator
-C type
-D kind
-G value -j comment
-l label
-s service
-g Display the password for the item found
-w Display the password(only) for the item found
delete-generic-password [-a account] [-s service] [-options...] [-keychain...]
-a account -c creator -C type -D kind -G value
-j comment -l label -s service
delete-internet-password [-a account] [-s server] [options...] [keychain...]
-a account -c creator -C type -D kind
-j comment -l label -p path -P port -r protocol -s server
-t authenticationType
-d securityDomain
find-internet-password [-a account] [-s server] [options...] [-g] [keychain...]
-a account -c creator -C type -D kind
-j comment -l label -p path -P port -r protocol -s server
-t authenticationType
-g Display the password for the item found
-w Display the password(only) for the item found
-d securityDomain
find-certificate [-a] [-c name] [-e emailAddress] [-m] [-p] [-Z] [keychain...]
-a all matching certificates
-c name Match on name
-e emailAddress M atch on emailAddress
-m Show the email addresses in the certificate
-p Output certificate in pem format. Default is to dump the attributes and keychain the cert is in.
-Z Print SHA-1 hash of the certificate
add-certificates [-k keychain] file... The files must contain one DER encoded X509 certificate each.
-k keychain
-h Show a usage message for the specified command.
help Show all commands, or show usage for a command.

Examples:

                     Export all certificates from all keychains into a pem file called allcerts.pem.
            security> find-certificate -a -p > allcerts.pem

                     Export all certificates from all keychains with the email address me@foo.com into a pem file called certs.pem.
            security> find-certificate -a -e me@foo.com -p > certs.pem

                     Print the SHA-1 hash of every certificate in 'login.keychain' whose common name includes 'MyName'
            security> find-certificate -a -c MyName -Z login.keychain | grep ^SHA-1

     find-identity  [-p policy] [-s string] [-v] [keychain...]
            Find an identity (certificate + private key) satisfying a given policy. If no policy arguments are provided, the
            X.509 basic policy is assumed. If no keychain arguments are provided, the default search list is used.

            -p policy       to evaluate (multiple -p are allowed). Supported policies: basic, ssl-client, ssl-server, smime, eap, ipsec, ichat, codesigning, sys-default, sys-kerberos-kdc
            -s string       policy-specific string (e.g. a DNS hostname for SSL, or RFC822 email address for S/MIME)
            -v              Show valid identities only (default is to show all identities)

            

Examples

Display valid identities that can be used for SSL client authentication security> find-identity -v -p ssl-client Display identities for a SSL server running on the host 'www.domain.com' security> find-identity -p ssl-server -s www.domain.com Display identities that can be used to sign a message from 'user@domain.com' security> find-identity -p smime -s user@domain.com delete-certificate [-c name] [-Z hash] [-t] [keychain...] Delete a certificate from a keychain. If no keychain arguments are provided, the default search list is used. -c name Specify certificate by its common name -Z hash Specify certificate by its SHA-1 hash -t Also delete user trust settings for this certificate The certificate to be deleted must be uniquely specified either by a string found in its common name, or by its SHA-1 hash. set-identity-preference [-n] [-c identity] [-s service] [-u keyUsage] [-Z hash] [keychain...] Set the preferred identity to use for a service. -n no identity (clears existing preference for the given service) -c identity by common name of the certificate -s service service (may be a URL, RFC822 email address, DNS host, or other name) for which this identity is to be preferred -u keyUsage -Z hash by SHA-1 hash of certificate

The identity is located by searching the specified keychain(s) for a certificate whose common name contains the given identity string. If no keychains are specified to search, the default search list is used. Different identity preferences can be set for individual key usages. Differentiate between two identities which contain the same string by providing a SHA-1 hash of the certificate (in addition to, or instead of, the name.)

PARTIAL PATHS AND WILDCARDS

Starting with 10.6, it is possible to specify identity preferences on a per-domain basis, by using the wildcard character '*' as the leftmost component of the service name. Unlike SSL wildcards, an identity preference wildcard can match more than one subdomain. For example, an identity preference for the name "*.army.mil" will match "server1.subdomain1.army.mil" or "server2.subdomain2.army.mil". Likewise, a preference for "*.mil" will match both "server.army.mil" and "server.navy.mil". KEY USAGE CODES 0 - preference is in effect for all possible key usages (default) 1 - encryption only 2 - decryption only 4 - signing only 8 - signature verification only 16 - signing with message recovery only 32 - signature verification with message recovery only 64 - key wrapping only 128 - key unwrapping only 256 - key derivation only To specify more than one usage, add values together. get-identity-preference [-s service] [-u keyUsage] [-p] [-c] [-Z] -s service Specify service (may be a URL, RFC822 email address, DNS host, or other name) -u keyUsage Specify key usage (optional) -p Output in pem format -c common name -Z SHA-1 hash create-db [-aho0] [-g dl|cspdl] [-m mode] [name] -a Turn off autocommit -g dl|cspdl Use the AppleDL (default) or AppleCspDL -m mode Set the file permissions to mode. -o Force using openparams argument -0 Force using version 0 openparams Examples

            security> create-db -m 0644 test.db

            security> create-db -g cspdl -a test2.db

export [-k keychain] [-t type] [-f format] [-w] [-p format] [-P passphrase] [-o outfile] -k keychain from which item(s) will be exported. -t type Possible types are certs, allKeys, pubKeys, privKeys, identities, and all. The default is all. An identity consists of both a certificate and the correspond- ing private key. -f format of the exported data. Possible formats are openssl, bsafe, pkcs7, pkcs8, pkcs12, x509, openssh1, openssh2, and pemseq. The default is pemseq if more than one item is being exported. The default is openssl if one key is being exported. The default is x509 if one certifi- cate is being exported. -w private keys are to be wrapped on export. -p PEM armour is to be applied to the output data. -P passphrase wrapping passphrase immediately. The default is to obtain a secure passphrase via GUI. -o outfile Default is to write data to stdout. Examples

            security> export -k login.keychain -t certs -o /tmp/certs.pem

            security> export -k newcert.keychain -t identities -f pkcs12 -o /tmp/mycerts.p12
import inputfile [-k keychain] [-t type] [-f format] [-w] [-P passphrase] [options...] -k keychain into which item(s) will be imported. -t type Possible types are cert, pub, priv, session, cert, and agg. Pub, priv, and session refer to keys; agg is one of the aggregate types (pkcs12 and PEM sequence). The command can often figure out what item_type an item contains based in the filename and/or item_format. -f format of the exported data. Possible formats are openssl, bsafe, raw, pkcs7, pkcs8, pkcs12, x509, openssh1, openssh2, and pemseq. The command can often figure out what format an item is in based in the filename and/or item_type. -w private keys are wrapped and must be unwrapped on import. -x private keys are non-extractable after being imported. -P passphrase the unwrapping passphrase immediately. The default is to obtain a secure passphrase via GUI. -a attrName attrValue Specify optional extended attribute name and value. Can be used multiple times. This is only valid when importing keys. -A Allow any application to access the imported key without warning (insecure, not recommended!) -T appPath Specify an application which may access the imported key (multiple -T are allowed)
            Examples

            security> import /tmp/certs.pem -k

            security> import /tmp/mycerts.p12 -t agg -k newcert.keychain

            security> import /tmp/mycerts.p12 -f pkcs12 -k newcert.keychain
cms [-C|-D|-E|-S] [options...] Encode or decode CMS messages. -C create a CMS encrypted message -D decode a CMS message -E create a CMS enveloped message -S create a CMS signed message Decoding options: -c content use this detached content file -h level generate email headers with info about CMS message (output level >= 0) -n suppress output of content Encoding options: -r id,... create envelope for comma-delimited list of recipients, where id can be a certificate nickname or email address -G include a signing time attribute -H hash hash = MD2|MD4|MD5|SHA1|SHA256|SHA384|SHA512 (default: SHA1) -N nick use certificate named "nick" for signing -P include a SMIMECapabilities attribute -T do not include content in CMS message -Y nick include an EncryptionKeyPreference attribute with certificate (use "NONE" to omit) -Z hash find a certificate by subject key ID Common options: -e envelope specify envelope file (valid with -D or -E) -k keychain specify keychain to use -i infile use infile as source of data (default: stdin) -o outfile use outfile as destination of data (default: stdout) -p password use password as key db password (default: prompt) -s pass data a single byte at a time to CMS -u certusage set type of certificate usage (default: certUsageEmailSigner) -v print debugging information Cert usage codes: 0 - certUsageSSLClient 1 - certUsageSSLServer 2 - certUsageSSLServerWithStepUp 3 - certUsageSSLCA 4 - certUsageEmailSigner 5 - certUsageEmailRecipient 6 - certUsageObjectSigner 7 - certUsageUserCertImport 8 - certUsageVerifyCA 9 - certUsageProtectedObjectSigner 10 - certUsageStatusResponder 11 - certUsageAnyCA install-mds Install (or re-install) the Module Directory Services (MDS) database. This is a system tool which is not normally used by users. There are no options. add-trusted-cert [-d] [-r resultType] [-p policy] [-a appPath] [-s policyString] [-e allowedError] [-u keyUsage] [-k keychain] [-i settingsFileIn] [-o settingsFileOut] [-D] certFile Add certificate (in DER or PEM format) from certFile to per-user or local Admin Trust Settings. When modifying per-user Trust Settings, user authentication is required via an authentication dialog. When modifying admin Trust Settings, the process must be running as root, or admin authentication is required. Options: -d Add to admin cert store; default is user. -r resultType resultType = trustRoot|trustAsRoot|deny|unspecified; default is trustRoot. -p policy Specify policy constraint (ssl, smime, codeSign, IPSec, iChat, basic, swUpdate, pkgSign, pkinit- Client, pkinitServer, eap). -r resultType resultType = trustRoot|trustAsRoot|deny|unspecified; default is trustRoot. -a appPath Specify application constraint. -s policyString Specify policy-specific string. -e allowedError Specify allowed error (an integer value, or one of: certExpired, hostnameMismatch) -u keyUsage Specify key usage, an integer. -k keychain Specify keychain to which cert is added. -i settingsFileIn Input trust settings file; default is user domain. -o settingsFileOut Output trust settings file; default is user domain. -D Add default setting instead of per-cert setting. No certFile is specified when using this option Key usage codes: -1 - Any 1 - Sign 2 - Encrypt/Decrypt Data 4 - Encrypt/Decrypt Key 8 - Sign certificate 16 - Sign revocation 32 - Key exchange To specify more than one usage, add values together (except -1 - Any). Examples security> add-trusted-cert /tmp/cert.der security> add-trusted-cert -d .tmp/cert.der remove-trusted-cert [-d] [-D] certFile Remove certificate (in DER or PEM format) in certFile from per-user or local Admin Trust Settings. When modifying per-user Trust Settings, user authentication is required via an authentication dialog. When modifying admin Trust Settings, the process must be running as root, or admin authentication is required. Options: -d Remove from admin cert store; default is user. -D Remove Default Root Cert setting instead of an actual cert setting. No certFile is specified when using this option. dump-trust-settings [-s] [-d] Display Trust Settings. Options: -s Display trusted system certs; default is user. -d Display trusted admin certs; default is user. user-trust-settings-enable [-d] [-e] Display or manipulate user-level Trust Settings. With no arguments, shows the current state of the user-level Trust Settings enable. Otherwise enables or disables user-level Trust Settings. Options: -d Disable user-level Trust Settings. -e Enable user-level Trust Settings. trust-settings-export [-s] [-d] settings_file Export Trust Settings to the specified file. Options: -s Export system Trust Settings; default is user. -d Export admin Trust Settings; default is user. trust-settings-import [-d] settings_file Import Trust Settings from the specified file. When modifying per-user Trust Settings, user authentication is required via an authentication dialog. When modifying admin Trust Settings, the process must be running as root, or admin authentication is required. Options: -d Import admin Trust Settings; default is user. verify-cert [-c certFile] [-r rootCertFile] [-p policy] [-k keychain] [-d date] [-n] [-L] [-l] [-e emailAddress] [-s sslHost] [-q] Verify one or more certificates. Options: -c certFile Certificate to verify, in DER or PEM format. Can be specified more than once; leaf certificate has to be specified first. -r rootCertFile Root certificate, in DER or PEM format. Can be specified more than once. If not specified, the sys- tem anchor certificates are used. If one root certificate is specified, and zero (non-root) certifi- cates are specified, the root certificate is verified against itself. -p policy Specify verification policy (ssl, smime, codeSign, IPSec, iChat, basic, swUpdate, pkgSign, pkinit- Client, pkinitServer, eap, appleID, macappstore, timestamping). Default is basic. -k keychain Keychain to search for intermediate certs. Can be specified multiple times. Default is the current user's keychain search list. -d date Date to set for verification. Specified in the format of YYYY-MM-DD-hh:mm:ss (time optional). e.g: 2016-04-25-15:59:59 for April 25, 2016 at 3:59:59 pm in GMT -n Avoid searching any keychains. -L Use local certificates only. If an issuing CA certificate is missing, this option will avoid access- ing the network to fetch it. -l Specifies that the leaf certificate is a CA cert. By default, a leaf certificate with a Basic Con- straints extension with the CA bit set fails verification. -e emailAddress Specify email address for the smime policy. -s sslHost Specify SSL host name for the ssl policy. -q Quiet, no stdout or stderr. Examples security> verify-cert -c applestore0.cer -c applestore1.cer -p ssl -s store.apple.com security> verify-cert -r serverbasic.crt authorize [-updPiew] [right...] Authorize requested right(s). The extend-rights flag will be passed by default. Options: -u Allow user interaction. -p Allow returning partial rights. -d Destroy acquired rights. -P Pre-authorize rights only. -l Operate authorization in least privileged mode. -i Internalize authref passed on stdin. -e Externalize authref to stdout -w Wait while holding AuthorizationRef until stdout is closed. This will allow client to read external- ized AuthorizationRef from pipe. Examples security> security authorize -ud my-right Basic authorization of my-right. security> security -q authorize -uew my-right | security -q authorize -i my-right Authorizing a right and passing it to another command as a way to add authorization to shell scripts. authorizationdb read <right-name> authorizationdb write <right-name> [allow|deny|<rulename>] authorizationdb remove <right-name> Read/Modify authorization policy database. Without a rulename write will read a dictionary as a plist from stdin. Examples security> security authorizationdb read system.privilege.admin > /tmp/aewp-def Read definition of system.privilege.admin right. security> security authorizationdb write system.preferences < /tmp/aewp-def Set system.preferences to definition of system.privilege.admin right. security> security authorizationdb write system.preferences authenticate-admin Every change to preferences requires an Admin user to authenticate. execute-with-privileges <program> [args...] Execute tool with privileges. On success stdin will be read and forwarded to the tool. leaks [-cycles] [-nocontext] [-nostacks] [-exclude symbol] Run /usr/bin/leaks on this process. This can help find memory leaks after running certain commands. Options: -cycles Use a stricter algorithm (See leaks(1) for details). -nocontext Withhold the hex dumps of the leaked memory. -nostacks Don't show stack traces of leaked memory. -exclude symbol Ignore leaks called from symbol. error [<error code(s)...>] Display an error string for the given security-related error code. The error can be in decimal or hex, e.g. 1234 or 0x1234. Multiple errors can be separated by spaces. ENVIRONMENT MallocStackLogging When using the leaks command or the -l option it's probably a good idea to set this environment variable before security is started. Doing so will allow leaks to display symbolic backtraces. FILES ~/Library/Preferences/com.apple.security.plist Property list file containing the current user's default keychain and keychain search list. /Library/Preferences/com.apple.security.plist Property list file containing the system default keychain and keychain search list. This is used by processes started at boot time, or those requesting to use the system search domain, such as system daemons. /Library/Preferences/com.apple.security-common.plist Property list file containing the common keychain search list, which is appended to every user's search list and to the system search list. SEE ALSO certtool(1), leaks(1) HISTORY security was first introduced in Mac OS X version 10.3. BUGS security still needs more commands before it can be considered complete. In particular, it should someday supersede both the certtool and systemkeychain commands. Darwin March 1, 2012