2 * TLS support code for CUPS on macOS.
4 * Copyright 2007-2016 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
16 /**** This file is included from tls.c ****/
19 * Include necessary headers...
24 extern char **environ;
28 * Constants, very secure stuff...
31 #define _CUPS_CDSA_PASSWORD "42" /* CUPS keychain password */
32 #define _CUPS_CDSA_PASSLEN 2 /* Length of keychain password */
39 static int tls_auto_create = 0;
40 /* Auto-create self-signed certs? */
41 static char *tls_common_name = NULL;
42 /* Default common name */
43 #ifdef HAVE_SECKEYCHAINOPEN
44 static SecKeychainRef tls_keychain = NULL;
45 /* Server cert keychain */
47 static SecIdentityRef tls_selfsigned = NULL;
48 /* Temporary self-signed cert */
49 #endif /* HAVE_SECKEYCHAINOPEN */
50 static char *tls_keypath = NULL;
51 /* Server cert keychain path */
52 static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER;
53 /* Mutex for keychain/certs */
54 static int tls_options = -1;/* Options for TLS connections */
61 static CFArrayRef http_cdsa_copy_server(const char *common_name);
62 static SecCertificateRef http_cdsa_create_credential(http_credential_t *credential);
63 #ifdef HAVE_SECKEYCHAINOPEN
64 static const char *http_cdsa_default_path(char *buffer, size_t bufsize);
65 static SecKeychainRef http_cdsa_open_keychain(const char *path, char *filename, size_t filesize);
66 static SecKeychainRef http_cdsa_open_system_keychain(void);
67 #endif /* HAVE_SECKEYCHAINOPEN */
68 static OSStatus http_cdsa_read(SSLConnectionRef connection, void *data, size_t *dataLength);
69 static int http_cdsa_set_credentials(http_t *http);
70 static OSStatus http_cdsa_write(SSLConnectionRef connection, const void *data, size_t *dataLength);
74 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
76 * @since CUPS 2.0/OS 10.10@
79 int /* O - 1 on success, 0 on failure */
80 cupsMakeServerCredentials(
81 const char *path, /* I - Keychain path or @code NULL@ for default */
82 const char *common_name, /* I - Common name */
83 int num_alt_names, /* I - Number of subject alternate names */
84 const char **alt_names, /* I - Subject Alternate Names */
85 time_t expiration_date) /* I - Expiration date */
87 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
88 int status = 0; /* Return status */
89 OSStatus err; /* Error code (if any) */
90 CFStringRef cfcommon_name = NULL;
91 /* CF string for server name */
92 SecIdentityRef ident = NULL; /* Identity */
93 SecKeyRef publicKey = NULL,
97 SecCertificateRef cert = NULL; /* Self-signed certificate */
98 CFMutableDictionaryRef keyParams = NULL;
99 /* Key generation parameters */
102 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));
107 (void)expiration_date;
111 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
117 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
121 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
124 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
129 * Create a public/private key pair...
132 keyParams = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
135 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
139 CFDictionaryAddValue(keyParams, kSecAttrKeyType, kSecAttrKeyTypeRSA);
140 CFDictionaryAddValue(keyParams, kSecAttrKeySizeInBits, CFSTR("2048"));
141 CFDictionaryAddValue(keyParams, kSecAttrLabel, cfcommon_name);
143 err = SecKeyGeneratePair(keyParams, &publicKey, &privateKey);
146 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err));
151 * Create a self-signed certificate using the public/private key pair...
154 CFIndex usageInt = kSecKeyUsageAll;
155 CFNumberRef usage = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &usageInt);
157 CFNumberRef len = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &lenInt);
158 CFTypeRef certKeys[] = { kSecCSRBasicContraintsPathLen, kSecSubjectAltName, kSecCertificateKeyUsage };
159 CFTypeRef certValues[] = { len, cfcommon_name, usage };
160 CFDictionaryRef certParams = CFDictionaryCreate(kCFAllocatorDefault, certKeys, certValues, sizeof(certKeys) / sizeof(certKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
164 const void *ca_o[] = { kSecOidOrganization, CFSTR("") };
165 const void *ca_cn[] = { kSecOidCommonName, cfcommon_name };
166 CFArrayRef ca_o_dn = CFArrayCreate(kCFAllocatorDefault, ca_o, 2, NULL);
167 CFArrayRef ca_cn_dn = CFArrayCreate(kCFAllocatorDefault, ca_cn, 2, NULL);
168 const void *ca_dn_array[2];
170 ca_dn_array[0] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_o_dn, 1, NULL);
171 ca_dn_array[1] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_cn_dn, 1, NULL);
173 CFArrayRef subject = CFArrayCreate(kCFAllocatorDefault, ca_dn_array, 2, NULL);
175 cert = SecGenerateSelfSignedCertificate(subject, certParams, publicKey, privateKey);
178 CFRelease(certParams);
182 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
186 ident = SecIdentityCreate(kCFAllocatorDefault, cert, privateKey);
190 _cupsMutexLock(&tls_mutex);
195 tls_selfsigned = ident;
197 _cupsMutexLock(&tls_mutex);
199 # if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point */
200 CFTypeRef itemKeys[] = { kSecClass, kSecAttrLabel, kSecValueRef };
201 CFTypeRef itemValues[] = { kSecClassIdentity, cfcommon_name, ident };
202 CFDictionaryRef itemAttrs = CFDictionaryCreate(kCFAllocatorDefault, itemKeys, itemValues, sizeof(itemKeys) / sizeof(itemKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
204 err = SecItemAdd(itemAttrs, NULL);
205 /* SecItemAdd consumes itemAttrs... */
211 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err));
219 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
222 * Cleanup and return...
228 CFRelease(cfcommon_name);
231 CFRelease(keyParams);
237 CFRelease(publicKey);
240 CFRelease(privateKey);
242 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status));
246 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
247 int pid, /* Process ID of command */
248 status, /* Status of command */
250 char command[1024], /* Command */
251 *argv[5], /* Command-line arguments */
252 *envp[1000], /* Environment variables */
253 days[32], /* CERTTOOL_EXPIRATION_DAYS env var */
254 keychain[1024], /* Keychain argument */
255 infofile[1024], /* Type-in information for cert */
256 filename[1024]; /* Default keychain path */
257 cups_file_t *fp; /* Seed/info file */
260 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));
266 path = http_cdsa_default_path(filename, sizeof(filename));
269 * Run the "certtool" command to generate a self-signed certificate...
272 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
276 * Create a file with the certificate information fields...
278 * Note: This assumes that the default questions are asked by the certtool
282 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
286 "CUPS Self-Signed Certificate\n"
287 /* Enter key and certificate label */
288 "r\n" /* Generate RSA key pair */
289 "2048\n" /* 2048 bit encryption key */
290 "y\n" /* OK (y = yes) */
291 "b\n" /* Usage (b=signing/encryption) */
292 "2\n" /* Sign with SHA256 */
293 "y\n" /* OK (y = yes) */
294 "%s\n" /* Common name */
295 "\n" /* Country (default) */
296 "\n" /* Organization (default) */
297 "\n" /* Organizational unit (default) */
298 "\n" /* State/Province (default) */
299 "\n" /* Email address */
300 "y\n", /* OK (y = yes) */
304 snprintf(keychain, sizeof(keychain), "k=%s", path);
306 argv[0] = "certtool";
311 snprintf(days, sizeof(days), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date - time(NULL) + 86399) / 86400));
313 for (i = 0; i < (int)(sizeof(envp) / sizeof(envp[0]) - 2) && environ[i]; i ++)
314 envp[i + 1] = environ[i];
317 posix_spawn_file_actions_t actions; /* File actions */
319 posix_spawn_file_actions_init(&actions);
320 posix_spawn_file_actions_addclose(&actions, 0);
321 posix_spawn_file_actions_addopen(&actions, 0, infofile, O_RDONLY, 0);
322 posix_spawn_file_actions_addclose(&actions, 1);
323 posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0);
324 posix_spawn_file_actions_addclose(&actions, 2);
325 posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
327 if (posix_spawn(&pid, command, &actions, NULL, argv, envp))
333 posix_spawn_file_actions_destroy(&actions);
337 while (waitpid(pid, &status, 0) < 0)
345 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
350 * 'cupsSetServerCredentials()' - Set the default server credentials.
352 * Note: The server credentials are used by all threads in the running process.
353 * This function is threadsafe.
355 * @since CUPS 2.0/macOS 10.10@
358 int /* O - 1 on success, 0 on failure */
359 cupsSetServerCredentials(
360 const char *path, /* I - Keychain path or @code NULL@ for default */
361 const char *common_name, /* I - Default common name for server */
362 int auto_create) /* I - 1 = automatically create self-signed certificates */
364 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
366 #ifdef HAVE_SECKEYCHAINOPEN
367 char filename[1024]; /* Keychain filename */
368 SecKeychainRef keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
372 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain.");
376 _cupsMutexLock(&tls_mutex);
379 * Close any keychain that is currently open...
383 CFRelease(tls_keychain);
386 _cupsStrFree(tls_keypath);
389 _cupsStrFree(tls_common_name);
392 * Save the new keychain...
395 tls_keychain = keychain;
396 tls_keypath = _cupsStrAlloc(filename);
397 tls_auto_create = auto_create;
398 tls_common_name = _cupsStrAlloc(common_name);
400 _cupsMutexUnlock(&tls_mutex);
402 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
408 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
412 tls_auto_create = auto_create;
413 tls_common_name = _cupsStrAlloc(common_name);
416 #endif /* HAVE_SECKEYCHAINOPEN */
421 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
422 * an encrypted connection.
424 * @since CUPS 1.5/macOS 10.7@
427 int /* O - Status of call (0 = success) */
429 http_t *http, /* I - Connection to server */
430 cups_array_t **credentials) /* O - Array of credentials */
432 OSStatus error; /* Error code */
433 SecTrustRef peerTrust; /* Peer trust reference */
434 CFIndex count; /* Number of credentials */
435 SecCertificateRef secCert; /* Certificate reference */
436 CFDataRef data; /* Certificate data */
437 int i; /* Looping var */
440 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http, (void *)credentials));
445 if (!http || !http->tls || !credentials)
448 if (!(error = SSLCopyPeerTrust(http->tls, &peerTrust)) && peerTrust)
450 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust)));
452 if ((*credentials = cupsArrayNew(NULL, NULL)) != NULL)
454 count = SecTrustGetCertificateCount(peerTrust);
456 for (i = 0; i < count; i ++)
458 secCert = SecTrustGetCertificateAtIndex(peerTrust, i);
461 CFStringRef cf_name = SecCertificateCopySubjectSummary(secCert);
464 CFStringGetCString(cf_name, name, sizeof(name), kCFStringEncodingUTF8);
466 strlcpy(name, "unknown", sizeof(name));
468 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i, name));
471 if ((data = SecCertificateCopyData(secCert)) != NULL)
473 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
475 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
481 CFRelease(peerTrust);
489 * '_httpCreateCredentials()' - Create credentials in the internal format.
492 http_tls_credentials_t /* O - Internal credentials */
493 _httpCreateCredentials(
494 cups_array_t *credentials) /* I - Array of credentials */
496 CFMutableArrayRef peerCerts; /* Peer credentials reference */
497 SecCertificateRef secCert; /* Certificate reference */
498 http_credential_t *credential; /* Credential data */
504 if ((peerCerts = CFArrayCreateMutable(kCFAllocatorDefault,
505 cupsArrayCount(credentials),
506 &kCFTypeArrayCallBacks)) == NULL)
509 for (credential = (http_credential_t *)cupsArrayFirst(credentials);
511 credential = (http_credential_t *)cupsArrayNext(credentials))
513 if ((secCert = http_cdsa_create_credential(credential)) != NULL)
515 CFArrayAppendValue(peerCerts, secCert);
525 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
527 * @since CUPS 2.0/macOS 10.10@
530 int /* O - 1 if valid, 0 otherwise */
531 httpCredentialsAreValidForName(
532 cups_array_t *credentials, /* I - Credentials */
533 const char *common_name) /* I - Name to check */
535 SecCertificateRef secCert; /* Certificate reference */
536 CFStringRef cfcert_name = NULL;
537 /* Certificate's common name (CF string) */
538 char cert_name[256]; /* Certificate's common name (C string) */
539 int valid = 1; /* Valid name? */
542 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
546 * Compare the common names...
549 if ((cfcert_name = SecCertificateCopySubjectSummary(secCert)) == NULL)
552 * Can't get common name, cannot be valid...
557 else if (CFStringGetCString(cfcert_name, cert_name, sizeof(cert_name), kCFStringEncodingUTF8) &&
558 _cups_strcasecmp(common_name, cert_name))
561 * Not an exact match for the common name, check for wildcard certs...
564 const char *domain = strchr(common_name, '.');
565 /* Domain in common name */
567 if (strncmp(cert_name, "*.", 2) || !domain || _cups_strcasecmp(domain, cert_name + 1))
570 * Not a wildcard match.
573 /* TODO: Check subject alternate names */
579 CFRelease(cfcert_name);
588 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
590 * @since CUPS 2.0/macOS 10.10@
593 http_trust_t /* O - Level of trust */
594 httpCredentialsGetTrust(
595 cups_array_t *credentials, /* I - Credentials */
596 const char *common_name) /* I - Common name for trust lookup */
598 SecCertificateRef secCert; /* Certificate reference */
599 http_trust_t trust = HTTP_TRUST_OK;
601 cups_array_t *tcreds = NULL; /* Trusted credentials */
602 _cups_globals_t *cg = _cupsGlobals();
603 /* Per-thread globals */
608 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No common name specified."), 1);
609 return (HTTP_TRUST_UNKNOWN);
612 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
614 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create credentials from array."), 1);
615 return (HTTP_TRUST_UNKNOWN);
618 if (cg->any_root < 0)
622 * Look this common name up in the default keychains...
625 httpLoadCredentials(NULL, &tcreds, common_name);
629 char credentials_str[1024], /* String for incoming credentials */
630 tcreds_str[1024]; /* String for saved credentials */
632 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
633 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
635 if (strcmp(credentials_str, tcreds_str))
638 * Credentials don't match, let's look at the expiration date of the new
639 * credentials and allow if the new ones have a later expiration...
642 if (!cg->trust_first)
645 * Do not trust certificates on first use...
648 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
650 trust = HTTP_TRUST_INVALID;
652 else if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds))
655 * The new credentials are not newly issued...
658 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are older than stored credentials."), 1);
660 trust = HTTP_TRUST_INVALID;
662 else if (!httpCredentialsAreValidForName(credentials, common_name))
665 * The common name does not match the issued certificate...
668 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are not valid for name."), 1);
670 trust = HTTP_TRUST_INVALID;
672 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
675 * Save the renewed credentials...
678 trust = HTTP_TRUST_RENEWED;
680 httpSaveCredentials(NULL, credentials, common_name);
684 httpFreeCredentials(tcreds);
686 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
688 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No stored credentials, not valid for name."), 1);
689 trust = HTTP_TRUST_INVALID;
691 else if (!cg->trust_first)
694 * See if we have a site CA certificate we can compare...
697 if (!httpLoadCredentials(NULL, &tcreds, "site"))
699 if (cupsArrayCount(credentials) != (cupsArrayCount(tcreds) + 1))
702 * Certificate isn't directly generated from the CA cert...
705 trust = HTTP_TRUST_INVALID;
710 * Do a tail comparison of the two certificates...
713 http_credential_t *a, *b; /* Certificates */
715 for (a = (http_credential_t *)cupsArrayFirst(tcreds), b = (http_credential_t *)cupsArrayIndex(credentials, 1);
717 a = (http_credential_t *)cupsArrayNext(tcreds), b = (http_credential_t *)cupsArrayNext(credentials))
718 if (a->datalen != b->datalen || memcmp(a->data, b->data, a->datalen))
722 trust = HTTP_TRUST_INVALID;
725 if (trust != HTTP_TRUST_OK)
726 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials do not validate against site CA certificate."), 1);
730 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
731 trust = HTTP_TRUST_INVALID;
735 if (trust == HTTP_TRUST_OK && !cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
737 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials have expired."), 1);
738 trust = HTTP_TRUST_EXPIRED;
741 if (trust == HTTP_TRUST_OK && !cg->any_root && cupsArrayCount(credentials) == 1)
743 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Self-signed credentials are blocked."), 1);
744 trust = HTTP_TRUST_INVALID;
754 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
756 * @since CUPS 2.0/macOS 10.10@
759 time_t /* O - Expiration date of credentials */
760 httpCredentialsGetExpiration(
761 cups_array_t *credentials) /* I - Credentials */
763 SecCertificateRef secCert; /* Certificate reference */
764 time_t expiration; /* Expiration date */
767 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
770 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
779 * 'httpCredentialsString()' - Return a string representing the credentials.
781 * @since CUPS 2.0/macOS 10.10@
784 size_t /* O - Total size of credentials string */
785 httpCredentialsString(
786 cups_array_t *credentials, /* I - Credentials */
787 char *buffer, /* I - Buffer or @code NULL@ */
788 size_t bufsize) /* I - Size of buffer */
790 http_credential_t *first; /* First certificate */
791 SecCertificateRef secCert; /* Certificate reference */
794 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", (void *)credentials, (void *)buffer, CUPS_LLCAST bufsize));
799 if (buffer && bufsize > 0)
802 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
803 (secCert = http_cdsa_create_credential(first)) != NULL)
805 CFStringRef cf_name; /* CF common name string */
806 char name[256]; /* Common name associated with cert */
807 time_t expiration; /* Expiration date of cert */
808 _cups_md5_state_t md5_state; /* MD5 state */
809 unsigned char md5_digest[16]; /* MD5 result */
811 if ((cf_name = SecCertificateCopySubjectSummary(secCert)) != NULL)
813 CFStringGetCString(cf_name, name, (CFIndex)sizeof(name), kCFStringEncodingUTF8);
817 strlcpy(name, "unknown", sizeof(name));
819 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
821 _cupsMD5Init(&md5_state);
822 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
823 _cupsMD5Finish(&md5_state, md5_digest);
825 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]);
830 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
832 return (strlen(buffer));
837 * '_httpFreeCredentials()' - Free internal credentials.
841 _httpFreeCredentials(
842 http_tls_credentials_t credentials) /* I - Internal credentials */
847 CFRelease(credentials);
852 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
854 * @since CUPS 2.0/OS 10.10@
857 int /* O - 0 on success, -1 on error */
859 const char *path, /* I - Keychain path or @code NULL@ for default */
860 cups_array_t **credentials, /* IO - Credentials */
861 const char *common_name) /* I - Common name for credentials */
863 OSStatus err; /* Error info */
864 #ifdef HAVE_SECKEYCHAINOPEN
865 char filename[1024]; /* Filename for keychain */
866 SecKeychainRef keychain = NULL,/* Keychain reference */
867 syschain = NULL;/* System keychain */
868 CFArrayRef list; /* Keychain list */
869 #endif /* HAVE_SECKEYCHAINOPEN */
870 SecCertificateRef cert = NULL; /* Certificate */
871 CFDataRef data; /* Certificate data */
872 SecPolicyRef policy = NULL; /* Policy ref */
873 CFStringRef cfcommon_name = NULL;
875 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
878 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
885 #ifdef HAVE_SECKEYCHAINOPEN
886 keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
891 syschain = http_cdsa_open_system_keychain();
896 #endif /* HAVE_SECKEYCHAINOPEN */
898 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
900 policy = SecPolicyCreateSSL(1, cfcommon_name);
903 CFRelease(cfcommon_name);
908 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
911 CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
912 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
913 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
914 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
916 #ifdef HAVE_SECKEYCHAINOPEN
919 const void *values[2] = { syschain, keychain };
921 list = CFArrayCreate(kCFAllocatorDefault, (const void **)values, 2, &kCFTypeArrayCallBacks);
924 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
925 CFDictionaryAddValue(query, kSecMatchSearchList, list);
927 #endif /* HAVE_SECKEYCHAINOPEN */
929 err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
934 if (CFGetTypeID(cert) != SecCertificateGetTypeID())
937 if ((data = SecCertificateCopyData(cert)) != NULL)
939 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
941 *credentials = cupsArrayNew(NULL, NULL);
942 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
948 #ifdef HAVE_SECKEYCHAINOPEN
954 #endif /* HAVE_SECKEYCHAINOPEN */
962 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
964 return (*credentials ? 0 : -1);
969 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
971 * @since CUPS 2.0/OS 10.10@
974 int /* O - -1 on error, 0 on success */
976 const char *path, /* I - Keychain path or @code NULL@ for default */
977 cups_array_t *credentials, /* I - Credentials */
978 const char *common_name) /* I - Common name for credentials */
980 int ret = -1; /* Return value */
981 OSStatus err; /* Error info */
982 #ifdef HAVE_SECKEYCHAINOPEN
983 char filename[1024]; /* Filename for keychain */
984 SecKeychainRef keychain = NULL;/* Keychain reference */
985 CFArrayRef list; /* Keychain list */
986 #endif /* HAVE_SECKEYCHAINOPEN */
987 SecCertificateRef cert = NULL; /* Certificate */
988 CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
991 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
995 if (!httpCredentialsAreValidForName(credentials, common_name))
997 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
1001 if ((cert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
1003 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
1007 #ifdef HAVE_SECKEYCHAINOPEN
1008 keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
1016 #endif /* HAVE_SECKEYCHAINOPEN */
1018 if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
1020 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
1024 CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
1025 CFDictionaryAddValue(attrs, kSecValueRef, cert);
1027 #ifdef HAVE_SECKEYCHAINOPEN
1028 if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
1030 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
1033 CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
1035 #endif /* HAVE_SECKEYCHAINOPEN */
1037 /* Note: SecItemAdd consumes "attrs"... */
1038 err = SecItemAdd(attrs, NULL);
1039 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err));
1043 #ifdef HAVE_SECKEYCHAINOPEN
1045 CFRelease(keychain);
1046 #endif /* HAVE_SECKEYCHAINOPEN */
1050 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
1057 * '_httpTLSInitialize()' - Initialize the TLS stack.
1061 _httpTLSInitialize(void)
1070 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1074 _httpTLSPending(http_t *http) /* I - HTTP connection */
1076 size_t bytes; /* Bytes that are available */
1079 if (!SSLGetBufferedReadSize(http->tls, &bytes))
1087 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1090 int /* O - Bytes read */
1091 _httpTLSRead(http_t *http, /* I - HTTP connection */
1092 char *buf, /* I - Buffer to store data */
1093 int len) /* I - Length of buffer */
1095 int result; /* Return value */
1096 OSStatus error; /* Error info */
1097 size_t processed; /* Number of bytes processed */
1100 error = SSLRead(http->tls, buf, (size_t)len, &processed);
1101 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error,
1106 result = (int)processed;
1109 case errSSLWouldBlock :
1111 result = (int)processed;
1119 case errSSLClosedGraceful :
1122 result = (int)processed;
1136 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1140 _httpTLSSetOptions(int options) /* I - Options */
1142 tls_options = options;
1147 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1150 int /* O - 0 on success, -1 on failure */
1151 _httpTLSStart(http_t *http) /* I - HTTP connection */
1153 char hostname[256], /* Hostname */
1154 *hostptr; /* Pointer into hostname */
1155 _cups_globals_t *cg = _cupsGlobals();
1156 /* Pointer to library globals */
1157 OSStatus error; /* Error code */
1158 const char *message = NULL;/* Error message */
1159 cups_array_t *credentials; /* Credentials array */
1160 cups_array_t *names; /* CUPS distinguished names */
1161 CFArrayRef dn_array; /* CF distinguished names array */
1162 CFIndex count; /* Number of credentials */
1163 CFDataRef data; /* Certificate data */
1164 int i; /* Looping var */
1165 http_credential_t *credential; /* Credential data */
1168 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http));
1170 if (tls_options < 0)
1172 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1174 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options));
1177 #ifdef HAVE_SECKEYCHAINOPEN
1178 if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
1180 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1181 http->error = errno = EINVAL;
1182 http->status = HTTP_STATUS_ERROR;
1183 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
1187 #endif /* HAVE_SECKEYCHAINOPEN */
1189 if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
1191 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1192 http->error = errno = ENOMEM;
1193 http->status = HTTP_STATUS_ERROR;
1194 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1199 error = SSLSetConnection(http->tls, http);
1200 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error));
1204 error = SSLSetIOFuncs(http->tls, http_cdsa_read, http_cdsa_write);
1205 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error));
1210 error = SSLSetSessionOption(http->tls, kSSLSessionOptionBreakOnServerAuth,
1212 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error));
1217 SSLProtocol minProtocol;
1219 if (tls_options & _HTTP_TLS_DENY_TLS10)
1220 minProtocol = kTLSProtocol11;
1221 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1222 minProtocol = kSSLProtocol3;
1224 minProtocol = kTLSProtocol1;
1226 error = SSLSetProtocolVersionMin(http->tls, minProtocol);
1227 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol, (int)error));
1230 # if HAVE_SSLSETENABLEDCIPHERS
1233 SSLCipherSuite supported[100]; /* Supported cipher suites */
1234 size_t num_supported; /* Number of supported cipher suites */
1235 SSLCipherSuite enabled[100]; /* Cipher suites to enable */
1236 size_t num_enabled; /* Number of cipher suites to enable */
1238 num_supported = sizeof(supported) / sizeof(supported[0]);
1239 error = SSLGetSupportedCiphers(http->tls, supported, &num_supported);
1243 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported));
1245 for (i = 0, num_enabled = 0; i < (int)num_supported && num_enabled < (sizeof(enabled) / sizeof(enabled[0])); i ++)
1247 switch (supported[i])
1249 /* Obviously insecure cipher suites that we never want to use */
1250 case SSL_NULL_WITH_NULL_NULL :
1251 case SSL_RSA_WITH_NULL_MD5 :
1252 case SSL_RSA_WITH_NULL_SHA :
1253 case SSL_RSA_EXPORT_WITH_RC4_40_MD5 :
1254 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 :
1255 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA :
1256 case SSL_RSA_WITH_DES_CBC_SHA :
1257 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA :
1258 case SSL_DH_DSS_WITH_DES_CBC_SHA :
1259 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA :
1260 case SSL_DH_RSA_WITH_DES_CBC_SHA :
1261 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA :
1262 case SSL_DHE_DSS_WITH_DES_CBC_SHA :
1263 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA :
1264 case SSL_DHE_RSA_WITH_DES_CBC_SHA :
1265 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 :
1266 case SSL_DH_anon_WITH_RC4_128_MD5 :
1267 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA :
1268 case SSL_DH_anon_WITH_DES_CBC_SHA :
1269 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA :
1270 case SSL_FORTEZZA_DMS_WITH_NULL_SHA :
1271 case TLS_DH_anon_WITH_AES_128_CBC_SHA :
1272 case TLS_DH_anon_WITH_AES_256_CBC_SHA :
1273 case TLS_ECDH_ECDSA_WITH_NULL_SHA :
1274 case TLS_ECDHE_RSA_WITH_NULL_SHA :
1275 case TLS_ECDH_anon_WITH_NULL_SHA :
1276 case TLS_ECDH_anon_WITH_RC4_128_SHA :
1277 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA :
1278 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA :
1279 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA :
1280 case TLS_RSA_WITH_NULL_SHA256 :
1281 case TLS_DH_anon_WITH_AES_128_CBC_SHA256 :
1282 case TLS_DH_anon_WITH_AES_256_CBC_SHA256 :
1283 case TLS_PSK_WITH_NULL_SHA :
1284 case TLS_DHE_PSK_WITH_NULL_SHA :
1285 case TLS_RSA_PSK_WITH_NULL_SHA :
1286 case TLS_DH_anon_WITH_AES_128_GCM_SHA256 :
1287 case TLS_DH_anon_WITH_AES_256_GCM_SHA384 :
1288 case TLS_PSK_WITH_NULL_SHA256 :
1289 case TLS_PSK_WITH_NULL_SHA384 :
1290 case TLS_DHE_PSK_WITH_NULL_SHA256 :
1291 case TLS_DHE_PSK_WITH_NULL_SHA384 :
1292 case TLS_RSA_PSK_WITH_NULL_SHA256 :
1293 case TLS_RSA_PSK_WITH_NULL_SHA384 :
1294 case SSL_RSA_WITH_DES_CBC_MD5 :
1295 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported[i]));
1298 /* RC4 cipher suites that should only be used as a last resort */
1299 case SSL_RSA_WITH_RC4_128_MD5 :
1300 case SSL_RSA_WITH_RC4_128_SHA :
1301 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
1302 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
1303 case TLS_ECDH_RSA_WITH_RC4_128_SHA :
1304 case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
1305 case TLS_PSK_WITH_RC4_128_SHA :
1306 case TLS_DHE_PSK_WITH_RC4_128_SHA :
1307 case TLS_RSA_PSK_WITH_RC4_128_SHA :
1308 if (tls_options & _HTTP_TLS_ALLOW_RC4)
1309 enabled[num_enabled ++] = supported[i];
1311 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported[i]));
1314 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1315 case TLS_DH_DSS_WITH_AES_128_CBC_SHA :
1316 case TLS_DH_RSA_WITH_AES_128_CBC_SHA :
1317 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA :
1318 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
1319 case TLS_DH_DSS_WITH_AES_256_CBC_SHA :
1320 case TLS_DH_RSA_WITH_AES_256_CBC_SHA :
1321 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA :
1322 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
1323 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA :
1324 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA :
1325 // case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
1326 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA :
1327 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256 :
1328 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256 :
1329 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 :
1330 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
1331 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256 :
1332 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256 :
1333 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 :
1334 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
1335 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA :
1336 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA :
1337 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA :
1338 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1339 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1340 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256 :
1341 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384 :
1342 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1343 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1344 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256 :
1345 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384 :
1346 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
1347 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
1348 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
1349 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
1350 if (tls_options & _HTTP_TLS_ALLOW_DH)
1351 enabled[num_enabled ++] = supported[i];
1353 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported[i]));
1356 /* Anything else we'll assume is secure */
1358 enabled[num_enabled ++] = supported[i];
1363 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled));
1364 error = SSLSetEnabledCiphers(http->tls, enabled, num_enabled);
1367 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1369 if (!error && http->mode == _HTTP_MODE_CLIENT)
1372 * Client: set client-side credentials, if any...
1375 if (cg->client_cert_cb)
1377 error = SSLSetSessionOption(http->tls,
1378 kSSLSessionOptionBreakOnCertRequested, true);
1379 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1380 "error=%d", (int)error));
1384 error = http_cdsa_set_credentials(http);
1385 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1392 * Server: find/create a certificate for TLS...
1395 if (http->fields[HTTP_FIELD_HOST][0])
1398 * Use hostname for TLS upgrade...
1401 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1406 * Resolve hostname from connection address...
1409 http_addr_t addr; /* Connection address */
1410 socklen_t addrlen; /* Length of address */
1412 addrlen = sizeof(addr);
1413 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1415 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
1418 else if (httpAddrLocalhost(&addr))
1422 httpAddrLookup(&addr, hostname, sizeof(hostname));
1423 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
1427 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1428 hostname[0] = '\0'; /* Don't allow numeric addresses */
1431 http->tls_credentials = http_cdsa_copy_server(hostname);
1432 else if (tls_common_name)
1433 http->tls_credentials = http_cdsa_copy_server(tls_common_name);
1435 if (!http->tls_credentials && tls_auto_create && (hostname[0] || tls_common_name))
1437 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
1439 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1441 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1442 http->error = errno = EINVAL;
1443 http->status = HTTP_STATUS_ERROR;
1444 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1449 http->tls_credentials = http_cdsa_copy_server(hostname[0] ? hostname : tls_common_name);
1452 if (!http->tls_credentials)
1454 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1455 http->error = errno = EINVAL;
1456 http->status = HTTP_STATUS_ERROR;
1457 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to find server credentials."), 1);
1462 error = SSLSetCertificate(http->tls, http->tls_credentials);
1464 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
1467 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http->tls_credentials));
1470 * Let the server know which hostname/domain we are trying to connect to
1471 * in case it wants to serve up a certificate with a matching common name.
1474 if (!error && http->mode == _HTTP_MODE_CLIENT)
1477 * Client: get the hostname to use for TLS...
1480 if (httpAddrLocalhost(http->hostaddr))
1482 strlcpy(hostname, "localhost", sizeof(hostname));
1487 * Otherwise make sure the hostname we have does not end in a trailing dot.
1490 strlcpy(hostname, http->hostname, sizeof(hostname));
1491 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1496 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
1498 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error));
1503 int done = 0; /* Are we done yet? */
1505 while (!error && !done)
1507 error = SSLHandshake(http->tls);
1509 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error));
1517 case errSSLWouldBlock :
1518 error = noErr; /* Force a retry */
1519 usleep(1000); /* in 1 millisecond */
1522 case errSSLServerAuthCompleted :
1524 if (cg->server_cert_cb)
1526 error = httpCopyCredentials(http, &credentials);
1529 error = (cg->server_cert_cb)(http, http->tls, credentials,
1530 cg->server_cert_data);
1531 httpFreeCredentials(credentials);
1534 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1535 "returned %d.", (int)error));
1539 case errSSLClientCertRequested :
1542 if (cg->client_cert_cb)
1545 if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
1548 if ((names = cupsArrayNew(NULL, NULL)) != NULL)
1550 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
1552 data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
1554 if ((credential = malloc(sizeof(*credential))) != NULL)
1556 credential->datalen = (size_t)CFDataGetLength(data);
1557 if ((credential->data = malloc(credential->datalen)))
1559 memcpy((void *)credential->data, CFDataGetBytePtr(data),
1560 credential->datalen);
1561 cupsArrayAdd(names, credential);
1569 CFRelease(dn_array);
1574 error = (cg->client_cert_cb)(http, http->tls, names,
1575 cg->client_cert_data);
1577 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1578 "returned %d.", (int)error));
1581 httpFreeCredentials(names);
1585 case errSSLUnknownRootCert :
1586 message = _("Unable to establish a secure connection to host "
1587 "(untrusted certificate).");
1590 case errSSLNoRootCert :
1591 message = _("Unable to establish a secure connection to host "
1592 "(self-signed certificate).");
1595 case errSSLCertExpired :
1596 message = _("Unable to establish a secure connection to host "
1597 "(expired certificate).");
1600 case errSSLCertNotYetValid :
1601 message = _("Unable to establish a secure connection to host "
1602 "(certificate not yet valid).");
1605 case errSSLHostNameMismatch :
1606 message = _("Unable to establish a secure connection to host "
1607 "(host name mismatch).");
1610 case errSSLXCertChainInvalid :
1611 message = _("Unable to establish a secure connection to host "
1612 "(certificate chain invalid).");
1615 case errSSLConnectionRefused :
1616 message = _("Unable to establish a secure connection to host "
1617 "(peer dropped connection before responding).");
1628 http->error = error;
1629 http->status = HTTP_STATUS_ERROR;
1630 errno = ECONNREFUSED;
1632 CFRelease(http->tls);
1636 * If an error string wasn't set by the callbacks use a generic one...
1640 #ifdef HAVE_CSSMERRORSTRING
1641 message = cssmErrorString(error);
1643 message = _("Unable to establish a secure connection to host.");
1644 #endif /* HAVE_CSSMERRORSTRING */
1646 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
1656 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1660 _httpTLSStop(http_t *http) /* I - HTTP connection */
1662 while (SSLClose(http->tls) == errSSLWouldBlock)
1665 CFRelease(http->tls);
1667 if (http->tls_credentials)
1668 CFRelease(http->tls_credentials);
1671 http->tls_credentials = NULL;
1676 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1679 int /* O - Bytes written */
1680 _httpTLSWrite(http_t *http, /* I - HTTP connection */
1681 const char *buf, /* I - Buffer holding data */
1682 int len) /* I - Length of buffer */
1684 ssize_t result; /* Return value */
1685 OSStatus error; /* Error info */
1686 size_t processed; /* Number of bytes processed */
1689 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http, (void *)buf, len));
1691 error = SSLWrite(http->tls, buf, (size_t)len, &processed);
1696 result = (int)processed;
1699 case errSSLWouldBlock :
1702 result = (int)processed;
1711 case errSSLClosedGraceful :
1715 result = (int)processed;
1725 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result));
1727 return ((int)result);
1732 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1735 static CFArrayRef /* O - Array of certificates or NULL */
1736 http_cdsa_copy_server(
1737 const char *common_name) /* I - Server's hostname */
1739 #ifdef HAVE_SECKEYCHAINOPEN
1740 OSStatus err; /* Error info */
1741 SecIdentityRef identity = NULL;/* Identity */
1742 CFArrayRef certificates = NULL;
1743 /* Certificate array */
1744 SecPolicyRef policy = NULL; /* Policy ref */
1745 CFStringRef cfcommon_name = NULL;
1747 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
1748 CFArrayRef list = NULL; /* Keychain list */
1749 SecKeychainRef syschain = NULL;/* System keychain */
1752 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name));
1754 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
1756 policy = SecPolicyCreateSSL(1, cfcommon_name);
1760 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
1764 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
1766 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
1770 _cupsMutexLock(&tls_mutex);
1772 CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
1773 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
1774 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
1775 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
1777 syschain = http_cdsa_open_system_keychain();
1781 const void *values[2] = { syschain, tls_keychain };
1783 list = CFArrayCreate(kCFAllocatorDefault, (const void **)values, 2, &kCFTypeArrayCallBacks);
1786 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
1788 CFDictionaryAddValue(query, kSecMatchSearchList, list);
1791 err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
1793 _cupsMutexUnlock(&tls_mutex);
1797 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err));
1801 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
1803 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
1807 if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
1809 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
1816 CFRelease(syschain);
1818 CFRelease(identity);
1822 CFRelease(cfcommon_name);
1826 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates));
1828 return (certificates);
1831 if (!tls_selfsigned)
1834 return (CFArrayCreate(NULL, (const void **)&tls_selfsigned, 1, &kCFTypeArrayCallBacks));
1835 #endif /* HAVE_SECKEYCHAINOPEN */
1840 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1843 static SecCertificateRef /* O - Certificate */
1844 http_cdsa_create_credential(
1845 http_credential_t *credential) /* I - Credential */
1850 return (SecCertificateCreateWithBytes(kCFAllocatorDefault, credential->data, (CFIndex)credential->datalen));
1854 #ifdef HAVE_SECKEYCHAINOPEN
1856 * 'http_cdsa_default_path()' - Get the default keychain path.
1859 static const char * /* O - Keychain path */
1860 http_cdsa_default_path(char *buffer, /* I - Path buffer */
1861 size_t bufsize) /* I - Size of buffer */
1863 const char *home = getenv("HOME"); /* HOME environment variable */
1867 * Determine the default keychain path. Note that the login and system
1868 * keychains are no longer accessible to user applications starting in macOS
1869 * 10.11.4 (!), so we need to create our own keychain just for CUPS.
1872 if (getuid() && home)
1873 snprintf(buffer, bufsize, "%s/.cups/ssl.keychain", home);
1875 strlcpy(buffer, "/etc/cups/ssl.keychain", bufsize);
1877 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer));
1884 * 'http_cdsa_open_keychain()' - Open (or create) a keychain.
1887 static SecKeychainRef /* O - Keychain or NULL */
1888 http_cdsa_open_keychain(
1889 const char *path, /* I - Path to keychain */
1890 char *filename, /* I - Keychain filename */
1891 size_t filesize) /* I - Size of filename buffer */
1893 SecKeychainRef keychain = NULL;/* Temporary keychain */
1894 OSStatus err; /* Error code */
1895 Boolean interaction; /* Interaction allowed? */
1896 SecKeychainStatus status = 0; /* Keychain status */
1900 * Get the keychain filename...
1904 path = http_cdsa_default_path(filename, filesize);
1906 strlcpy(filename, path, filesize);
1909 * Save the interaction setting and disable while we open the keychain...
1912 SecKeychainGetUserInteractionAllowed(&interaction);
1913 SecKeychainSetUserInteractionAllowed(FALSE);
1915 if (access(path, R_OK))
1918 * Create a new keychain at the given path...
1921 err = SecKeychainCreate(path, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, FALSE, NULL, &keychain);
1926 * Open the existing keychain and unlock as needed...
1929 err = SecKeychainOpen(path, &keychain);
1932 err = SecKeychainGetStatus(keychain, &status);
1934 if (err == noErr && !(status & kSecUnlockStateStatus))
1935 err = SecKeychainUnlock(keychain, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, TRUE);
1939 * Restore interaction setting...
1942 SecKeychainSetUserInteractionAllowed(interaction);
1945 * Release the keychain if we had any errors...
1950 /* TODO: Set cups last error string */
1951 DEBUG_printf(("4http_cdsa_open_keychain: Unable to open keychain (%d), returning NULL.", (int)err));
1955 CFRelease(keychain);
1961 * Return the keychain or NULL...
1969 * 'http_cdsa_open_system_keychain()' - Open the System keychain.
1972 static SecKeychainRef
1973 http_cdsa_open_system_keychain(void)
1975 SecKeychainRef keychain = NULL;/* Temporary keychain */
1976 OSStatus err; /* Error code */
1977 Boolean interaction; /* Interaction allowed? */
1978 SecKeychainStatus status = 0; /* Keychain status */
1982 * Save the interaction setting and disable while we open the keychain...
1985 SecKeychainGetUserInteractionAllowed(&interaction);
1986 SecKeychainSetUserInteractionAllowed(TRUE);
1988 err = SecKeychainOpen("/Library/Keychains/System.keychain", &keychain);
1991 err = SecKeychainGetStatus(keychain, &status);
1993 if (err == noErr && !(status & kSecUnlockStateStatus))
1994 err = errSecInteractionNotAllowed;
1997 * Restore interaction setting...
2000 SecKeychainSetUserInteractionAllowed(interaction);
2003 * Release the keychain if we had any errors...
2008 /* TODO: Set cups last error string */
2009 DEBUG_printf(("4http_cdsa_open_system_keychain: Unable to open keychain (%d), returning NULL.", (int)err));
2013 CFRelease(keychain);
2019 * Return the keychain or NULL...
2024 #endif /* HAVE_SECKEYCHAINOPEN */
2028 * 'http_cdsa_read()' - Read function for the CDSA library.
2031 static OSStatus /* O - -1 on error, 0 on success */
2033 SSLConnectionRef connection, /* I - SSL/TLS connection */
2034 void *data, /* I - Data buffer */
2035 size_t *dataLength) /* IO - Number of bytes */
2037 OSStatus result; /* Return value */
2038 ssize_t bytes; /* Number of bytes read */
2039 http_t *http; /* HTTP connection */
2042 http = (http_t *)connection;
2044 if (!http->blocking)
2047 * Make sure we have data before we read...
2050 while (!_httpWait(http, http->wait_value, 0))
2052 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2055 http->error = ETIMEDOUT;
2062 bytes = recv(http->fd, data, *dataLength, 0);
2064 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2066 if ((size_t)bytes == *dataLength)
2072 *dataLength = (size_t)bytes;
2073 result = errSSLWouldBlock;
2080 result = errSSLClosedGraceful;
2081 else if (errno == EAGAIN)
2082 result = errSSLWouldBlock;
2084 result = errSSLClosedAbort;
2092 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
2095 static int /* O - Status of connection */
2096 http_cdsa_set_credentials(http_t *http) /* I - HTTP connection */
2098 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2099 OSStatus error = 0; /* Error code */
2100 http_tls_credentials_t credentials = NULL;
2101 /* TLS credentials */
2104 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http));
2107 * Prefer connection specific credentials...
2110 if ((credentials = http->tls_credentials) == NULL)
2111 credentials = cg->tls_credentials;
2115 error = SSLSetCertificate(http->tls, credentials);
2116 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
2120 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
2127 * 'http_cdsa_write()' - Write function for the CDSA library.
2130 static OSStatus /* O - -1 on error, 0 on success */
2132 SSLConnectionRef connection, /* I - SSL/TLS connection */
2133 const void *data, /* I - Data buffer */
2134 size_t *dataLength) /* IO - Number of bytes */
2136 OSStatus result; /* Return value */
2137 ssize_t bytes; /* Number of bytes read */
2138 http_t *http; /* HTTP connection */
2141 http = (http_t *)connection;
2145 bytes = write(http->fd, data, *dataLength);
2147 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2149 if ((size_t)bytes == *dataLength)
2153 else if (bytes >= 0)
2155 *dataLength = (size_t)bytes;
2156 result = errSSLWouldBlock;
2162 if (errno == EAGAIN)
2163 result = errSSLWouldBlock;
2165 result = errSSLClosedAbort;