4 * TLS support code for CUPS on OS X.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
18 /**** This file is included from tls.c ****/
21 * Include necessary headers...
26 extern char **environ
;
30 * Test define - set to 1 to use SSLSetEnabledCiphers. Currently disabled (0)
31 * because of <rdar://problem/18707430>.
34 #define USE_SET_ENABLED_CIPHERS 0
41 #ifdef HAVE_SECKEYCHAINOPEN
42 static int tls_auto_create
= 0;
43 /* Auto-create self-signed certs? */
44 static char *tls_common_name
= NULL
;
45 /* Default common name */
46 static SecKeychainRef tls_keychain
= NULL
;
47 /* Server cert keychain */
48 static char *tls_keypath
= NULL
;
49 /* Server cert keychain path */
50 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
51 /* Mutex for keychain/certs */
52 static int tls_options
= 0;/* Options for TLS connections */
53 #endif /* HAVE_SECKEYCHAINOPEN */
60 #ifdef HAVE_SECKEYCHAINOPEN
61 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
62 #endif /* HAVE_SECKEYCHAINOPEN */
63 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
64 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
65 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
66 static int http_cdsa_set_credentials(http_t
*http
);
67 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
71 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
73 * @since CUPS 2.0/OS 10.10@
76 int /* O - 1 on success, 0 on failure */
77 cupsMakeServerCredentials(
78 const char *path
, /* I - Keychain path or @code NULL@ for default */
79 const char *common_name
, /* I - Common name */
80 int num_alt_names
, /* I - Number of subject alternate names */
81 const char **alt_names
, /* I - Subject Alternate Names */
82 time_t expiration_date
) /* I - Expiration date */
84 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE) && defined(HAVE_SECKEYCHAINOPEN)
85 char filename
[1024]; /* Default keychain path */
86 int status
= 0; /* Return status */
87 OSStatus err
; /* Error code (if any) */
88 CFStringRef cfcommon_name
= NULL
;
89 /* CF string for server name */
90 SecIdentityRef ident
= NULL
; /* Identity */
91 SecKeyRef publicKey
= NULL
,
95 CFMutableDictionaryRef keyParams
= NULL
;
96 /* Key generation parameters */
99 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
));
103 (void)expiration_date
;
106 path
= http_cdsa_default_path(filename
, sizeof(filename
));
108 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
113 * Create a public/private key pair...
116 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
120 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
121 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
122 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, CFSTR("CUPS Self-Signed Certificate"));
124 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
129 * Create a self-signed certificate using the public/private key pair...
132 CFIndex usageInt
= kSecKeyUsageAll
;
133 CFNumberRef usage
= CFNumberCreate(alloc
, kCFNumberCFIndexType
, &usageInt
);
134 CFDictionaryRef certParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
,
135 kSecCSRBasicContraintsPathLen
, CFINT(0), kSecSubjectAltName
, cfcommon_name
, kSecCertificateKeyUsage
, usage
, NULL
, NULL
);
138 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
139 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
140 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
141 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
142 const void *ca_dn_array
[2];
144 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
145 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
147 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
148 SecCertificateRef cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
150 CFRelease(certParams
);
155 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
161 * Cleanup and return...
167 CFRelease(cfcommon_name
);
170 CFRelease(keyParams
);
179 CFRelease(publicKey
);
182 CFRelease(publicKey
);
186 #else /* !(HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN) */
187 int pid
, /* Process ID of command */
188 status
, /* Status of command */
190 char command
[1024], /* Command */
191 *argv
[4], /* Command-line arguments */
192 *envp
[1000], /* Environment variables */
193 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
194 keychain
[1024], /* Keychain argument */
195 infofile
[1024], /* Type-in information for cert */
196 filename
[1024]; /* Default keychain path */
197 cups_file_t
*fp
; /* Seed/info file */
200 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
));
206 path
= http_cdsa_default_path(filename
, sizeof(filename
));
209 * Run the "certtool" command to generate a self-signed certificate...
212 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
216 * Create a file with the certificate information fields...
218 * Note: This assumes that the default questions are asked by the certtool
222 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
226 "CUPS Self-Signed Certificate\n"
227 /* Enter key and certificate label */
228 "r\n" /* Generate RSA key pair */
229 "2048\n" /* Key size in bits */
230 "y\n" /* OK (y = yes) */
231 "b\n" /* Usage (b=signing/encryption) */
232 "s\n" /* Sign with SHA1 */
233 "y\n" /* OK (y = yes) */
234 "%s\n" /* Common name */
235 "\n" /* Country (default) */
236 "\n" /* Organization (default) */
237 "\n" /* Organizational unit (default) */
238 "\n" /* State/Province (default) */
239 "\n" /* Email address */
240 "y\n", /* OK (y = yes) */
244 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
246 argv
[0] = "certtool";
251 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
253 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
254 envp
[i
+ 1] = environ
[i
];
257 posix_spawn_file_actions_t actions
; /* File actions */
259 posix_spawn_file_actions_init(&actions
);
260 posix_spawn_file_actions_addclose(&actions
, 0);
261 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
262 posix_spawn_file_actions_addclose(&actions
, 1);
263 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
264 posix_spawn_file_actions_addclose(&actions
, 2);
265 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
267 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
273 posix_spawn_file_actions_destroy(&actions
);
277 while (waitpid(pid
, &status
, 0) < 0)
285 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
290 * 'cupsSetServerCredentials()' - Set the default server credentials.
292 * Note: The server credentials are used by all threads in the running process.
293 * This function is threadsafe.
295 * @since CUPS 2.0/OS X 10.10@
298 int /* O - 1 on success, 0 on failure */
299 cupsSetServerCredentials(
300 const char *path
, /* I - Keychain path or @code NULL@ for default */
301 const char *common_name
, /* I - Default common name for server */
302 int auto_create
) /* I - 1 = automatically create self-signed certificates */
304 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
306 #ifdef HAVE_SECKEYCHAINOPEN
307 char filename
[1024]; /* Filename for keychain */
308 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
312 path
= http_cdsa_default_path(filename
, sizeof(filename
));
314 if (SecKeychainOpen(path
, &keychain
) != noErr
)
316 /* TODO: Set cups last error string */
317 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain, returning 0.");
321 _cupsMutexLock(&tls_mutex
);
324 * Close any keychain that is currently open...
328 CFRelease(tls_keychain
);
331 _cupsStrFree(tls_keypath
);
334 _cupsStrFree(tls_common_name
);
337 * Save the new keychain...
340 tls_keychain
= keychain
;
341 tls_keypath
= _cupsStrAlloc(path
);
342 tls_auto_create
= auto_create
;
343 tls_common_name
= _cupsStrAlloc(common_name
);
345 _cupsMutexUnlock(&tls_mutex
);
347 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
351 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
353 #endif /* HAVE_SECKEYCHAINOPEN */
358 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
359 * an encrypted connection.
361 * @since CUPS 1.5/OS X 10.7@
364 int /* O - Status of call (0 = success) */
366 http_t
*http
, /* I - Connection to server */
367 cups_array_t
**credentials
) /* O - Array of credentials */
369 OSStatus error
; /* Error code */
370 SecTrustRef peerTrust
; /* Peer trust reference */
371 CFIndex count
; /* Number of credentials */
372 SecCertificateRef secCert
; /* Certificate reference */
373 CFDataRef data
; /* Certificate data */
374 int i
; /* Looping var */
377 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
382 if (!http
|| !http
->tls
|| !credentials
)
385 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
387 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
389 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
391 count
= SecTrustGetCertificateCount(peerTrust
);
393 for (i
= 0; i
< count
; i
++)
395 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
398 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
401 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
403 strlcpy(name
, "unknown", sizeof(name
));
405 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
408 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
410 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
412 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
418 CFRelease(peerTrust
);
426 * '_httpCreateCredentials()' - Create credentials in the internal format.
429 http_tls_credentials_t
/* O - Internal credentials */
430 _httpCreateCredentials(
431 cups_array_t
*credentials
) /* I - Array of credentials */
433 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
434 SecCertificateRef secCert
; /* Certificate reference */
435 http_credential_t
*credential
; /* Credential data */
441 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
442 cupsArrayCount(credentials
),
443 &kCFTypeArrayCallBacks
)) == NULL
)
446 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
448 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
450 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
452 CFArrayAppendValue(peerCerts
, secCert
);
462 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
464 * @since CUPS 2.0/OS X 10.10@
467 int /* O - 1 if valid, 0 otherwise */
468 httpCredentialsAreValidForName(
469 cups_array_t
*credentials
, /* I - Credentials */
470 const char *common_name
) /* I - Name to check */
472 SecCertificateRef secCert
; /* Certificate reference */
473 CFStringRef cfcert_name
= NULL
;
474 /* Certificate's common name (CF string) */
475 char cert_name
[256]; /* Certificate's common name (C string) */
476 int valid
= 1; /* Valid name? */
479 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
483 * Compare the common names...
486 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
489 * Can't get common name, cannot be valid...
494 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
495 _cups_strcasecmp(common_name
, cert_name
))
498 * Not an exact match for the common name, check for wildcard certs...
501 const char *domain
= strchr(common_name
, '.');
502 /* Domain in common name */
504 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
507 * Not a wildcard match.
510 /* TODO: Check subject alternate names */
516 CFRelease(cfcert_name
);
525 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
527 * @since CUPS 2.0/OS X 10.10@
530 http_trust_t
/* O - Level of trust */
531 httpCredentialsGetTrust(
532 cups_array_t
*credentials
, /* I - Credentials */
533 const char *common_name
) /* I - Common name for trust lookup */
535 SecCertificateRef secCert
; /* Certificate reference */
536 http_trust_t trust
= HTTP_TRUST_OK
;
538 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
539 _cups_globals_t
*cg
= _cupsGlobals();
540 /* Per-thread globals */
544 return (HTTP_TRUST_UNKNOWN
);
546 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
547 return (HTTP_TRUST_UNKNOWN
);
550 * Look this common name up in the default keychains...
553 httpLoadCredentials(NULL
, &tcreds
, common_name
);
557 char credentials_str
[1024], /* String for incoming credentials */
558 tcreds_str
[1024]; /* String for saved credentials */
560 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
561 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
563 if (strcmp(credentials_str
, tcreds_str
))
566 * Credentials don't match, let's look at the expiration date of the new
567 * credentials and allow if the new ones have a later expiration...
570 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
571 !httpCredentialsAreValidForName(credentials
, common_name
))
574 * Either the new credentials are not newly issued, or the common name
575 * does not match the issued certificate...
578 trust
= HTTP_TRUST_INVALID
;
580 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
583 * Save the renewed credentials...
586 trust
= HTTP_TRUST_RENEWED
;
588 httpSaveCredentials(NULL
, credentials
, common_name
);
592 httpFreeCredentials(tcreds
);
594 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
595 trust
= HTTP_TRUST_INVALID
;
597 if (!cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
598 trust
= HTTP_TRUST_EXPIRED
;
599 else if (!cg
->any_root
&& cupsArrayCount(credentials
) == 1)
600 trust
= HTTP_TRUST_INVALID
;
609 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
611 * @since CUPS 2.0/OS X 10.10@
614 time_t /* O - Expiration date of credentials */
615 httpCredentialsGetExpiration(
616 cups_array_t
*credentials
) /* I - Credentials */
618 SecCertificateRef secCert
; /* Certificate reference */
619 time_t expiration
; /* Expiration date */
622 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
625 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
634 * 'httpCredentialsString()' - Return a string representing the credentials.
636 * @since CUPS 2.0/OS X 10.10@
639 size_t /* O - Total size of credentials string */
640 httpCredentialsString(
641 cups_array_t
*credentials
, /* I - Credentials */
642 char *buffer
, /* I - Buffer or @code NULL@ */
643 size_t bufsize
) /* I - Size of buffer */
645 http_credential_t
*first
; /* First certificate */
646 SecCertificateRef secCert
; /* Certificate reference */
649 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
654 if (buffer
&& bufsize
> 0)
657 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
658 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
660 CFStringRef cf_name
; /* CF common name string */
661 char name
[256]; /* Common name associated with cert */
662 time_t expiration
; /* Expiration date of cert */
663 _cups_md5_state_t md5_state
; /* MD5 state */
664 unsigned char md5_digest
[16]; /* MD5 result */
666 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
668 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
672 strlcpy(name
, "unknown", sizeof(name
));
674 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
676 _cupsMD5Init(&md5_state
);
677 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
678 _cupsMD5Finish(&md5_state
, md5_digest
);
680 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]);
685 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
687 return (strlen(buffer
));
692 * '_httpFreeCredentials()' - Free internal credentials.
696 _httpFreeCredentials(
697 http_tls_credentials_t credentials
) /* I - Internal credentials */
702 CFRelease(credentials
);
707 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
709 * @since CUPS 2.0/OS 10.10@
712 int /* O - 0 on success, -1 on error */
714 const char *path
, /* I - Keychain path or @code NULL@ for default */
715 cups_array_t
**credentials
, /* IO - Credentials */
716 const char *common_name
) /* I - Common name for credentials */
718 #ifdef HAVE_SECKEYCHAINOPEN
719 OSStatus err
; /* Error info */
720 char filename
[1024]; /* Filename for keychain */
721 SecKeychainRef keychain
= NULL
;/* Keychain reference */
722 SecIdentitySearchRef search
= NULL
; /* Search reference */
723 SecCertificateRef cert
= NULL
; /* Certificate */
724 CFDataRef data
; /* Certificate data */
725 SecPolicyRef policy
= NULL
; /* Policy ref */
726 CFStringRef cfcommon_name
= NULL
;
728 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
729 CFArrayRef list
= NULL
; /* Keychain list */
732 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
740 path
= http_cdsa_default_path(filename
, sizeof(filename
));
742 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
745 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
747 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
750 CFRelease(cfcommon_name
);
755 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
758 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
760 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
761 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
762 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
763 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
764 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
768 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
773 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
776 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
778 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
780 *credentials
= cupsArrayNew(NULL
, NULL
);
781 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
798 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
800 return (*credentials
? 0 : -1);
808 #endif /* HAVE_SECKEYCHAINOPEN */
813 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
815 * @since CUPS 2.0/OS 10.10@
818 int /* O - -1 on error, 0 on success */
820 const char *path
, /* I - Keychain path or @code NULL@ for default */
821 cups_array_t
*credentials
, /* I - Credentials */
822 const char *common_name
) /* I - Common name for credentials */
824 #ifdef HAVE_SECKEYCHAINOPEN
825 int ret
= -1; /* Return value */
826 OSStatus err
; /* Error info */
827 char filename
[1024]; /* Filename for keychain */
828 SecKeychainRef keychain
= NULL
;/* Keychain reference */
829 SecIdentitySearchRef search
= NULL
; /* Search reference */
830 SecCertificateRef cert
= NULL
; /* Certificate */
831 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
832 CFArrayRef list
= NULL
; /* Keychain list */
835 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
839 if (!httpCredentialsAreValidForName(credentials
, common_name
))
841 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
845 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
847 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
852 path
= http_cdsa_default_path(filename
, sizeof(filename
));
854 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
856 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err
));
860 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
862 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
866 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
868 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
872 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
873 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
874 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
876 /* Note: SecItemAdd consumes "attrs"... */
877 err
= SecItemAdd(attrs
, NULL
);
878 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
891 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
901 #endif /* HAVE_SECKEYCHAINOPEN */
906 * '_httpTLSInitialize()' - Initialize the TLS stack.
910 _httpTLSInitialize(void)
919 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
923 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
925 size_t bytes
; /* Bytes that are available */
928 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
936 * '_httpTLSRead()' - Read from a SSL/TLS connection.
939 int /* O - Bytes read */
940 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
941 char *buf
, /* I - Buffer to store data */
942 int len
) /* I - Length of buffer */
944 int result
; /* Return value */
945 OSStatus error
; /* Error info */
946 size_t processed
; /* Number of bytes processed */
949 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
950 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
955 result
= (int)processed
;
958 case errSSLWouldBlock
:
960 result
= (int)processed
;
968 case errSSLClosedGraceful
:
971 result
= (int)processed
;
985 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
989 _httpTLSSetOptions(int options
) /* I - Options */
991 tls_options
= options
;
996 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
999 int /* O - 0 on success, -1 on failure */
1000 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
1002 char hostname
[256], /* Hostname */
1003 *hostptr
; /* Pointer into hostname */
1004 _cups_globals_t
*cg
= _cupsGlobals();
1005 /* Pointer to library globals */
1006 OSStatus error
; /* Error code */
1007 const char *message
= NULL
;/* Error message */
1008 cups_array_t
*credentials
; /* Credentials array */
1009 cups_array_t
*names
; /* CUPS distinguished names */
1010 CFArrayRef dn_array
; /* CF distinguished names array */
1011 CFIndex count
; /* Number of credentials */
1012 CFDataRef data
; /* Certificate data */
1013 int i
; /* Looping var */
1014 http_credential_t
*credential
; /* Credential data */
1017 DEBUG_printf(("7_httpTLSStart(http=%p)", http
));
1019 #ifdef HAVE_SECKEYCHAINOPEN
1020 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1022 if (http
->mode
== _HTTP_MODE_SERVER
)
1023 #endif /* HAVE_SECKEYCHAINOPEN */
1025 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1026 http
->error
= errno
= EINVAL
;
1027 http
->status
= HTTP_STATUS_ERROR
;
1028 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1033 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1035 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1036 http
->error
= errno
= ENOMEM
;
1037 http
->status
= HTTP_STATUS_ERROR
;
1038 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1043 error
= SSLSetConnection(http
->tls
, http
);
1044 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1048 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1049 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1054 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1056 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error
));
1061 error
= SSLSetProtocolVersionMin(http
->tls
, (tls_options
& _HTTP_TLS_ALLOW_SSL3
) ? kSSLProtocol3
: kTLSProtocol1
);
1062 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin, error=%d", (int)error
));
1065 # if USE_SET_ENABLED_CIPHERS
1068 SSLCipherSuite supported
[100]; /* Supported cipher suites */
1069 size_t num_supported
; /* Number of supported cipher suites */
1070 SSLCipherSuite enabled
[100]; /* Cipher suites to enable */
1071 size_t num_enabled
; /* Number of cipher suites to enable */
1073 num_supported
= sizeof(supported
) / sizeof(supported
[0]);
1074 error
= SSLGetSupportedCiphers(http
->tls
, supported
, &num_supported
);
1078 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported
));
1080 for (i
= 0, num_enabled
= 0; i
< (int)num_supported
&& num_enabled
< (sizeof(enabled
) / sizeof(enabled
[0])); i
++)
1082 switch (supported
[i
])
1084 /* Obviously insecure cipher suites that we never want to use */
1085 case SSL_NULL_WITH_NULL_NULL
:
1086 case SSL_RSA_WITH_NULL_MD5
:
1087 case SSL_RSA_WITH_NULL_SHA
:
1088 case SSL_RSA_EXPORT_WITH_RC4_40_MD5
:
1089 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
1090 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1091 case SSL_RSA_WITH_DES_CBC_SHA
:
1092 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1093 case SSL_DH_DSS_WITH_DES_CBC_SHA
:
1094 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1095 case SSL_DH_RSA_WITH_DES_CBC_SHA
:
1096 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1097 case SSL_DHE_DSS_WITH_DES_CBC_SHA
:
1098 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1099 case SSL_DHE_RSA_WITH_DES_CBC_SHA
:
1100 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
:
1101 case SSL_DH_anon_WITH_RC4_128_MD5
:
1102 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
:
1103 case SSL_DH_anon_WITH_DES_CBC_SHA
:
1104 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
:
1105 case SSL_FORTEZZA_DMS_WITH_NULL_SHA
:
1106 case TLS_DH_anon_WITH_AES_128_CBC_SHA
:
1107 case TLS_DH_anon_WITH_AES_256_CBC_SHA
:
1108 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
1109 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
1110 case TLS_ECDH_anon_WITH_NULL_SHA
:
1111 case TLS_ECDH_anon_WITH_RC4_128_SHA
:
1112 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
:
1113 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA
:
1114 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA
:
1115 case TLS_RSA_WITH_NULL_SHA256
:
1116 case TLS_DH_anon_WITH_AES_128_CBC_SHA256
:
1117 case TLS_DH_anon_WITH_AES_256_CBC_SHA256
:
1118 case TLS_PSK_WITH_NULL_SHA
:
1119 case TLS_DHE_PSK_WITH_NULL_SHA
:
1120 case TLS_RSA_PSK_WITH_NULL_SHA
:
1121 case TLS_DH_anon_WITH_AES_128_GCM_SHA256
:
1122 case TLS_DH_anon_WITH_AES_256_GCM_SHA384
:
1123 case TLS_PSK_WITH_NULL_SHA256
:
1124 case TLS_PSK_WITH_NULL_SHA384
:
1125 case TLS_DHE_PSK_WITH_NULL_SHA256
:
1126 case TLS_DHE_PSK_WITH_NULL_SHA384
:
1127 case TLS_RSA_PSK_WITH_NULL_SHA256
:
1128 case TLS_RSA_PSK_WITH_NULL_SHA384
:
1129 case SSL_RSA_WITH_DES_CBC_MD5
:
1132 /* RC4 cipher suites that should only be used as a last resort */
1133 case SSL_RSA_WITH_RC4_128_MD5
:
1134 case SSL_RSA_WITH_RC4_128_SHA
:
1135 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
1136 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
1137 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
1138 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
1139 case TLS_PSK_WITH_RC4_128_SHA
:
1140 case TLS_DHE_PSK_WITH_RC4_128_SHA
:
1141 case TLS_RSA_PSK_WITH_RC4_128_SHA
:
1142 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1143 enabled
[num_enabled
++] = supported
[i
];
1146 /* Anything else we'll assume is secure */
1148 enabled
[num_enabled
++] = supported
[i
];
1153 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled
));
1154 error
= SSLSetEnabledCiphers(http
->tls
, enabled
, num_enabled
);
1157 #endif /* USE_SET_ENABLED_CIPHERS */
1159 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1162 * Client: set client-side credentials, if any...
1165 if (cg
->client_cert_cb
)
1167 error
= SSLSetSessionOption(http
->tls
,
1168 kSSLSessionOptionBreakOnCertRequested
, true);
1169 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1170 "error=%d", (int)error
));
1174 error
= http_cdsa_set_credentials(http
);
1175 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1182 * Server: find/create a certificate for TLS...
1185 if (http
->fields
[HTTP_FIELD_HOST
][0])
1188 * Use hostname for TLS upgrade...
1191 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1196 * Resolve hostname from connection address...
1199 http_addr_t addr
; /* Connection address */
1200 socklen_t addrlen
; /* Length of address */
1202 addrlen
= sizeof(addr
);
1203 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1205 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1208 else if (httpAddrLocalhost(&addr
))
1212 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1213 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1217 #ifdef HAVE_SECKEYCHAINOPEN
1218 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1219 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1222 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1223 else if (tls_common_name
)
1224 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1226 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1228 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1230 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1232 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1233 http
->error
= errno
= EINVAL
;
1234 http
->status
= HTTP_STATUS_ERROR
;
1235 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1240 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1242 #endif /* HAVE_SECKEYCHAINOPEN */
1244 if (!http
->tls_credentials
)
1246 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1247 http
->error
= errno
= EINVAL
;
1248 http
->status
= HTTP_STATUS_ERROR
;
1249 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1254 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1256 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1259 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http
->tls_credentials
));
1262 * Let the server know which hostname/domain we are trying to connect to
1263 * in case it wants to serve up a certificate with a matching common name.
1266 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1269 * Client: get the hostname to use for TLS...
1272 if (httpAddrLocalhost(http
->hostaddr
))
1274 strlcpy(hostname
, "localhost", sizeof(hostname
));
1279 * Otherwise make sure the hostname we have does not end in a trailing dot.
1282 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1283 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1288 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1290 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1295 int done
= 0; /* Are we done yet? */
1297 while (!error
&& !done
)
1299 error
= SSLHandshake(http
->tls
);
1301 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1309 case errSSLWouldBlock
:
1310 error
= noErr
; /* Force a retry */
1311 usleep(1000); /* in 1 millisecond */
1314 case errSSLServerAuthCompleted
:
1316 if (cg
->server_cert_cb
)
1318 error
= httpCopyCredentials(http
, &credentials
);
1321 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1322 cg
->server_cert_data
);
1323 httpFreeCredentials(credentials
);
1326 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1327 "returned %d.", (int)error
));
1331 case errSSLClientCertRequested
:
1334 if (cg
->client_cert_cb
)
1337 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1340 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1342 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1344 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1346 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1348 credential
->datalen
= (size_t)CFDataGetLength(data
);
1349 if ((credential
->data
= malloc(credential
->datalen
)))
1351 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1352 credential
->datalen
);
1353 cupsArrayAdd(names
, credential
);
1361 CFRelease(dn_array
);
1366 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1367 cg
->client_cert_data
);
1369 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1370 "returned %d.", (int)error
));
1373 httpFreeCredentials(names
);
1377 case errSSLUnknownRootCert
:
1378 message
= _("Unable to establish a secure connection to host "
1379 "(untrusted certificate).");
1382 case errSSLNoRootCert
:
1383 message
= _("Unable to establish a secure connection to host "
1384 "(self-signed certificate).");
1387 case errSSLCertExpired
:
1388 message
= _("Unable to establish a secure connection to host "
1389 "(expired certificate).");
1392 case errSSLCertNotYetValid
:
1393 message
= _("Unable to establish a secure connection to host "
1394 "(certificate not yet valid).");
1397 case errSSLHostNameMismatch
:
1398 message
= _("Unable to establish a secure connection to host "
1399 "(host name mismatch).");
1402 case errSSLXCertChainInvalid
:
1403 message
= _("Unable to establish a secure connection to host "
1404 "(certificate chain invalid).");
1407 case errSSLConnectionRefused
:
1408 message
= _("Unable to establish a secure connection to host "
1409 "(peer dropped connection before responding).");
1420 http
->error
= error
;
1421 http
->status
= HTTP_STATUS_ERROR
;
1422 errno
= ECONNREFUSED
;
1424 CFRelease(http
->tls
);
1428 * If an error string wasn't set by the callbacks use a generic one...
1432 #ifdef HAVE_CSSMERRORSTRING
1433 message
= cssmErrorString(error
);
1435 message
= _("Unable to establish a secure connection to host.");
1436 #endif /* HAVE_CSSMERRORSTRING */
1438 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1448 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1452 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1454 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1457 CFRelease(http
->tls
);
1459 if (http
->tls_credentials
)
1460 CFRelease(http
->tls_credentials
);
1463 http
->tls_credentials
= NULL
;
1468 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1471 int /* O - Bytes written */
1472 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1473 const char *buf
, /* I - Buffer holding data */
1474 int len
) /* I - Length of buffer */
1476 ssize_t result
; /* Return value */
1477 OSStatus error
; /* Error info */
1478 size_t processed
; /* Number of bytes processed */
1481 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1483 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1488 result
= (int)processed
;
1491 case errSSLWouldBlock
:
1494 result
= (int)processed
;
1503 case errSSLClosedGraceful
:
1507 result
= (int)processed
;
1517 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1519 return ((int)result
);
1523 #ifdef HAVE_SECKEYCHAINOPEN
1525 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1528 static CFArrayRef
/* O - Array of certificates or NULL */
1529 http_cdsa_copy_server(
1530 const char *common_name
) /* I - Server's hostname */
1532 OSStatus err
; /* Error info */
1533 SecIdentitySearchRef search
= NULL
; /* Search reference */
1534 SecIdentityRef identity
= NULL
;/* Identity */
1535 CFArrayRef certificates
= NULL
;
1536 /* Certificate array */
1537 SecPolicyRef policy
= NULL
; /* Policy ref */
1538 CFStringRef cfcommon_name
= NULL
;
1540 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1541 CFArrayRef list
= NULL
; /* Keychain list */
1544 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1546 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1549 CFRelease(cfcommon_name
);
1554 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1557 _cupsMutexLock(&tls_mutex
);
1559 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1561 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1562 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1563 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1564 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1565 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1569 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1571 _cupsMutexUnlock(&tls_mutex
);
1576 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1579 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1587 CFRelease(identity
);
1594 return (certificates
);
1596 #endif /* HAVE_SECKEYCHAINOPEN */
1600 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1603 static SecCertificateRef
/* O - Certificate */
1604 http_cdsa_create_credential(
1605 http_credential_t
*credential
) /* I - Credential */
1610 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1615 * 'http_cdsa_default_path()' - Get the default keychain path.
1618 static const char * /* O - Keychain path */
1619 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1620 size_t bufsize
) /* I - Size of buffer */
1622 const char *home
= getenv("HOME"); /* HOME environment variable */
1625 if (getuid() && home
)
1626 snprintf(buffer
, bufsize
, "%s/Library/Keychains/login.keychain", home
);
1628 strlcpy(buffer
, "/Library/Keychains/System.keychain", bufsize
);
1630 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1637 * 'http_cdsa_read()' - Read function for the CDSA library.
1640 static OSStatus
/* O - -1 on error, 0 on success */
1642 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1643 void *data
, /* I - Data buffer */
1644 size_t *dataLength
) /* IO - Number of bytes */
1646 OSStatus result
; /* Return value */
1647 ssize_t bytes
; /* Number of bytes read */
1648 http_t
*http
; /* HTTP connection */
1651 http
= (http_t
*)connection
;
1653 if (!http
->blocking
)
1656 * Make sure we have data before we read...
1659 while (!_httpWait(http
, http
->wait_value
, 0))
1661 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1664 http
->error
= ETIMEDOUT
;
1671 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1673 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1675 if ((size_t)bytes
== *dataLength
)
1681 *dataLength
= (size_t)bytes
;
1682 result
= errSSLWouldBlock
;
1689 result
= errSSLClosedGraceful
;
1690 else if (errno
== EAGAIN
)
1691 result
= errSSLWouldBlock
;
1693 result
= errSSLClosedAbort
;
1701 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1704 static int /* O - Status of connection */
1705 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
1707 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1708 OSStatus error
= 0; /* Error code */
1709 http_tls_credentials_t credentials
= NULL
;
1710 /* TLS credentials */
1713 DEBUG_printf(("7http_tls_set_credentials(%p)", http
));
1716 * Prefer connection specific credentials...
1719 if ((credentials
= http
->tls_credentials
) == NULL
)
1720 credentials
= cg
->tls_credentials
;
1724 error
= SSLSetCertificate(http
->tls
, credentials
);
1725 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1729 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1736 * 'http_cdsa_write()' - Write function for the CDSA library.
1739 static OSStatus
/* O - -1 on error, 0 on success */
1741 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1742 const void *data
, /* I - Data buffer */
1743 size_t *dataLength
) /* IO - Number of bytes */
1745 OSStatus result
; /* Return value */
1746 ssize_t bytes
; /* Number of bytes read */
1747 http_t
*http
; /* HTTP connection */
1750 http
= (http_t
*)connection
;
1754 bytes
= write(http
->fd
, data
, *dataLength
);
1756 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1758 if ((size_t)bytes
== *dataLength
)
1762 else if (bytes
>= 0)
1764 *dataLength
= (size_t)bytes
;
1765 result
= errSSLWouldBlock
;
1771 if (errno
== EAGAIN
)
1772 result
= errSSLWouldBlock
;
1774 result
= errSSLClosedAbort
;