]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - cups/tls-darwin.c
License change: Apache License, Version 2.0.
[thirdparty/cups.git] / cups / tls-darwin.c
index ff54b11ab625a5ed2e0444ac1ab4b2f9214aa988..89ac8c206a3e74ea15d225b8690a21dd9f805b6b 100644 (file)
@@ -1,18 +1,10 @@
 /*
- * "$Id$"
+ * TLS support code for CUPS on macOS.
  *
- * TLS support code for CUPS on OS X.
- *
- * Copyright 2007-2014 by Apple Inc.
+ * Copyright 2007-2017 by Apple Inc.
  * Copyright 1997-2007 by Easy Software Products, all rights reserved.
  *
- * These coded instructions, statements, and computer programs are the
- * property of Apple Inc. and are protected by Federal copyright
- * law.  Distribution and use rights are outlined in the file "LICENSE.txt"
- * which should have been included with this file.  If this file is
- * file is missing or damaged, see the license at "http://www.cups.org/".
- *
- * This file is subject to the Apple OS-Developed Software exception.
+ * Licensed under Apache License v2.0.  See the file "LICENSE" for more information.
  */
 
 /**** This file is included from tls.c ****/
 
 #include <spawn.h>
 
-extern char **environ;
+extern char **environ; /* @private@ */
 
 
 /*
- * Test define - set to 1 to use SSLSetEnabledCiphers.  Currently disabled (0)
- * because of <rdar://problem/18707430>.
+ * Constants, very secure stuff...
  */
 
-#define USE_SET_ENABLED_CIPHERS 0
+#define _CUPS_CDSA_PASSWORD    "42"    /* CUPS keychain password */
+#define _CUPS_CDSA_PASSLEN     2       /* Length of keychain password */
 
 
 /*
  * Local globals...
  */
 
-#ifdef HAVE_SECKEYCHAINOPEN
 static int             tls_auto_create = 0;
                                        /* Auto-create self-signed certs? */
 static char            *tls_common_name = NULL;
                                        /* Default common name */
+#ifdef HAVE_SECKEYCHAINOPEN
+static int             tls_cups_keychain = 0;
+                                       /* Opened the CUPS keychain? */
 static SecKeychainRef  tls_keychain = NULL;
                                        /* Server cert keychain */
+#else
+static SecIdentityRef  tls_selfsigned = NULL;
+                                       /* Temporary self-signed cert */
+#endif /* HAVE_SECKEYCHAINOPEN */
 static char            *tls_keypath = NULL;
                                        /* Server cert keychain path */
 static _cups_mutex_t   tls_mutex = _CUPS_MUTEX_INITIALIZER;
                                        /* Mutex for keychain/certs */
-static int             tls_options = 0;/* Options for TLS connections */
-#endif /* HAVE_SECKEYCHAINOPEN */
+static int             tls_options = -1,/* Options for TLS connections */
+                       tls_min_version = _HTTP_TLS_1_0,
+                       tls_max_version = _HTTP_TLS_MAX;
 
 
 /*
  * Local functions...
  */
 
-#ifdef HAVE_SECKEYCHAINOPEN
 static CFArrayRef      http_cdsa_copy_server(const char *common_name);
-#endif /* HAVE_SECKEYCHAINOPEN */
 static SecCertificateRef http_cdsa_create_credential(http_credential_t *credential);
+#ifdef HAVE_SECKEYCHAINOPEN
 static const char      *http_cdsa_default_path(char *buffer, size_t bufsize);
+static SecKeychainRef  http_cdsa_open_keychain(const char *path, char *filename, size_t filesize);
+static SecKeychainRef  http_cdsa_open_system_keychain(void);
+#endif /* HAVE_SECKEYCHAINOPEN */
 static OSStatus                http_cdsa_read(SSLConnectionRef connection, void *data, size_t *dataLength);
 static int             http_cdsa_set_credentials(http_t *http);
 static OSStatus                http_cdsa_write(SSLConnectionRef connection, const void *data, size_t *dataLength);
@@ -81,8 +82,7 @@ cupsMakeServerCredentials(
     const char **alt_names,            /* I - Subject Alternate Names */
     time_t     expiration_date)                /* I - Expiration date */
 {
-#if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE) && defined(HAVE_SECKEYCHAINOPEN)
-  char                 filename[1024]; /* Default keychain path */
+#if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
   int                  status = 0;     /* Return status */
   OSStatus             err;            /* Error code (if any) */
   CFStringRef          cfcommon_name = NULL;
@@ -92,22 +92,36 @@ cupsMakeServerCredentials(
                                        /* Public key */
                        privateKey = NULL;
                                        /* Private key */
+  SecCertificateRef    cert = NULL;    /* Self-signed certificate */
   CFMutableDictionaryRef keyParams = NULL;
                                        /* Key generation parameters */
 
 
   DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
 
+  (void)path;
   (void)num_alt_names;
   (void)alt_names;
   (void)expiration_date;
 
-  if (!path)
-    path = http_cdsa_default_path(filename, sizeof(filename));
+  if (path)
+  {
+    DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
+    return (0);
+  }
+
+  if (tls_selfsigned)
+  {
+    DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
+    return (1);
+  }
 
   cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
   if (!cfcommon_name)
+  {
+    DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
     goto cleanup;
+  }
 
  /*
   * Create a public/private key pair...
@@ -115,25 +129,35 @@ cupsMakeServerCredentials(
 
   keyParams = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
   if (!keyParams)
+  {
+    DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
     goto cleanup;
+  }
 
   CFDictionaryAddValue(keyParams, kSecAttrKeyType, kSecAttrKeyTypeRSA);
   CFDictionaryAddValue(keyParams, kSecAttrKeySizeInBits, CFSTR("2048"));
-  CFDictionaryAddValue(keyParams, kSecAttrLabel, CFSTR("CUPS Self-Signed Certificate"));
+  CFDictionaryAddValue(keyParams, kSecAttrLabel, cfcommon_name);
 
   err = SecKeyGeneratePair(keyParams, &publicKey, &privateKey);
   if (err != noErr)
+  {
+    DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err));
     goto cleanup;
+  }
 
  /*
   * Create a self-signed certificate using the public/private key pair...
   */
 
   CFIndex      usageInt = kSecKeyUsageAll;
-  CFNumberRef  usage = CFNumberCreate(alloc, kCFNumberCFIndexType, &usageInt);
-  CFDictionaryRef certParams = CFDictionaryCreateMutable(kCFAllocatorDefault,
-kSecCSRBasicContraintsPathLen, CFINT(0), kSecSubjectAltName, cfcommon_name, kSecCertificateKeyUsage, usage, NULL, NULL);
+  CFNumberRef  usage = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &usageInt);
+  CFIndex      lenInt = 0;
+  CFNumberRef  len = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &lenInt);
+  CFTypeRef certKeys[] = { kSecCSRBasicContraintsPathLen, kSecSubjectAltName, kSecCertificateKeyUsage };
+  CFTypeRef certValues[] = { len, cfcommon_name, usage };
+  CFDictionaryRef certParams = CFDictionaryCreate(kCFAllocatorDefault, certKeys, certValues, sizeof(certKeys) / sizeof(certKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
   CFRelease(usage);
+  CFRelease(len);
 
   const void   *ca_o[] = { kSecOidOrganization, CFSTR("") };
   const void   *ca_cn[] = { kSecOidCommonName, cfcommon_name };
@@ -145,17 +169,52 @@ kSecCSRBasicContraintsPathLen, CFINT(0), kSecSubjectAltName, cfcommon_name, kSec
   ca_dn_array[1] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_cn_dn, 1, NULL);
 
   CFArrayRef   subject = CFArrayCreate(kCFAllocatorDefault, ca_dn_array, 2, NULL);
-  SecCertificateRef cert = SecGenerateSelfSignedCertificate(subject, certParams, publicKey, privateKey);
+
+  cert = SecGenerateSelfSignedCertificate(subject, certParams, publicKey, privateKey);
+
   CFRelease(subject);
   CFRelease(certParams);
 
   if (!cert)
+  {
+    DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
     goto cleanup;
+  }
 
   ident = SecIdentityCreate(kCFAllocatorDefault, cert, privateKey);
 
   if (ident)
+  {
+    _cupsMutexLock(&tls_mutex);
+
+    if (tls_selfsigned)
+      CFRelease(ident);
+    else
+      tls_selfsigned = ident;
+
+    _cupsMutexLock(&tls_mutex);
+
+#  if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point  */
+    CFTypeRef itemKeys[] = { kSecClass, kSecAttrLabel, kSecValueRef };
+    CFTypeRef itemValues[] = { kSecClassIdentity, cfcommon_name, ident };
+    CFDictionaryRef itemAttrs = CFDictionaryCreate(kCFAllocatorDefault, itemKeys, itemValues, sizeof(itemKeys) / sizeof(itemKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
+
+    err = SecItemAdd(itemAttrs, NULL);
+    /* SecItemAdd consumes itemAttrs... */
+
+    CFRelease(ident);
+
+    if (err != noErr)
+    {
+      DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err));
+      goto cleanup;
+    }
+#  endif /* 0 */
+
     status = 1;
+  }
+  else
+    DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
 
   /*
    * Cleanup and return...
@@ -169,9 +228,6 @@ cleanup:
   if (keyParams)
     CFRelease(keyParams);
 
-  if (ident)
-    CFRelease(ident);
-
   if (cert)
     CFRelease(cert);
 
@@ -179,16 +235,18 @@ cleanup:
     CFRelease(publicKey);
 
   if (privateKey)
-    CFRelease(publicKey);
+    CFRelease(privateKey);
+
+  DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status));
 
   return (status);
 
-#else /* !(HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN) */
+#else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
   int          pid,                    /* Process ID of command */
                status,                 /* Status of command */
                i;                      /* Looping var */
   char         command[1024],          /* Command */
-               *argv[4],               /* Command-line arguments */
+               *argv[5],               /* Command-line arguments */
                *envp[1000],            /* Environment variables */
                days[32],               /* CERTTOOL_EXPIRATION_DAYS env var */
                keychain[1024],         /* Keychain argument */
@@ -197,7 +255,7 @@ cleanup:
   cups_file_t  *fp;                    /* Seed/info file */
 
 
-  DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
+  DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, (void *)alt_names, (int)expiration_date));
 
   (void)num_alt_names;
   (void)alt_names;
@@ -226,10 +284,10 @@ cleanup:
                  "CUPS Self-Signed Certificate\n"
                                        /* Enter key and certificate label */
                  "r\n"                 /* Generate RSA key pair */
-                 "2048\n"              /* Key size in bits */
+                 "2048\n"              /* 2048 bit encryption key */
                  "y\n"                 /* OK (y = yes) */
                  "b\n"                 /* Usage (b=signing/encryption) */
-                 "s\n"                 /* Sign with SHA1 */
+                 "2\n"                 /* Sign with SHA256 */
                  "y\n"                 /* OK (y = yes) */
                  "%s\n"                        /* Common name */
                  "\n"                  /* Country (default) */
@@ -292,7 +350,7 @@ cleanup:
  * Note: The server credentials are used by all threads in the running process.
  * This function is threadsafe.
  *
- * @since CUPS 2.0/OS X 10.10@
+ * @since CUPS 2.0/macOS 10.10@
  */
 
 int                                    /* O - 1 on success, 0 on failure */
@@ -304,17 +362,12 @@ cupsSetServerCredentials(
   DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
 
 #ifdef HAVE_SECKEYCHAINOPEN
-  char                 filename[1024]; /* Filename for keychain */
-  SecKeychainRef       keychain = NULL;/* Temporary keychain */
-
-
-  if (!path)
-    path = http_cdsa_default_path(filename, sizeof(filename));
+  char         filename[1024];         /* Keychain filename */
+  SecKeychainRef keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
 
-  if (SecKeychainOpen(path, &keychain) != noErr)
+  if (!keychain)
   {
-    /* TODO: Set cups last error string */
-    DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain, returning 0.");
+    DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain.");
     return (0);
   }
 
@@ -338,7 +391,7 @@ cupsSetServerCredentials(
   */
 
   tls_keychain    = keychain;
-  tls_keypath     = _cupsStrAlloc(path);
+  tls_keypath     = _cupsStrAlloc(filename);
   tls_auto_create = auto_create;
   tls_common_name = _cupsStrAlloc(common_name);
 
@@ -348,8 +401,16 @@ cupsSetServerCredentials(
   return (1);
 
 #else
-  DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
-  return (0);
+  if (path)
+  {
+    DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
+    return (0);
+  }
+
+  tls_auto_create = auto_create;
+  tls_common_name = _cupsStrAlloc(common_name);
+
+  return (1);
 #endif /* HAVE_SECKEYCHAINOPEN */
 }
 
@@ -358,7 +419,7 @@ cupsSetServerCredentials(
  * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
  *                           an encrypted connection.
  *
- * @since CUPS 1.5/OS X 10.7@
+ * @since CUPS 1.5/macOS 10.7@
  */
 
 int                                    /* O - Status of call (0 = success) */
@@ -374,7 +435,7 @@ httpCopyCredentials(
   int                  i;              /* Looping var */
 
 
-  DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
+  DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http, (void *)credentials));
 
   if (credentials)
     *credentials = NULL;
@@ -461,7 +522,7 @@ _httpCreateCredentials(
 /*
  * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
  *
- * @since CUPS 2.0/OS X 10.10@
+ * @since CUPS 2.0/macOS 10.10@
  */
 
 int                                    /* O - 1 if valid, 0 otherwise */
@@ -524,7 +585,7 @@ httpCredentialsAreValidForName(
 /*
  * 'httpCredentialsGetTrust()' - Return the trust of credentials.
  *
- * @since CUPS 2.0/OS X 10.10@
+ * @since CUPS 2.0/macOS 10.10@
  */
 
 http_trust_t                           /* O - Level of trust */
@@ -541,10 +602,19 @@ httpCredentialsGetTrust(
 
 
   if (!common_name)
+  {
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No common name specified."), 1);
     return (HTTP_TRUST_UNKNOWN);
+  }
 
   if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
+  {
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create credentials from array."), 1);
     return (HTTP_TRUST_UNKNOWN);
+  }
+
+  if (cg->any_root < 0)
+    _cupsSetDefaults();
 
  /*
   * Look this common name up in the default keychains...
@@ -567,14 +637,34 @@ httpCredentialsGetTrust(
       * credentials and allow if the new ones have a later expiration...
       */
 
-      if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds) ||
-          !httpCredentialsAreValidForName(credentials, common_name))
+      if (!cg->trust_first)
       {
        /*
-        * Either the new credentials are not newly issued, or the common name
-       * does not match the issued certificate...
+        * Do not trust certificates on first use...
        */
 
+        _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
+
+        trust = HTTP_TRUST_INVALID;
+      }
+      else if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds))
+      {
+       /*
+        * The new credentials are not newly issued...
+       */
+
+        _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are older than stored credentials."), 1);
+
+        trust = HTTP_TRUST_INVALID;
+      }
+      else if (!httpCredentialsAreValidForName(credentials, common_name))
+      {
+       /*
+        * The common name does not match the issued certificate...
+       */
+
+        _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are not valid for name."), 1);
+
         trust = HTTP_TRUST_INVALID;
       }
       else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
@@ -592,12 +682,65 @@ httpCredentialsGetTrust(
     httpFreeCredentials(tcreds);
   }
   else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
+  {
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No stored credentials, not valid for name."), 1);
     trust = HTTP_TRUST_INVALID;
+  }
+  else if (!cg->trust_first)
+  {
+   /*
+    * See if we have a site CA certificate we can compare...
+    */
+
+    if (!httpLoadCredentials(NULL, &tcreds, "site"))
+    {
+      if (cupsArrayCount(credentials) != (cupsArrayCount(tcreds) + 1))
+      {
+       /*
+        * Certificate isn't directly generated from the CA cert...
+       */
+
+        trust = HTTP_TRUST_INVALID;
+      }
+      else
+      {
+       /*
+        * Do a tail comparison of the two certificates...
+       */
+
+        http_credential_t      *a, *b;         /* Certificates */
+
+        for (a = (http_credential_t *)cupsArrayFirst(tcreds), b = (http_credential_t *)cupsArrayIndex(credentials, 1);
+            a && b;
+            a = (http_credential_t *)cupsArrayNext(tcreds), b = (http_credential_t *)cupsArrayNext(credentials))
+         if (a->datalen != b->datalen || memcmp(a->data, b->data, a->datalen))
+           break;
+
+        if (a || b)
+         trust = HTTP_TRUST_INVALID;
+      }
 
-  if (!cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
+      if (trust != HTTP_TRUST_OK)
+       _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials do not validate against site CA certificate."), 1);
+    }
+    else
+    {
+      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
+      trust = HTTP_TRUST_INVALID;
+    }
+  }
+
+  if (trust == HTTP_TRUST_OK && !cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
+  {
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials have expired."), 1);
     trust = HTTP_TRUST_EXPIRED;
-  else if (!cg->any_root && cupsArrayCount(credentials) == 1)
+  }
+
+  if (trust == HTTP_TRUST_OK && !cg->any_root && cupsArrayCount(credentials) == 1)
+  {
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Self-signed credentials are blocked."), 1);
     trust = HTTP_TRUST_INVALID;
+  }
 
   CFRelease(secCert);
 
@@ -608,7 +751,7 @@ httpCredentialsGetTrust(
 /*
  * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
  *
- * @since CUPS 2.0/OS X 10.10@
+ * @since CUPS 2.0/macOS 10.10@
  */
 
 time_t                                 /* O - Expiration date of credentials */
@@ -633,7 +776,7 @@ httpCredentialsGetExpiration(
 /*
  * 'httpCredentialsString()' - Return a string representing the credentials.
  *
- * @since CUPS 2.0/OS X 10.10@
+ * @since CUPS 2.0/macOS 10.10@
  */
 
 size_t                                 /* O - Total size of credentials string */
@@ -646,7 +789,7 @@ httpCredentialsString(
   SecCertificateRef    secCert;        /* Certificate reference */
 
 
-  DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
+  DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", (void *)credentials, (void *)buffer, CUPS_LLCAST bufsize));
 
   if (!buffer)
     return (0);
@@ -660,7 +803,6 @@ httpCredentialsString(
     CFStringRef                cf_name;        /* CF common name string */
     char               name[256];      /* Common name associated with cert */
     time_t             expiration;     /* Expiration date of cert */
-    _cups_md5_state_t  md5_state;      /* MD5 state */
     unsigned char      md5_digest[16]; /* MD5 result */
 
     if ((cf_name = SecCertificateCopySubjectSummary(secCert)) != NULL)
@@ -673,9 +815,7 @@ httpCredentialsString(
 
     expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
 
-    _cupsMD5Init(&md5_state);
-    _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
-    _cupsMD5Finish(&md5_state, md5_digest);
+    cupsHashData("md5", first->data, first->datalen, md5_digest, sizeof(md5_digest));
 
     snprintf(buffer, bufsize, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, httpGetDateString(expiration), md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
 
@@ -715,33 +855,41 @@ httpLoadCredentials(
     cups_array_t **credentials,                /* IO - Credentials */
     const char   *common_name)         /* I  - Common name for credentials */
 {
-#ifdef HAVE_SECKEYCHAINOPEN
   OSStatus             err;            /* Error info */
+#ifdef HAVE_SECKEYCHAINOPEN
   char                 filename[1024]; /* Filename for keychain */
-  SecKeychainRef       keychain = NULL;/* Keychain reference */
-  SecIdentitySearchRef search = NULL;  /* Search reference */
+  SecKeychainRef       keychain = NULL,/* Keychain reference */
+                       syschain = NULL;/* System keychain */
+  CFArrayRef           list;           /* Keychain list */
+#endif /* HAVE_SECKEYCHAINOPEN */
   SecCertificateRef    cert = NULL;    /* Certificate */
   CFDataRef            data;           /* Certificate data */
   SecPolicyRef         policy = NULL;  /* Policy ref */
   CFStringRef          cfcommon_name = NULL;
                                        /* Server name */
   CFMutableDictionaryRef query = NULL; /* Query qualifiers */
-  CFArrayRef           list = NULL;    /* Keychain list */
 
 
-  DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
+  DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
 
   if (!credentials)
     return (-1);
 
   *credentials = NULL;
 
-  if (!path)
-    path = http_cdsa_default_path(filename, sizeof(filename));
+#ifdef HAVE_SECKEYCHAINOPEN
+  keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
 
-  if ((err = SecKeychainOpen(path, &keychain)) != noErr)
+  if (!keychain)
     goto cleanup;
 
+  syschain = http_cdsa_open_system_keychain();
+
+#else
+  if (path)
+    return (-1);
+#endif /* HAVE_SECKEYCHAINOPEN */
+
   cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
 
   policy = SecPolicyCreateSSL(1, cfcommon_name);
@@ -755,15 +903,23 @@ httpLoadCredentials(
   if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
     goto cleanup;
 
-  list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
-
   CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
   CFDictionaryAddValue(query, kSecMatchPolicy, policy);
   CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
   CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
-  CFDictionaryAddValue(query, kSecMatchSearchList, list);
 
+#ifdef HAVE_SECKEYCHAINOPEN
+  if (syschain)
+  {
+    const void *values[2] = { syschain, keychain };
+
+    list = CFArrayCreate(kCFAllocatorDefault, (const void **)values, 2, &kCFTypeArrayCallBacks);
+  }
+  else
+    list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
+  CFDictionaryAddValue(query, kSecMatchSearchList, list);
   CFRelease(list);
+#endif /* HAVE_SECKEYCHAINOPEN */
 
   err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
 
@@ -784,10 +940,13 @@ httpLoadCredentials(
 
   cleanup :
 
+#ifdef HAVE_SECKEYCHAINOPEN
   if (keychain)
     CFRelease(keychain);
-  if (search)
-    CFRelease(search);
+
+  if (syschain)
+    CFRelease(syschain);
+#endif /* HAVE_SECKEYCHAINOPEN */
   if (cert)
     CFRelease(cert);
   if (policy)
@@ -798,14 +957,6 @@ httpLoadCredentials(
   DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
 
   return (*credentials ? 0 : -1);
-
-#else
-  (void)path;
-  (void)credentials;
-  (void)common_name;
-
-  return (-1);
-#endif /* HAVE_SECKEYCHAINOPEN */
 }
 
 
@@ -821,18 +972,18 @@ httpSaveCredentials(
     cups_array_t *credentials,         /* I - Credentials */
     const char   *common_name)         /* I - Common name for credentials */
 {
-#ifdef HAVE_SECKEYCHAINOPEN
   int                  ret = -1;       /* Return value */
   OSStatus             err;            /* Error info */
+#ifdef HAVE_SECKEYCHAINOPEN
   char                 filename[1024]; /* Filename for keychain */
   SecKeychainRef       keychain = NULL;/* Keychain reference */
-  SecIdentitySearchRef search = NULL;  /* Search reference */
+  CFArrayRef           list;           /* Keychain list */
+#endif /* HAVE_SECKEYCHAINOPEN */
   SecCertificateRef    cert = NULL;    /* Certificate */
   CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
-  CFArrayRef           list = NULL;    /* Keychain list */
 
 
-  DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
+  DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
   if (!credentials)
     goto cleanup;
 
@@ -848,20 +999,16 @@ httpSaveCredentials(
     goto cleanup;
   }
 
-  if (!path)
-    path = http_cdsa_default_path(filename, sizeof(filename));
+#ifdef HAVE_SECKEYCHAINOPEN
+  keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
 
-  if ((err = SecKeychainOpen(path, &keychain)) != noErr)
-  {
-    DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err));
+  if (!keychain)
     goto cleanup;
-  }
 
-  if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
-  {
-    DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
-    goto cleanup;
-  }
+#else
+  if (path)
+    return (-1);
+#endif /* HAVE_SECKEYCHAINOPEN */
 
   if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
   {
@@ -871,7 +1018,16 @@ httpSaveCredentials(
 
   CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
   CFDictionaryAddValue(attrs, kSecValueRef, cert);
+
+#ifdef HAVE_SECKEYCHAINOPEN
+  if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
+  {
+    DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
+    goto cleanup;
+  }
   CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
+  CFRelease(list);
+#endif /* HAVE_SECKEYCHAINOPEN */
 
   /* Note: SecItemAdd consumes "attrs"... */
   err = SecItemAdd(attrs, NULL);
@@ -879,26 +1035,16 @@ httpSaveCredentials(
 
   cleanup :
 
-  if (list)
-    CFRelease(list);
+#ifdef HAVE_SECKEYCHAINOPEN
   if (keychain)
     CFRelease(keychain);
-  if (search)
-    CFRelease(search);
+#endif /* HAVE_SECKEYCHAINOPEN */
   if (cert)
     CFRelease(cert);
 
   DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
 
   return (ret);
-
-#else
-  (void)path;
-  (void)credentials;
-  (void)common_name;
-
-  return (-1);
-#endif /* HAVE_SECKEYCHAINOPEN */
 }
 
 
@@ -986,9 +1132,16 @@ _httpTLSRead(http_t *http,                /* I - HTTP connection */
  */
 
 void
-_httpTLSSetOptions(int options)                /* I - Options */
+_httpTLSSetOptions(int options,                /* I - Options */
+                   int min_version,    /* I - Minimum TLS version */
+                   int max_version)    /* I - Maximum TLS version */
 {
-  tls_options = options;
+  if (!(options & _HTTP_TLS_SET_DEFAULT) || tls_options < 0)
+  {
+    tls_options     = options;
+    tls_min_version = min_version;
+    tls_max_version = max_version;
+  }
 }
 
 
@@ -1014,13 +1167,17 @@ _httpTLSStart(http_t *http)             /* I - HTTP connection */
   http_credential_t    *credential;    /* Credential data */
 
 
-  DEBUG_printf(("7_httpTLSStart(http=%p)", http));
+  DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http));
+
+  if (tls_options < 0)
+  {
+    DEBUG_puts("4_httpTLSStart: Setting defaults.");
+    _cupsSetDefaults();
+    DEBUG_printf(("4_httpTLSStart: tls_options=%x, tls_min_version=%d, tls_max_version=%d", tls_options, tls_min_version, tls_max_version));
+  }
 
 #ifdef HAVE_SECKEYCHAINOPEN
   if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
-#else
-  if (http->mode == _HTTP_MODE_SERVER)
-#endif /* HAVE_SECKEYCHAINOPEN */
   {
     DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
     http->error  = errno = EINVAL;
@@ -1029,6 +1186,7 @@ _httpTLSStart(http_t *http)               /* I - HTTP connection */
 
     return (-1);
   }
+#endif /* HAVE_SECKEYCHAINOPEN */
 
   if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
   {
@@ -1058,11 +1216,27 @@ _httpTLSStart(http_t *http)             /* I - HTTP connection */
 
   if (!error)
   {
-    error = SSLSetProtocolVersionMin(http->tls, (tls_options & _HTTP_TLS_ALLOW_SSL3) ? kSSLProtocol3 : kTLSProtocol1);
-    DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin, error=%d", (int)error));
+    static const SSLProtocol protocols[] =     /* Min/max protocol versions */
+    {
+      kSSLProtocol3,
+      kTLSProtocol1,
+      kTLSProtocol11,
+      kTLSProtocol12,
+      kTLSProtocol13,
+      kTLSProtocolMaxSupported
+    };
+
+    error = SSLSetProtocolVersionMin(http->tls, protocols[tls_min_version]);
+    DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", protocols[tls_min_version], (int)error));
+
+    if (!error)
+    {
+      error = SSLSetProtocolVersionMax(http->tls, protocols[tls_max_version]);
+      DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMax(%d), error=%d", protocols[tls_max_version], (int)error));
+    }
   }
 
-#  if USE_SET_ENABLED_CIPHERS
+#  if HAVE_SSLSETENABLEDCIPHERS
   if (!error)
   {
     SSLCipherSuite     supported[100]; /* Supported cipher suites */
@@ -1127,6 +1301,7 @@ _httpTLSStart(http_t *http)               /* I - HTTP connection */
          case TLS_RSA_PSK_WITH_NULL_SHA256 :
          case TLS_RSA_PSK_WITH_NULL_SHA384 :
          case SSL_RSA_WITH_DES_CBC_MD5 :
+             DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported[i]));
              break;
 
           /* RC4 cipher suites that should only be used as a last resort */
@@ -1141,9 +1316,76 @@ _httpTLSStart(http_t *http)              /* I - HTTP connection */
          case TLS_RSA_PSK_WITH_RC4_128_SHA :
              if (tls_options & _HTTP_TLS_ALLOW_RC4)
                enabled[num_enabled ++] = supported[i];
+             else
+               DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported[i]));
              break;
 
-          /* Anything else we'll assume is secure */
+          /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
+          case TLS_DH_DSS_WITH_AES_128_CBC_SHA :
+          case TLS_DH_RSA_WITH_AES_128_CBC_SHA :
+          case TLS_DHE_DSS_WITH_AES_128_CBC_SHA :
+          case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
+          case TLS_DH_DSS_WITH_AES_256_CBC_SHA :
+          case TLS_DH_RSA_WITH_AES_256_CBC_SHA :
+          case TLS_DHE_DSS_WITH_AES_256_CBC_SHA :
+          case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
+          case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA :
+          case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA :
+          case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA :
+          case TLS_DH_DSS_WITH_AES_128_CBC_SHA256 :
+          case TLS_DH_RSA_WITH_AES_128_CBC_SHA256 :
+          case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 :
+          case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
+          case TLS_DH_DSS_WITH_AES_256_CBC_SHA256 :
+          case TLS_DH_RSA_WITH_AES_256_CBC_SHA256 :
+          case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 :
+          case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
+          case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA :
+          case TLS_DHE_PSK_WITH_AES_128_CBC_SHA :
+          case TLS_DHE_PSK_WITH_AES_256_CBC_SHA :
+          case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
+          case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
+             if (tls_options & _HTTP_TLS_DENY_CBC)
+             {
+               DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported[i]));
+               break;
+             }
+
+//          case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
+//          case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
+          case TLS_DH_RSA_WITH_AES_128_GCM_SHA256 :
+          case TLS_DH_RSA_WITH_AES_256_GCM_SHA384 :
+//          case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
+//          case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
+          case TLS_DH_DSS_WITH_AES_128_GCM_SHA256 :
+          case TLS_DH_DSS_WITH_AES_256_GCM_SHA384 :
+          case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
+          case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
+              if (tls_options & _HTTP_TLS_ALLOW_DH)
+               enabled[num_enabled ++] = supported[i];
+             else
+               DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported[i]));
+              break;
+
+          case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
+          case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 :
+          case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 :
+          case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 :
+          case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 :
+          case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 :
+          case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 :
+          case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 :
+          case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 :
+          case TLS_RSA_WITH_3DES_EDE_CBC_SHA :
+          case TLS_RSA_WITH_AES_128_CBC_SHA :
+          case TLS_RSA_WITH_AES_256_CBC_SHA :
+              if (tls_options & _HTTP_TLS_DENY_CBC)
+             {
+               DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported[i]));
+               break;
+             }
+
+          /* Anything else we'll assume is "secure" */
           default :
              enabled[num_enabled ++] = supported[i];
              break;
@@ -1154,7 +1396,7 @@ _httpTLSStart(http_t *http)               /* I - HTTP connection */
       error = SSLSetEnabledCiphers(http->tls, enabled, num_enabled);
     }
   }
-#endif /* USE_SET_ENABLED_CIPHERS */
+#endif /* HAVE_SSLSETENABLEDCIPHERS */
 
   if (!error && http->mode == _HTTP_MODE_CLIENT)
   {
@@ -1214,7 +1456,6 @@ _httpTLSStart(http_t *http)               /* I - HTTP connection */
       }
     }
 
-#ifdef HAVE_SECKEYCHAINOPEN
     if (isdigit(hostname[0] & 255) || hostname[0] == '[')
       hostname[0] = '\0';              /* Don't allow numeric addresses */
 
@@ -1239,7 +1480,6 @@ _httpTLSStart(http_t *http)               /* I - HTTP connection */
 
       http->tls_credentials = http_cdsa_copy_server(hostname[0] ? hostname : tls_common_name);
     }
-#endif /* HAVE_SECKEYCHAINOPEN */
 
     if (!http->tls_credentials)
     {
@@ -1256,7 +1496,7 @@ _httpTLSStart(http_t *http)               /* I - HTTP connection */
     DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
   }
 
-  DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http->tls_credentials));
+  DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http->tls_credentials));
 
  /*
   * Let the server know which hostname/domain we are trying to connect to
@@ -1478,7 +1718,7 @@ _httpTLSWrite(http_t     *http,           /* I - HTTP connection */
   size_t       processed;              /* Number of bytes processed */
 
 
-  DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http, buf, len));
+  DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http, (void *)buf, len));
 
   error = SSLWrite(http->tls, buf, (size_t)len, &processed);
 
@@ -1520,7 +1760,6 @@ _httpTLSWrite(http_t     *http,           /* I - HTTP connection */
 }
 
 
-#ifdef HAVE_SECKEYCHAINOPEN
 /*
  * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
  */
@@ -1529,8 +1768,8 @@ static CFArrayRef                 /* O - Array of certificates or NULL */
 http_cdsa_copy_server(
     const char *common_name)           /* I - Server's hostname */
 {
+#ifdef HAVE_SECKEYCHAINOPEN
   OSStatus             err;            /* Error info */
-  SecIdentitySearchRef search = NULL;  /* Search reference */
   SecIdentityRef       identity = NULL;/* Identity */
   CFArrayRef           certificates = NULL;
                                        /* Certificate array */
@@ -1539,61 +1778,100 @@ http_cdsa_copy_server(
                                        /* Server name */
   CFMutableDictionaryRef query = NULL; /* Query qualifiers */
   CFArrayRef           list = NULL;    /* Keychain list */
+  SecKeychainRef       syschain = NULL;/* System keychain */
+  SecKeychainStatus    status = 0;     /* Keychain status */
 
 
+  DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name));
+
   cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
 
   policy = SecPolicyCreateSSL(1, cfcommon_name);
 
-  if (cfcommon_name)
-    CFRelease(cfcommon_name);
-
   if (!policy)
+  {
+    DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
     goto cleanup;
+  }
 
   if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
+  {
+    DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
     goto cleanup;
+  }
 
   _cupsMutexLock(&tls_mutex);
 
-  list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
+  err = SecKeychainGetStatus(tls_keychain, &status);
+
+  if (err == noErr && !(status & kSecUnlockStateStatus) && tls_cups_keychain)
+    SecKeychainUnlock(tls_keychain, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, TRUE);
 
   CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
   CFDictionaryAddValue(query, kSecMatchPolicy, policy);
   CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
   CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
-  CFDictionaryAddValue(query, kSecMatchSearchList, list);
 
+  syschain = http_cdsa_open_system_keychain();
+
+  if (syschain)
+  {
+    const void *values[2] = { syschain, tls_keychain };
+
+    list = CFArrayCreate(kCFAllocatorDefault, (const void **)values, 2, &kCFTypeArrayCallBacks);
+  }
+  else
+    list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
+
+  CFDictionaryAddValue(query, kSecMatchSearchList, list);
   CFRelease(list);
 
   err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
 
   _cupsMutexUnlock(&tls_mutex);
 
-  if (err)
+  if (err != noErr)
+  {
+    DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err));
     goto cleanup;
+  }
 
   if (CFGetTypeID(identity) != SecIdentityGetTypeID())
+  {
+    DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
     goto cleanup;
+  }
 
   if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
+  {
+    DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
     goto cleanup;
+  }
 
   cleanup :
 
-  if (search)
-    CFRelease(search);
+  if (syschain)
+    CFRelease(syschain);
   if (identity)
     CFRelease(identity);
-
   if (policy)
     CFRelease(policy);
+  if (cfcommon_name)
+    CFRelease(cfcommon_name);
   if (query)
     CFRelease(query);
 
+  DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates));
+
   return (certificates);
-}
+#else
+
+  if (!tls_selfsigned)
+    return (NULL);
+
+  return (CFArrayCreate(NULL, (const void **)&tls_selfsigned, 1, &kCFTypeArrayCallBacks));
 #endif /* HAVE_SECKEYCHAINOPEN */
+}
 
 
 /*
@@ -1611,6 +1889,7 @@ http_cdsa_create_credential(
 }
 
 
+#ifdef HAVE_SECKEYCHAINOPEN
 /*
  * 'http_cdsa_default_path()' - Get the default keychain path.
  */
@@ -1622,10 +1901,16 @@ http_cdsa_default_path(char   *buffer,  /* I - Path buffer */
   const char *home = getenv("HOME");   /* HOME environment variable */
 
 
+ /*
+  * Determine the default keychain path.  Note that the login and system
+  * keychains are no longer accessible to user applications starting in macOS
+  * 10.11.4 (!), so we need to create our own keychain just for CUPS.
+  */
+
   if (getuid() && home)
-    snprintf(buffer, bufsize, "%s/Library/Keychains/login.keychain", home);
+    snprintf(buffer, bufsize, "%s/.cups/ssl.keychain", home);
   else
-    strlcpy(buffer, "/Library/Keychains/System.keychain", bufsize);
+    strlcpy(buffer, "/etc/cups/ssl.keychain", bufsize);
 
   DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer));
 
@@ -1633,6 +1918,156 @@ http_cdsa_default_path(char   *buffer,  /* I - Path buffer */
 }
 
 
+/*
+ * 'http_cdsa_open_keychain()' - Open (or create) a keychain.
+ */
+
+static SecKeychainRef                  /* O - Keychain or NULL */
+http_cdsa_open_keychain(
+    const char *path,                  /* I - Path to keychain */
+    char       *filename,              /* I - Keychain filename */
+    size_t     filesize)               /* I - Size of filename buffer */
+{
+  SecKeychainRef       keychain = NULL;/* Temporary keychain */
+  OSStatus             err;            /* Error code */
+  Boolean              interaction;    /* Interaction allowed? */
+  SecKeychainStatus    status = 0;     /* Keychain status */
+
+
+ /*
+  * Get the keychain filename...
+  */
+
+  if (!path)
+  {
+    path = http_cdsa_default_path(filename, filesize);
+    tls_cups_keychain = 1;
+  }
+  else
+  {
+    strlcpy(filename, path, filesize);
+    tls_cups_keychain = 0;
+  }
+
+ /*
+  * Save the interaction setting and disable while we open the keychain...
+  */
+
+  SecKeychainGetUserInteractionAllowed(&interaction);
+  SecKeychainSetUserInteractionAllowed(FALSE);
+
+  if (access(path, R_OK) && tls_cups_keychain)
+  {
+   /*
+    * Create a new keychain at the given path...
+    */
+
+    err = SecKeychainCreate(path, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, FALSE, NULL, &keychain);
+  }
+  else
+  {
+   /*
+    * Open the existing keychain and unlock as needed...
+    */
+
+    err = SecKeychainOpen(path, &keychain);
+
+    if (err == noErr)
+      err = SecKeychainGetStatus(keychain, &status);
+
+    if (err == noErr && !(status & kSecUnlockStateStatus) && tls_cups_keychain)
+      err = SecKeychainUnlock(keychain, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, TRUE);
+  }
+
+ /*
+  * Restore interaction setting...
+  */
+
+  SecKeychainSetUserInteractionAllowed(interaction);
+
+ /*
+  * Release the keychain if we had any errors...
+  */
+
+  if (err != noErr)
+  {
+    /* TODO: Set cups last error string */
+    DEBUG_printf(("4http_cdsa_open_keychain: Unable to open keychain (%d), returning NULL.", (int)err));
+
+    if (keychain)
+    {
+      CFRelease(keychain);
+      keychain = NULL;
+    }
+  }
+
+ /*
+  * Return the keychain or NULL...
+  */
+
+  return (keychain);
+}
+
+
+/*
+ * 'http_cdsa_open_system_keychain()' - Open the System keychain.
+ */
+
+static SecKeychainRef
+http_cdsa_open_system_keychain(void)
+{
+  SecKeychainRef       keychain = NULL;/* Temporary keychain */
+  OSStatus             err;            /* Error code */
+  Boolean              interaction;    /* Interaction allowed? */
+  SecKeychainStatus    status = 0;     /* Keychain status */
+
+
+ /*
+  * Save the interaction setting and disable while we open the keychain...
+  */
+
+  SecKeychainGetUserInteractionAllowed(&interaction);
+  SecKeychainSetUserInteractionAllowed(TRUE);
+
+  err = SecKeychainOpen("/Library/Keychains/System.keychain", &keychain);
+
+  if (err == noErr)
+    err = SecKeychainGetStatus(keychain, &status);
+
+  if (err == noErr && !(status & kSecUnlockStateStatus))
+    err = errSecInteractionNotAllowed;
+
+ /*
+  * Restore interaction setting...
+  */
+
+  SecKeychainSetUserInteractionAllowed(interaction);
+
+ /*
+  * Release the keychain if we had any errors...
+  */
+
+  if (err != noErr)
+  {
+    /* TODO: Set cups last error string */
+    DEBUG_printf(("4http_cdsa_open_system_keychain: Unable to open keychain (%d), returning NULL.", (int)err));
+
+    if (keychain)
+    {
+      CFRelease(keychain);
+      keychain = NULL;
+    }
+  }
+
+ /*
+  * Return the keychain or NULL...
+  */
+
+  return (keychain);
+}
+#endif /* HAVE_SECKEYCHAINOPEN */
+
+
 /*
  * 'http_cdsa_read()' - Read function for the CDSA library.
  */
@@ -1710,7 +2145,7 @@ http_cdsa_set_credentials(http_t *http)   /* I - HTTP connection */
                                        /* TLS credentials */
 
 
-  DEBUG_printf(("7http_tls_set_credentials(%p)", http));
+  DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http));
 
  /*
   * Prefer connection specific credentials...
@@ -1776,8 +2211,3 @@ http_cdsa_write(
 
   return (result);
 }
-
-
-/*
- * End of "$Id$".
- */