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
;
33 #ifdef HAVE_SECKEYCHAINOPEN
34 static int tls_auto_create
= 0;
35 /* Auto-create self-signed certs? */
36 static char *tls_common_name
= NULL
;
37 /* Default common name */
38 static SecKeychainRef tls_keychain
= NULL
;
39 /* Server cert keychain */
40 static char *tls_keypath
= NULL
;
41 /* Server cert keychain path */
42 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
43 /* Mutex for keychain/certs */
44 #endif /* HAVE_SECKEYCHAINOPEN */
51 #ifdef HAVE_SECKEYCHAINOPEN
52 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
53 #endif /* HAVE_SECKEYCHAINOPEN */
54 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
55 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
56 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
57 static int http_cdsa_set_credentials(http_t
*http
);
58 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
62 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
64 * @since CUPS 2.0/OS 10.10@
67 int /* O - 1 on success, 0 on failure */
68 cupsMakeServerCredentials(
69 const char *path
, /* I - Keychain path or @code NULL@ for default */
70 const char *common_name
, /* I - Common name */
71 int num_alt_names
, /* I - Number of subject alternate names */
72 const char **alt_names
, /* I - Subject Alternate Names */
73 time_t expiration_date
) /* I - Expiration date */
75 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE) && defined(HAVE_SECKEYCHAINOPEN)
76 char filename
[1024]; /* Default keychain path */
77 int status
= 0; /* Return status */
78 OSStatus err
; /* Error code (if any) */
79 CFStringRef cfcommon_name
= NULL
;
80 /* CF string for server name */
81 SecIdentityRef ident
= NULL
; /* Identity */
82 SecKeyRef publicKey
= NULL
,
86 CFMutableDictionaryRef keyParams
= NULL
;
87 /* Key generation parameters */
90 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
));
94 (void)expiration_date
;
97 path
= http_cdsa_default_path(filename
, sizeof(filename
));
99 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
104 * Create a public/private key pair...
107 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
111 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
112 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
113 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, CFSTR("CUPS Self-Signed Certificate"));
115 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
120 * Create a self-signed certificate using the public/private key pair...
123 CFIndex usageInt
= kSecKeyUsageAll
;
124 CFNumberRef usage
= CFNumberCreate(alloc
, kCFNumberCFIndexType
, &usageInt
);
125 CFDictionaryRef certParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
,
126 kSecCSRBasicContraintsPathLen
, CFINT(0), kSecSubjectAltName
, cfcommon_name
, kSecCertificateKeyUsage
, usage
, NULL
, NULL
);
129 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
130 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
131 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
132 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
133 const void *ca_dn_array
[2];
135 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
136 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
138 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
139 SecCertificateRef cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
141 CFRelease(certParams
);
146 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
152 * Cleanup and return...
158 CFRelease(cfcommon_name
);
161 CFRelease(keyParams
);
170 CFRelease(publicKey
);
173 CFRelease(publicKey
);
177 #else /* !(HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN) */
178 int pid
, /* Process ID of command */
179 status
, /* Status of command */
181 char command
[1024], /* Command */
182 *argv
[4], /* Command-line arguments */
183 *envp
[1000], /* Environment variables */
184 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
185 keychain
[1024], /* Keychain argument */
186 infofile
[1024], /* Type-in information for cert */
187 filename
[1024]; /* Default keychain path */
188 cups_file_t
*fp
; /* Seed/info file */
191 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
));
197 path
= http_cdsa_default_path(filename
, sizeof(filename
));
200 * Run the "certtool" command to generate a self-signed certificate...
203 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
207 * Create a file with the certificate information fields...
209 * Note: This assumes that the default questions are asked by the certtool
213 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
217 "CUPS Self-Signed Certificate\n"
218 /* Enter key and certificate label */
219 "r\n" /* Generate RSA key pair */
220 "2048\n" /* Key size in bits */
221 "y\n" /* OK (y = yes) */
222 "b\n" /* Usage (b=signing/encryption) */
223 "s\n" /* Sign with SHA1 */
224 "y\n" /* OK (y = yes) */
225 "%s\n" /* Common name */
226 "\n" /* Country (default) */
227 "\n" /* Organization (default) */
228 "\n" /* Organizational unit (default) */
229 "\n" /* State/Province (default) */
230 "\n" /* Email address */
231 "y\n", /* OK (y = yes) */
235 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
237 argv
[0] = "certtool";
242 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
244 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
245 envp
[i
+ 1] = environ
[i
];
248 posix_spawn_file_actions_t actions
; /* File actions */
250 posix_spawn_file_actions_init(&actions
);
251 posix_spawn_file_actions_addclose(&actions
, 0);
252 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
253 posix_spawn_file_actions_addclose(&actions
, 1);
254 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
255 posix_spawn_file_actions_addclose(&actions
, 2);
256 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
258 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
264 posix_spawn_file_actions_destroy(&actions
);
268 while (waitpid(pid
, &status
, 0) < 0)
276 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
281 * 'cupsSetServerCredentials()' - Set the default server credentials.
283 * Note: The server credentials are used by all threads in the running process.
284 * This function is threadsafe.
286 * @since CUPS 2.0/OS X 10.10@
289 int /* O - 1 on success, 0 on failure */
290 cupsSetServerCredentials(
291 const char *path
, /* I - Keychain path or @code NULL@ for default */
292 const char *common_name
, /* I - Default common name for server */
293 int auto_create
) /* I - 1 = automatically create self-signed certificates */
295 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
297 #ifdef HAVE_SECKEYCHAINOPEN
298 char filename
[1024]; /* Filename for keychain */
299 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
303 path
= http_cdsa_default_path(filename
, sizeof(filename
));
305 if (SecKeychainOpen(path
, &keychain
) != noErr
)
307 /* TODO: Set cups last error string */
308 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain, returning 0.");
312 _cupsMutexLock(&tls_mutex
);
315 * Close any keychain that is currently open...
319 CFRelease(tls_keychain
);
322 _cupsStrFree(tls_keypath
);
325 _cupsStrFree(tls_common_name
);
328 * Save the new keychain...
331 tls_keychain
= keychain
;
332 tls_keypath
= _cupsStrAlloc(path
);
333 tls_auto_create
= auto_create
;
334 tls_common_name
= _cupsStrAlloc(common_name
);
336 _cupsMutexUnlock(&tls_mutex
);
338 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
342 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
344 #endif /* HAVE_SECKEYCHAINOPEN */
349 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
350 * an encrypted connection.
352 * @since CUPS 1.5/OS X 10.7@
355 int /* O - Status of call (0 = success) */
357 http_t
*http
, /* I - Connection to server */
358 cups_array_t
**credentials
) /* O - Array of credentials */
360 OSStatus error
; /* Error code */
361 SecTrustRef peerTrust
; /* Peer trust reference */
362 CFIndex count
; /* Number of credentials */
363 SecCertificateRef secCert
; /* Certificate reference */
364 CFDataRef data
; /* Certificate data */
365 int i
; /* Looping var */
368 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
373 if (!http
|| !http
->tls
|| !credentials
)
376 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
378 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
380 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
382 count
= SecTrustGetCertificateCount(peerTrust
);
384 for (i
= 0; i
< count
; i
++)
386 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
389 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
392 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
394 strlcpy(name
, "unknown", sizeof(name
));
396 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
399 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
401 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
403 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
409 CFRelease(peerTrust
);
417 * '_httpCreateCredentials()' - Create credentials in the internal format.
420 http_tls_credentials_t
/* O - Internal credentials */
421 _httpCreateCredentials(
422 cups_array_t
*credentials
) /* I - Array of credentials */
424 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
425 SecCertificateRef secCert
; /* Certificate reference */
426 http_credential_t
*credential
; /* Credential data */
432 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
433 cupsArrayCount(credentials
),
434 &kCFTypeArrayCallBacks
)) == NULL
)
437 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
439 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
441 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
443 CFArrayAppendValue(peerCerts
, secCert
);
453 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
455 * @since CUPS 2.0/OS X 10.10@
458 int /* O - 1 if valid, 0 otherwise */
459 httpCredentialsAreValidForName(
460 cups_array_t
*credentials
, /* I - Credentials */
461 const char *common_name
) /* I - Name to check */
463 SecCertificateRef secCert
; /* Certificate reference */
464 CFStringRef cfcert_name
= NULL
;
465 /* Certificate's common name (CF string) */
466 char cert_name
[256]; /* Certificate's common name (C string) */
467 int valid
= 1; /* Valid name? */
470 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
474 * Compare the common names...
477 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
480 * Can't get common name, cannot be valid...
485 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
486 _cups_strcasecmp(common_name
, cert_name
))
489 * Not an exact match for the common name, check for wildcard certs...
492 const char *domain
= strchr(common_name
, '.');
493 /* Domain in common name */
495 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
498 * Not a wildcard match.
501 /* TODO: Check subject alternate names */
507 CFRelease(cfcert_name
);
516 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
518 * @since CUPS 2.0/OS X 10.10@
521 http_trust_t
/* O - Level of trust */
522 httpCredentialsGetTrust(
523 cups_array_t
*credentials
, /* I - Credentials */
524 const char *common_name
) /* I - Common name for trust lookup */
526 SecCertificateRef secCert
; /* Certificate reference */
527 http_trust_t trust
= HTTP_TRUST_OK
;
529 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
530 _cups_globals_t
*cg
= _cupsGlobals();
531 /* Per-thread globals */
535 return (HTTP_TRUST_UNKNOWN
);
537 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
538 return (HTTP_TRUST_UNKNOWN
);
541 * Look this common name up in the default keychains...
544 httpLoadCredentials(NULL
, &tcreds
, common_name
);
548 char credentials_str
[1024], /* String for incoming credentials */
549 tcreds_str
[1024]; /* String for saved credentials */
551 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
552 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
554 if (strcmp(credentials_str
, tcreds_str
))
557 * Credentials don't match, let's look at the expiration date of the new
558 * credentials and allow if the new ones have a later expiration...
561 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
562 !httpCredentialsAreValidForName(credentials
, common_name
))
565 * Either the new credentials are not newly issued, or the common name
566 * does not match the issued certificate...
569 trust
= HTTP_TRUST_INVALID
;
571 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
574 * Save the renewed credentials...
577 trust
= HTTP_TRUST_RENEWED
;
579 httpSaveCredentials(NULL
, credentials
, common_name
);
583 httpFreeCredentials(tcreds
);
585 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
586 trust
= HTTP_TRUST_INVALID
;
588 if (!cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
589 trust
= HTTP_TRUST_EXPIRED
;
590 else if (!cg
->any_root
&& cupsArrayCount(credentials
) == 1)
591 trust
= HTTP_TRUST_INVALID
;
600 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
602 * @since CUPS 2.0/OS X 10.10@
605 time_t /* O - Expiration date of credentials */
606 httpCredentialsGetExpiration(
607 cups_array_t
*credentials
) /* I - Credentials */
609 SecCertificateRef secCert
; /* Certificate reference */
610 time_t expiration
; /* Expiration date */
613 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
616 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
625 * 'httpCredentialsString()' - Return a string representing the credentials.
627 * @since CUPS 2.0/OS X 10.10@
630 size_t /* O - Total size of credentials string */
631 httpCredentialsString(
632 cups_array_t
*credentials
, /* I - Credentials */
633 char *buffer
, /* I - Buffer or @code NULL@ */
634 size_t bufsize
) /* I - Size of buffer */
636 http_credential_t
*first
; /* First certificate */
637 SecCertificateRef secCert
; /* Certificate reference */
640 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
645 if (buffer
&& bufsize
> 0)
648 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
649 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
651 CFStringRef cf_name
; /* CF common name string */
652 char name
[256]; /* Common name associated with cert */
653 time_t expiration
; /* Expiration date of cert */
654 _cups_md5_state_t md5_state
; /* MD5 state */
655 unsigned char md5_digest
[16]; /* MD5 result */
657 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
659 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
663 strlcpy(name
, "unknown", sizeof(name
));
665 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
667 _cupsMD5Init(&md5_state
);
668 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
669 _cupsMD5Finish(&md5_state
, md5_digest
);
671 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]);
676 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
678 return (strlen(buffer
));
683 * '_httpFreeCredentials()' - Free internal credentials.
687 _httpFreeCredentials(
688 http_tls_credentials_t credentials
) /* I - Internal credentials */
693 CFRelease(credentials
);
698 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
700 * @since CUPS 2.0/OS 10.10@
703 int /* O - 0 on success, -1 on error */
705 const char *path
, /* I - Keychain path or @code NULL@ for default */
706 cups_array_t
**credentials
, /* IO - Credentials */
707 const char *common_name
) /* I - Common name for credentials */
709 #ifdef HAVE_SECKEYCHAINOPEN
710 OSStatus err
; /* Error info */
711 char filename
[1024]; /* Filename for keychain */
712 SecKeychainRef keychain
= NULL
;/* Keychain reference */
713 SecIdentitySearchRef search
= NULL
; /* Search reference */
714 SecCertificateRef cert
= NULL
; /* Certificate */
715 CFDataRef data
; /* Certificate data */
716 SecPolicyRef policy
= NULL
; /* Policy ref */
717 CFStringRef cfcommon_name
= NULL
;
719 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
720 CFArrayRef list
= NULL
; /* Keychain list */
723 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
731 path
= http_cdsa_default_path(filename
, sizeof(filename
));
733 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
736 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
738 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
741 CFRelease(cfcommon_name
);
746 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
749 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
751 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
752 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
753 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
754 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
755 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
759 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
764 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
767 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
769 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
771 *credentials
= cupsArrayNew(NULL
, NULL
);
772 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
789 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
791 return (*credentials
? 0 : -1);
799 #endif /* HAVE_SECKEYCHAINOPEN */
804 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
806 * @since CUPS 2.0/OS 10.10@
809 int /* O - -1 on error, 0 on success */
811 const char *path
, /* I - Keychain path or @code NULL@ for default */
812 cups_array_t
*credentials
, /* I - Credentials */
813 const char *common_name
) /* I - Common name for credentials */
815 #ifdef HAVE_SECKEYCHAINOPEN
816 int ret
= -1; /* Return value */
817 OSStatus err
; /* Error info */
818 char filename
[1024]; /* Filename for keychain */
819 SecKeychainRef keychain
= NULL
;/* Keychain reference */
820 SecIdentitySearchRef search
= NULL
; /* Search reference */
821 SecCertificateRef cert
= NULL
; /* Certificate */
822 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
823 CFArrayRef list
= NULL
; /* Keychain list */
826 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
830 if (!httpCredentialsAreValidForName(credentials
, common_name
))
832 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
836 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
838 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
843 path
= http_cdsa_default_path(filename
, sizeof(filename
));
845 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
847 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err
));
851 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
853 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
857 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
859 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
863 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
864 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
865 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
867 /* Note: SecItemAdd consumes "attrs"... */
868 err
= SecItemAdd(attrs
, NULL
);
869 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
882 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
892 #endif /* HAVE_SECKEYCHAINOPEN */
897 * '_httpTLSInitialize()' - Initialize the TLS stack.
901 _httpTLSInitialize(void)
910 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
914 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
916 size_t bytes
; /* Bytes that are available */
919 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
927 * '_httpTLSRead()' - Read from a SSL/TLS connection.
930 int /* O - Bytes read */
931 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
932 char *buf
, /* I - Buffer to store data */
933 int len
) /* I - Length of buffer */
935 int result
; /* Return value */
936 OSStatus error
; /* Error info */
937 size_t processed
; /* Number of bytes processed */
940 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
941 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
946 result
= (int)processed
;
949 case errSSLWouldBlock
:
951 result
= (int)processed
;
959 case errSSLClosedGraceful
:
962 result
= (int)processed
;
976 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
979 int /* O - 0 on success, -1 on failure */
980 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
982 char hostname
[256], /* Hostname */
983 *hostptr
; /* Pointer into hostname */
984 _cups_globals_t
*cg
= _cupsGlobals();
985 /* Pointer to library globals */
986 OSStatus error
; /* Error code */
987 const char *message
= NULL
;/* Error message */
988 cups_array_t
*credentials
; /* Credentials array */
989 cups_array_t
*names
; /* CUPS distinguished names */
990 CFArrayRef dn_array
; /* CF distinguished names array */
991 CFIndex count
; /* Number of credentials */
992 CFDataRef data
; /* Certificate data */
993 int i
; /* Looping var */
994 http_credential_t
*credential
; /* Credential data */
997 DEBUG_printf(("7_httpTLSStart(http=%p)", http
));
999 #ifdef HAVE_SECKEYCHAINOPEN
1000 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1002 if (http
->mode
== _HTTP_MODE_SERVER
)
1003 #endif /* HAVE_SECKEYCHAINOPEN */
1005 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1006 http
->error
= errno
= EINVAL
;
1007 http
->status
= HTTP_STATUS_ERROR
;
1008 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1013 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1015 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1016 http
->error
= errno
= ENOMEM
;
1017 http
->status
= HTTP_STATUS_ERROR
;
1018 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1023 error
= SSLSetConnection(http
->tls
, http
);
1024 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1028 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1029 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1034 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1036 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d",
1040 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1043 * Client: set client-side credentials, if any...
1046 if (cg
->client_cert_cb
)
1048 error
= SSLSetSessionOption(http
->tls
,
1049 kSSLSessionOptionBreakOnCertRequested
, true);
1050 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1051 "error=%d", (int)error
));
1055 error
= http_cdsa_set_credentials(http
);
1056 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1063 * Server: find/create a certificate for TLS...
1066 if (http
->fields
[HTTP_FIELD_HOST
][0])
1069 * Use hostname for TLS upgrade...
1072 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1077 * Resolve hostname from connection address...
1080 http_addr_t addr
; /* Connection address */
1081 socklen_t addrlen
; /* Length of address */
1083 addrlen
= sizeof(addr
);
1084 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1086 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1089 else if (httpAddrLocalhost(&addr
))
1093 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1094 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1098 #ifdef HAVE_SECKEYCHAINOPEN
1099 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1100 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1103 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1104 else if (tls_common_name
)
1105 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1107 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1109 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1111 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1113 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1114 http
->error
= errno
= EINVAL
;
1115 http
->status
= HTTP_STATUS_ERROR
;
1116 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1121 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1123 #endif /* HAVE_SECKEYCHAINOPEN */
1125 if (!http
->tls_credentials
)
1127 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1128 http
->error
= errno
= EINVAL
;
1129 http
->status
= HTTP_STATUS_ERROR
;
1130 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1135 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1137 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1140 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http
->tls_credentials
));
1143 * Let the server know which hostname/domain we are trying to connect to
1144 * in case it wants to serve up a certificate with a matching common name.
1147 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1150 * Client: get the hostname to use for TLS...
1153 if (httpAddrLocalhost(http
->hostaddr
))
1155 strlcpy(hostname
, "localhost", sizeof(hostname
));
1160 * Otherwise make sure the hostname we have does not end in a trailing dot.
1163 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1164 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1169 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1171 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1176 int done
= 0; /* Are we done yet? */
1178 while (!error
&& !done
)
1180 error
= SSLHandshake(http
->tls
);
1182 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1190 case errSSLWouldBlock
:
1191 error
= noErr
; /* Force a retry */
1192 usleep(1000); /* in 1 millisecond */
1195 case errSSLServerAuthCompleted
:
1197 if (cg
->server_cert_cb
)
1199 error
= httpCopyCredentials(http
, &credentials
);
1202 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1203 cg
->server_cert_data
);
1204 httpFreeCredentials(credentials
);
1207 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1208 "returned %d.", (int)error
));
1212 case errSSLClientCertRequested
:
1215 if (cg
->client_cert_cb
)
1218 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1221 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1223 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1225 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1227 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1229 credential
->datalen
= (size_t)CFDataGetLength(data
);
1230 if ((credential
->data
= malloc(credential
->datalen
)))
1232 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1233 credential
->datalen
);
1234 cupsArrayAdd(names
, credential
);
1242 CFRelease(dn_array
);
1247 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1248 cg
->client_cert_data
);
1250 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1251 "returned %d.", (int)error
));
1254 httpFreeCredentials(names
);
1258 case errSSLUnknownRootCert
:
1259 message
= _("Unable to establish a secure connection to host "
1260 "(untrusted certificate).");
1263 case errSSLNoRootCert
:
1264 message
= _("Unable to establish a secure connection to host "
1265 "(self-signed certificate).");
1268 case errSSLCertExpired
:
1269 message
= _("Unable to establish a secure connection to host "
1270 "(expired certificate).");
1273 case errSSLCertNotYetValid
:
1274 message
= _("Unable to establish a secure connection to host "
1275 "(certificate not yet valid).");
1278 case errSSLHostNameMismatch
:
1279 message
= _("Unable to establish a secure connection to host "
1280 "(host name mismatch).");
1283 case errSSLXCertChainInvalid
:
1284 message
= _("Unable to establish a secure connection to host "
1285 "(certificate chain invalid).");
1288 case errSSLConnectionRefused
:
1289 message
= _("Unable to establish a secure connection to host "
1290 "(peer dropped connection before responding).");
1301 http
->error
= error
;
1302 http
->status
= HTTP_STATUS_ERROR
;
1303 errno
= ECONNREFUSED
;
1305 CFRelease(http
->tls
);
1309 * If an error string wasn't set by the callbacks use a generic one...
1313 #ifdef HAVE_CSSMERRORSTRING
1314 message
= cssmErrorString(error
);
1316 message
= _("Unable to establish a secure connection to host.");
1317 #endif /* HAVE_CSSMERRORSTRING */
1319 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1329 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1333 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1335 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1338 CFRelease(http
->tls
);
1340 if (http
->tls_credentials
)
1341 CFRelease(http
->tls_credentials
);
1344 http
->tls_credentials
= NULL
;
1349 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1352 int /* O - Bytes written */
1353 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1354 const char *buf
, /* I - Buffer holding data */
1355 int len
) /* I - Length of buffer */
1357 ssize_t result
; /* Return value */
1358 OSStatus error
; /* Error info */
1359 size_t processed
; /* Number of bytes processed */
1362 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1364 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1369 result
= (int)processed
;
1372 case errSSLWouldBlock
:
1375 result
= (int)processed
;
1384 case errSSLClosedGraceful
:
1388 result
= (int)processed
;
1398 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1400 return ((int)result
);
1404 #ifdef HAVE_SECKEYCHAINOPEN
1406 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1409 static CFArrayRef
/* O - Array of certificates or NULL */
1410 http_cdsa_copy_server(
1411 const char *common_name
) /* I - Server's hostname */
1413 OSStatus err
; /* Error info */
1414 SecIdentitySearchRef search
= NULL
; /* Search reference */
1415 SecIdentityRef identity
= NULL
;/* Identity */
1416 CFArrayRef certificates
= NULL
;
1417 /* Certificate array */
1418 SecPolicyRef policy
= NULL
; /* Policy ref */
1419 CFStringRef cfcommon_name
= NULL
;
1421 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1422 CFArrayRef list
= NULL
; /* Keychain list */
1425 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1427 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1430 CFRelease(cfcommon_name
);
1435 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1438 _cupsMutexLock(&tls_mutex
);
1440 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1442 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1443 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1444 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1445 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1446 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1450 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1452 _cupsMutexUnlock(&tls_mutex
);
1457 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1460 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1468 CFRelease(identity
);
1475 return (certificates
);
1477 #endif /* HAVE_SECKEYCHAINOPEN */
1481 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1484 static SecCertificateRef
/* O - Certificate */
1485 http_cdsa_create_credential(
1486 http_credential_t
*credential
) /* I - Credential */
1491 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1496 * 'http_cdsa_default_path()' - Get the default keychain path.
1499 static const char * /* O - Keychain path */
1500 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1501 size_t bufsize
) /* I - Size of buffer */
1503 const char *home
= getenv("HOME"); /* HOME environment variable */
1506 if (getuid() && home
)
1507 snprintf(buffer
, bufsize
, "%s/Library/Keychains/login.keychain", home
);
1509 strlcpy(buffer
, "/Library/Keychains/System.keychain", bufsize
);
1511 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1518 * 'http_cdsa_read()' - Read function for the CDSA library.
1521 static OSStatus
/* O - -1 on error, 0 on success */
1523 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1524 void *data
, /* I - Data buffer */
1525 size_t *dataLength
) /* IO - Number of bytes */
1527 OSStatus result
; /* Return value */
1528 ssize_t bytes
; /* Number of bytes read */
1529 http_t
*http
; /* HTTP connection */
1532 http
= (http_t
*)connection
;
1534 if (!http
->blocking
)
1537 * Make sure we have data before we read...
1540 while (!_httpWait(http
, http
->wait_value
, 0))
1542 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1545 http
->error
= ETIMEDOUT
;
1552 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1554 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1556 if ((size_t)bytes
== *dataLength
)
1562 *dataLength
= (size_t)bytes
;
1563 result
= errSSLWouldBlock
;
1570 result
= errSSLClosedGraceful
;
1571 else if (errno
== EAGAIN
)
1572 result
= errSSLWouldBlock
;
1574 result
= errSSLClosedAbort
;
1582 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1585 static int /* O - Status of connection */
1586 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
1588 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1589 OSStatus error
= 0; /* Error code */
1590 http_tls_credentials_t credentials
= NULL
;
1591 /* TLS credentials */
1594 DEBUG_printf(("7http_tls_set_credentials(%p)", http
));
1597 * Prefer connection specific credentials...
1600 if ((credentials
= http
->tls_credentials
) == NULL
)
1601 credentials
= cg
->tls_credentials
;
1605 error
= SSLSetCertificate(http
->tls
, credentials
);
1606 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1610 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1617 * 'http_cdsa_write()' - Write function for the CDSA library.
1620 static OSStatus
/* O - -1 on error, 0 on success */
1622 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1623 const void *data
, /* I - Data buffer */
1624 size_t *dataLength
) /* IO - Number of bytes */
1626 OSStatus result
; /* Return value */
1627 ssize_t bytes
; /* Number of bytes read */
1628 http_t
*http
; /* HTTP connection */
1631 http
= (http_t
*)connection
;
1635 bytes
= write(http
->fd
, data
, *dataLength
);
1637 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1639 if ((size_t)bytes
== *dataLength
)
1643 else if (bytes
>= 0)
1645 *dataLength
= (size_t)bytes
;
1646 result
= errSSLWouldBlock
;
1652 if (errno
== EAGAIN
)
1653 result
= errSSLWouldBlock
;
1655 result
= errSSLClosedAbort
;