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 http.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 OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
55 static int http_cdsa_set_credentials(http_t
*http
);
56 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
60 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
65 int /* O - 1 on success, 0 on failure */
66 cupsMakeServerCredentials(
67 const char *path
, /* I - Path to keychain/directory */
68 const char *common_name
, /* I - Common name */
69 int num_alt_names
, /* I - Number of subject alternate names */
70 const char **alt_names
, /* I - Subject Alternate Names */
71 time_t expiration_date
) /* I - Expiration date */
73 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE) && defined(HAVE_SECKEYCHAINOPEN)
74 int status
= 0; /* Return status */
75 OSStatus err
; /* Error code (if any) */
76 CFStringRef cfcommon_name
= NULL
;
77 /* CF string for server name */
78 SecIdentityRef ident
= NULL
; /* Identity */
79 SecKeyRef publicKey
= NULL
,
83 CFMutableDictionaryRef keyParams
= NULL
;
84 /* Key generation parameters */
89 (void)expiration_date
;
91 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
,
92 kCFStringEncodingUTF8
);
97 * Create a public/private key pair...
100 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
101 &kCFTypeDictionaryKeyCallBacks
,
102 &kCFTypeDictionaryValueCallBacks
);
106 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
107 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
108 CFDictionaryAddValue(keyParams
, kSecAttrLabel
,
109 CFSTR("CUPS Self-Signed Certificate"));
111 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
116 * Create a self-signed certificate using the public/private key pair...
119 CFIndex usageInt
= kSecKeyUsageAll
;
120 CFNumberRef usage
= CFNumberCreate(alloc
, kCFNumberCFIndexType
, &usageInt
);
121 CFDictionaryRef certParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
,
122 kSecCSRBasicContraintsPathLen
, CFINT(0), kSecSubjectAltName
, cfcommon_name
, kSecCertificateKeyUsage
, usage
, NULL
, NULL
);
125 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
126 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
127 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
128 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
129 const void *ca_dn_array
[2];
131 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
132 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
134 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
135 SecCertificateRef cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
137 CFRelease(certParams
);
142 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
148 * Cleanup and return...
154 CFRelease(cfcommon_name
);
157 CFRelease(keyParams
);
166 CFRelease(publicKey
);
169 CFRelease(publicKey
);
173 #else /* !(HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN) */
174 int pid
, /* Process ID of command */
175 status
, /* Status of command */
177 char command
[1024], /* Command */
178 *argv
[4], /* Command-line arguments */
179 *envp
[1000], /* Environment variables */
180 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
181 keychain
[1024], /* Keychain argument */
182 infofile
[1024]; /* Type-in information for cert */
183 cups_file_t
*fp
; /* Seed/info file */
190 * Run the "certtool" command to generate a self-signed certificate...
193 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
197 * Create a file with the certificate information fields...
199 * Note: This assumes that the default questions are asked by the certtool
203 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
207 "CUPS Self-Signed Certificate\n"
208 /* Enter key and certificate label */
209 "r\n" /* Generate RSA key pair */
210 "2048\n" /* Key size in bits */
211 "y\n" /* OK (y = yes) */
212 "b\n" /* Usage (b=signing/encryption) */
213 "s\n" /* Sign with SHA1 */
214 "y\n" /* OK (y = yes) */
215 "%s\n" /* Common name */
216 "\n" /* Country (default) */
217 "\n" /* Organization (default) */
218 "\n" /* Organizational unit (default) */
219 "\n" /* State/Province (default) */
220 "\n" /* Email address */
221 "y\n", /* OK (y = yes) */
225 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
227 argv
[0] = "certtool";
232 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
234 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
235 envp
[i
+ 1] = environ
[i
];
238 posix_spawn_file_actions_t actions
; /* File actions */
240 posix_spawn_file_actions_init(&actions
);
241 posix_spawn_file_actions_addclose(&actions
, 0);
242 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
244 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
250 posix_spawn_file_actions_destroy(&actions
);
254 while (waitpid(pid
, &status
, 0) < 0)
262 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
267 * 'cupsSetServerCredentials()' - Set the default server credentials.
269 * Note: The server credentials are used by all threads in the running process.
270 * This function is threadsafe.
275 int /* O - 1 on success, 0 on failure */
276 cupsSetServerCredentials(
277 const char *path
, /* I - Path to keychain/directory */
278 const char *common_name
, /* I - Default common name for server */
279 int auto_create
) /* I - 1 = automatically create self-signed certificates */
281 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
283 #ifdef HAVE_SECKEYCHAINOPEN
284 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
287 if (SecKeychainOpen(path
, &keychain
) != noErr
)
289 /* TODO: Set cups last error string */
290 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain, returning 0.");
294 _cupsMutexLock(&tls_mutex
);
297 * Close any keychain that is currently open...
301 CFRelease(tls_keychain
);
304 _cupsStrFree(tls_keypath
);
307 _cupsStrFree(tls_common_name
);
310 * Save the new keychain...
313 tls_keychain
= keychain
;
314 tls_keypath
= _cupsStrAlloc(path
);
315 tls_auto_create
= auto_create
;
316 tls_common_name
= _cupsStrAlloc(common_name
);
318 _cupsMutexUnlock(&tls_mutex
);
320 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
324 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
326 #endif /* HAVE_SECKEYCHAINOPEN */
331 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
332 * an encrypted connection.
334 * @since CUPS 1.5/OS X 10.7@
337 int /* O - Status of call (0 = success) */
339 http_t
*http
, /* I - Connection to server */
340 cups_array_t
**credentials
) /* O - Array of credentials */
342 OSStatus error
; /* Error code */
343 SecTrustRef peerTrust
; /* Peer trust reference */
344 CFIndex count
; /* Number of credentials */
345 SecCertificateRef secCert
; /* Certificate reference */
346 CFDataRef data
; /* Certificate data */
347 int i
; /* Looping var */
350 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
355 if (!http
|| !http
->tls
|| !credentials
)
358 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
360 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
362 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
364 count
= SecTrustGetCertificateCount(peerTrust
);
366 for (i
= 0; i
< count
; i
++)
368 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
371 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
374 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
376 strlcpy(name
, "unknown", sizeof(name
));
378 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
381 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
383 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
385 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
391 CFRelease(peerTrust
);
399 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
402 static SecCertificateRef
/* O - Certificate */
403 http_cdsa_create_credential(
404 http_credential_t
*credential
) /* I - Credential */
409 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
414 * '_httpCreateCredentials()' - Create credentials in the internal format.
417 http_tls_credentials_t
/* O - Internal credentials */
418 _httpCreateCredentials(
419 cups_array_t
*credentials
) /* I - Array of credentials */
421 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
422 SecCertificateRef secCert
; /* Certificate reference */
423 http_credential_t
*credential
; /* Credential data */
429 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
430 cupsArrayCount(credentials
),
431 &kCFTypeArrayCallBacks
)) == NULL
)
434 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
436 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
438 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
440 CFArrayAppendValue(peerCerts
, secCert
);
450 * 'httpCredentialsAreTrusted()' - Return whether the credentials are trusted.
455 int /* O - 1 if trusted, 0 if not/unknown */
456 httpCredentialsAreTrusted(
457 cups_array_t
*credentials
, /* I - Credentials */
458 const char *common_name
) /* I - Common name for trust lookup */
460 SecCertificateRef secCert
; /* Certificate reference */
461 int trusted
= 1; /* Trusted? */
462 int save
= 0; /* Save credentials? */
463 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
464 _cups_globals_t
*cg
= _cupsGlobals();
465 /* Per-thread globals */
471 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
475 * Look this common name up in the default keychains...
478 httpLoadCredentials(NULL
, &tcreds
, common_name
);
482 char credentials_str
[1024], /* String for incoming credentials */
483 tcreds_str
[1024]; /* String for saved credentials */
485 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
486 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
488 if (strcmp(credentials_str
, tcreds_str
))
491 * Credentials don't match, let's look at the expiration date of the new
492 * credentials and allow if the new ones have a later expiration...
495 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
496 !httpCredentialsIsValidName(credentials
, common_name
))
499 * Either the new credentials are not newly issued, or the common name
500 * does not match the issued certificate...
508 * Flag that we should save the new credentials...
515 httpFreeCredentials(tcreds
);
517 else if (!httpCredentialsIsValidName(credentials
, common_name
))
522 if (!cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
524 else if (!cg
->any_root
&& cupsArrayCount(credentials
) == 1)
528 httpSaveCredentials(NULL
, credentials
, common_name
);
537 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
542 time_t /* O - Expiration date of credentials */
543 httpCredentialsGetExpiration(
544 cups_array_t
*credentials
) /* I - Credentials */
546 SecCertificateRef secCert
; /* Certificate reference */
547 time_t expiration
; /* Expiration date */
550 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
553 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
562 * 'httpCredentialsIsValidName()' - Return whether the credentials are valid for the given name.
567 int /* O - 1 if valid, 0 otherwise */
568 httpCredentialsIsValidName(
569 cups_array_t
*credentials
, /* I - Credentials */
570 const char *common_name
) /* I - Name to check */
572 SecCertificateRef secCert
; /* Certificate reference */
573 CFStringRef cfcert_name
= NULL
;
574 /* Certificate's common name (CF string) */
575 char cert_name
[256]; /* Certificate's common name (C string) */
576 int valid
= 1; /* Valid name? */
579 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
583 * Compare the common names...
586 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
589 * Can't get common name, cannot be valid...
594 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
595 _cups_strcasecmp(common_name
, cert_name
))
598 * Not an exact match for the common name, check for wildcard certs...
601 const char *domain
= strchr(common_name
, '.');
602 /* Domain in common name */
604 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
607 * Not a wildcard match.
610 /* TODO: Check subject alternate names */
616 CFRelease(cfcert_name
);
625 * 'httpCredentialsString()' - Return a string representing the credentials.
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.
703 int /* O - 0 on success, -1 on error */
705 const char *path
, /* I - Keychain/PKCS#12 path */
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
));
732 const char *home
= getenv("HOME"); /* HOME environment variable */
734 if (getuid() && home
)
735 snprintf(filename
, sizeof(filename
), "%s/Library/Keychains/login.keychain", home
);
737 strlcpy(filename
, "/Library/Keychains/System.keychain", sizeof(filename
));
741 DEBUG_printf(("1httpLoadCredentials: Using default path \"%s\".", path
));
745 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
748 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
750 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
753 CFRelease(cfcommon_name
);
758 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
761 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
763 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
764 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
765 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
766 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
767 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
771 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
776 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
779 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
781 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
783 *credentials
= cupsArrayNew(NULL
, NULL
);
784 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
801 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
803 return (*credentials
? 0 : -1);
811 #endif /* HAVE_SECKEYCHAINOPEN */
816 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
821 int /* O - -1 on error, 0 on success */
823 const char *path
, /* I - Keychain/PKCS#12 path */
824 cups_array_t
*credentials
, /* I - Credentials */
825 const char *common_name
) /* I - Common name for credentials */
827 #ifdef HAVE_SECKEYCHAINOPEN
828 int ret
= -1; /* Return value */
829 OSStatus err
; /* Error info */
830 char filename
[1024]; /* Filename for keychain */
831 SecKeychainRef keychain
= NULL
;/* Keychain reference */
832 SecIdentitySearchRef search
= NULL
; /* Search reference */
833 SecCertificateRef cert
= NULL
; /* Certificate */
834 CFStringRef cfcommon_name
= NULL
;
836 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
837 CFArrayRef list
= NULL
; /* Keychain list */
840 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
844 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
846 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
852 const char *home
= getenv("HOME"); /* HOME environment variable */
854 if (getuid() && home
)
855 snprintf(filename
, sizeof(filename
), "%s/Library/Keychains/login.keychain", home
);
857 strlcpy(filename
, "/Library/Keychains/System.keychain", sizeof(filename
));
861 DEBUG_printf(("1httpSaveCredentials: Using default path \"%s\".", path
));
864 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
866 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err
));
870 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
872 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
876 if ((cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
)) == NULL
)
878 DEBUG_puts("1httpSaveCredentials: Unable to create common name string.");
882 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
884 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
888 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
889 CFDictionaryAddValue(attrs
, kSecAttrLabel
, cfcommon_name
);
890 CFDictionaryAddValue(attrs
, kSecAttrSubject
, cfcommon_name
);
891 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
892 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
894 /* Note: SecItemAdd consumes "attrs"... */
895 if ((err
= SecItemAdd(attrs
, NULL
)) == noErr
)
898 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
903 CFRelease(cfcommon_name
);
913 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
923 #endif /* HAVE_SECKEYCHAINOPEN */
928 * '_httpTLSInitialize()' - Initialize the TLS stack.
932 _httpTLSInitialize(void)
941 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
945 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
947 size_t bytes
; /* Bytes that are available */
950 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
958 * '_httpTLSRead()' - Read from a SSL/TLS connection.
961 int /* O - Bytes read */
962 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
963 char *buf
, /* I - Buffer to store data */
964 int len
) /* I - Length of buffer */
966 int result
; /* Return value */
967 OSStatus error
; /* Error info */
968 size_t processed
; /* Number of bytes processed */
971 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
972 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
977 result
= (int)processed
;
980 case errSSLWouldBlock
:
982 result
= (int)processed
;
990 case errSSLClosedGraceful
:
993 result
= (int)processed
;
1007 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1010 int /* O - 0 on success, -1 on failure */
1011 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
1013 char hostname
[256], /* Hostname */
1014 *hostptr
; /* Pointer into hostname */
1015 _cups_globals_t
*cg
= _cupsGlobals();
1016 /* Pointer to library globals */
1017 OSStatus error
; /* Error code */
1018 const char *message
= NULL
;/* Error message */
1019 cups_array_t
*credentials
; /* Credentials array */
1020 cups_array_t
*names
; /* CUPS distinguished names */
1021 CFArrayRef dn_array
; /* CF distinguished names array */
1022 CFIndex count
; /* Number of credentials */
1023 CFDataRef data
; /* Certificate data */
1024 int i
; /* Looping var */
1025 http_credential_t
*credential
; /* Credential data */
1028 DEBUG_printf(("7_httpTLSStart(http=%p)", http
));
1030 #ifdef HAVE_SECKEYCHAINOPEN
1031 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1033 if (http
->mode
== _HTTP_MODE_SERVER
)
1034 #endif /* HAVE_SECKEYCHAINOPEN */
1036 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1037 http
->error
= errno
= EINVAL
;
1038 http
->status
= HTTP_STATUS_ERROR
;
1039 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1044 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1046 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1047 http
->error
= errno
= ENOMEM
;
1048 http
->status
= HTTP_STATUS_ERROR
;
1049 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1054 error
= SSLSetConnection(http
->tls
, http
);
1055 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1059 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1060 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1065 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1067 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d",
1071 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1074 * Client: set client-side credentials, if any...
1077 if (cg
->client_cert_cb
)
1079 error
= SSLSetSessionOption(http
->tls
,
1080 kSSLSessionOptionBreakOnCertRequested
, true);
1081 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1082 "error=%d", (int)error
));
1086 error
= http_cdsa_set_credentials(http
);
1087 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1094 * Server: find/create a certificate for TLS...
1097 if (http
->fields
[HTTP_FIELD_HOST
][0])
1100 * Use hostname for TLS upgrade...
1103 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1108 * Resolve hostname from connection address...
1111 http_addr_t addr
; /* Connection address */
1112 socklen_t addrlen
; /* Length of address */
1114 addrlen
= sizeof(addr
);
1115 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1117 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1120 else if (httpAddrLocalhost(&addr
))
1124 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1125 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1129 #ifdef HAVE_SECKEYCHAINOPEN
1130 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1131 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1134 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1135 else if (tls_common_name
)
1136 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1138 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1140 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1142 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1144 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1145 http
->error
= errno
= EINVAL
;
1146 http
->status
= HTTP_STATUS_ERROR
;
1147 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1152 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1154 #endif /* HAVE_SECKEYCHAINOPEN */
1156 if (!http
->tls_credentials
)
1158 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1159 http
->error
= errno
= EINVAL
;
1160 http
->status
= HTTP_STATUS_ERROR
;
1161 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1166 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1168 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1171 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http
->tls_credentials
));
1174 * Let the server know which hostname/domain we are trying to connect to
1175 * in case it wants to serve up a certificate with a matching common name.
1178 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1181 * Client: get the hostname to use for TLS...
1184 if (httpAddrLocalhost(http
->hostaddr
))
1186 strlcpy(hostname
, "localhost", sizeof(hostname
));
1191 * Otherwise make sure the hostname we have does not end in a trailing dot.
1194 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1195 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1200 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1202 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1207 int done
= 0; /* Are we done yet? */
1209 while (!error
&& !done
)
1211 error
= SSLHandshake(http
->tls
);
1213 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1221 case errSSLWouldBlock
:
1222 error
= noErr
; /* Force a retry */
1223 usleep(1000); /* in 1 millisecond */
1226 case errSSLServerAuthCompleted
:
1228 if (cg
->server_cert_cb
)
1230 error
= httpCopyCredentials(http
, &credentials
);
1233 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1234 cg
->server_cert_data
);
1235 httpFreeCredentials(credentials
);
1238 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1239 "returned %d.", (int)error
));
1243 case errSSLClientCertRequested
:
1246 if (cg
->client_cert_cb
)
1249 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1252 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1254 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1256 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1258 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1260 credential
->datalen
= (size_t)CFDataGetLength(data
);
1261 if ((credential
->data
= malloc(credential
->datalen
)))
1263 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1264 credential
->datalen
);
1265 cupsArrayAdd(names
, credential
);
1273 CFRelease(dn_array
);
1278 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1279 cg
->client_cert_data
);
1281 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1282 "returned %d.", (int)error
));
1285 httpFreeCredentials(names
);
1289 case errSSLUnknownRootCert
:
1290 message
= _("Unable to establish a secure connection to host "
1291 "(untrusted certificate).");
1294 case errSSLNoRootCert
:
1295 message
= _("Unable to establish a secure connection to host "
1296 "(self-signed certificate).");
1299 case errSSLCertExpired
:
1300 message
= _("Unable to establish a secure connection to host "
1301 "(expired certificate).");
1304 case errSSLCertNotYetValid
:
1305 message
= _("Unable to establish a secure connection to host "
1306 "(certificate not yet valid).");
1309 case errSSLHostNameMismatch
:
1310 message
= _("Unable to establish a secure connection to host "
1311 "(host name mismatch).");
1314 case errSSLXCertChainInvalid
:
1315 message
= _("Unable to establish a secure connection to host "
1316 "(certificate chain invalid).");
1319 case errSSLConnectionRefused
:
1320 message
= _("Unable to establish a secure connection to host "
1321 "(peer dropped connection before responding).");
1332 http
->error
= error
;
1333 http
->status
= HTTP_STATUS_ERROR
;
1334 errno
= ECONNREFUSED
;
1336 CFRelease(http
->tls
);
1340 * If an error string wasn't set by the callbacks use a generic one...
1344 #ifdef HAVE_CSSMERRORSTRING
1345 message
= cssmErrorString(error
);
1347 message
= _("Unable to establish a secure connection to host.");
1348 #endif /* HAVE_CSSMERRORSTRING */
1350 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1360 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1364 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1366 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1369 CFRelease(http
->tls
);
1371 if (http
->tls_credentials
)
1372 CFRelease(http
->tls_credentials
);
1375 http
->tls_credentials
= NULL
;
1380 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1383 int /* O - Bytes written */
1384 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1385 const char *buf
, /* I - Buffer holding data */
1386 int len
) /* I - Length of buffer */
1388 ssize_t result
; /* Return value */
1389 OSStatus error
; /* Error info */
1390 size_t processed
; /* Number of bytes processed */
1393 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1395 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1400 result
= (int)processed
;
1403 case errSSLWouldBlock
:
1406 result
= (int)processed
;
1415 case errSSLClosedGraceful
:
1419 result
= (int)processed
;
1429 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1431 return ((int)result
);
1435 #ifdef HAVE_SECKEYCHAINOPEN
1437 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1440 static CFArrayRef
/* O - Array of certificates or NULL */
1441 http_cdsa_copy_server(
1442 const char *common_name
) /* I - Server's hostname */
1444 OSStatus err
; /* Error info */
1445 SecIdentitySearchRef search
= NULL
; /* Search reference */
1446 SecIdentityRef identity
= NULL
;/* Identity */
1447 CFArrayRef certificates
= NULL
;
1448 /* Certificate array */
1449 SecPolicyRef policy
= NULL
; /* Policy ref */
1450 CFStringRef cfcommon_name
= NULL
;
1452 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1453 CFArrayRef list
= NULL
; /* Keychain list */
1456 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1458 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1461 CFRelease(cfcommon_name
);
1466 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1469 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1471 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1472 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1473 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1474 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1475 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1479 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1484 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1487 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1495 CFRelease(identity
);
1502 return (certificates
);
1504 #endif /* HAVE_SECKEYCHAINOPEN */
1508 * 'http_cdsa_read()' - Read function for the CDSA library.
1511 static OSStatus
/* O - -1 on error, 0 on success */
1513 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1514 void *data
, /* I - Data buffer */
1515 size_t *dataLength
) /* IO - Number of bytes */
1517 OSStatus result
; /* Return value */
1518 ssize_t bytes
; /* Number of bytes read */
1519 http_t
*http
; /* HTTP connection */
1522 http
= (http_t
*)connection
;
1524 if (!http
->blocking
)
1527 * Make sure we have data before we read...
1530 while (!_httpWait(http
, http
->wait_value
, 0))
1532 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1535 http
->error
= ETIMEDOUT
;
1542 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1544 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1546 if ((size_t)bytes
== *dataLength
)
1552 *dataLength
= (size_t)bytes
;
1553 result
= errSSLWouldBlock
;
1560 result
= errSSLClosedGraceful
;
1561 else if (errno
== EAGAIN
)
1562 result
= errSSLWouldBlock
;
1564 result
= errSSLClosedAbort
;
1572 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1575 static int /* O - Status of connection */
1576 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
1578 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1579 OSStatus error
= 0; /* Error code */
1580 http_tls_credentials_t credentials
= NULL
;
1581 /* TLS credentials */
1584 DEBUG_printf(("7http_tls_set_credentials(%p)", http
));
1587 * Prefer connection specific credentials...
1590 if ((credentials
= http
->tls_credentials
) == NULL
)
1591 credentials
= cg
->tls_credentials
;
1595 error
= SSLSetCertificate(http
->tls
, credentials
);
1596 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1600 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1607 * 'http_cdsa_write()' - Write function for the CDSA library.
1610 static OSStatus
/* O - -1 on error, 0 on success */
1612 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1613 const void *data
, /* I - Data buffer */
1614 size_t *dataLength
) /* IO - Number of bytes */
1616 OSStatus result
; /* Return value */
1617 ssize_t bytes
; /* Number of bytes read */
1618 http_t
*http
; /* HTTP connection */
1621 http
= (http_t
*)connection
;
1625 bytes
= write(http
->fd
, data
, *dataLength
);
1627 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1629 if ((size_t)bytes
== *dataLength
)
1633 else if (bytes
>= 0)
1635 *dataLength
= (size_t)bytes
;
1636 result
= errSSLWouldBlock
;
1642 if (errno
== EAGAIN
)
1643 result
= errSSLWouldBlock
;
1645 result
= errSSLClosedAbort
;