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 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
455 int /* O - 1 if valid, 0 otherwise */
456 httpCredentialsAreValidForName(
457 cups_array_t
*credentials
, /* I - Credentials */
458 const char *common_name
) /* I - Name to check */
460 SecCertificateRef secCert
; /* Certificate reference */
461 CFStringRef cfcert_name
= NULL
;
462 /* Certificate's common name (CF string) */
463 char cert_name
[256]; /* Certificate's common name (C string) */
464 int valid
= 1; /* Valid name? */
467 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
471 * Compare the common names...
474 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
477 * Can't get common name, cannot be valid...
482 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
483 _cups_strcasecmp(common_name
, cert_name
))
486 * Not an exact match for the common name, check for wildcard certs...
489 const char *domain
= strchr(common_name
, '.');
490 /* Domain in common name */
492 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
495 * Not a wildcard match.
498 /* TODO: Check subject alternate names */
504 CFRelease(cfcert_name
);
513 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
518 http_trust_t
/* O - Level of trust */
519 httpCredentialsGetTrust(
520 cups_array_t
*credentials
, /* I - Credentials */
521 const char *common_name
) /* I - Common name for trust lookup */
523 SecCertificateRef secCert
; /* Certificate reference */
524 http_trust_t trust
= HTTP_TRUST_OK
;
526 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
527 _cups_globals_t
*cg
= _cupsGlobals();
528 /* Per-thread globals */
532 return (HTTP_TRUST_UNKNOWN
);
534 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
535 return (HTTP_TRUST_UNKNOWN
);
538 * Look this common name up in the default keychains...
541 httpLoadCredentials(NULL
, &tcreds
, common_name
);
545 char credentials_str
[1024], /* String for incoming credentials */
546 tcreds_str
[1024]; /* String for saved credentials */
548 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
549 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
551 if (strcmp(credentials_str
, tcreds_str
))
554 * Credentials don't match, let's look at the expiration date of the new
555 * credentials and allow if the new ones have a later expiration...
558 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
559 !httpCredentialsAreValidForName(credentials
, common_name
))
562 * Either the new credentials are not newly issued, or the common name
563 * does not match the issued certificate...
566 trust
= HTTP_TRUST_INVALID
;
568 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
571 * Save the renewed credentials...
574 trust
= HTTP_TRUST_RENEWED
;
576 httpSaveCredentials(NULL
, credentials
, common_name
);
580 httpFreeCredentials(tcreds
);
582 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
583 trust
= HTTP_TRUST_INVALID
;
585 if (!cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
586 trust
= HTTP_TRUST_EXPIRED
;
587 else if (!cg
->any_root
&& cupsArrayCount(credentials
) == 1)
588 trust
= HTTP_TRUST_INVALID
;
597 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
602 time_t /* O - Expiration date of credentials */
603 httpCredentialsGetExpiration(
604 cups_array_t
*credentials
) /* I - Credentials */
606 SecCertificateRef secCert
; /* Certificate reference */
607 time_t expiration
; /* Expiration date */
610 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
613 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
622 * 'httpCredentialsString()' - Return a string representing the credentials.
627 size_t /* O - Total size of credentials string */
628 httpCredentialsString(
629 cups_array_t
*credentials
, /* I - Credentials */
630 char *buffer
, /* I - Buffer or @code NULL@ */
631 size_t bufsize
) /* I - Size of buffer */
633 http_credential_t
*first
; /* First certificate */
634 SecCertificateRef secCert
; /* Certificate reference */
637 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
642 if (buffer
&& bufsize
> 0)
645 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
646 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
648 CFStringRef cf_name
; /* CF common name string */
649 char name
[256]; /* Common name associated with cert */
650 time_t expiration
; /* Expiration date of cert */
651 _cups_md5_state_t md5_state
; /* MD5 state */
652 unsigned char md5_digest
[16]; /* MD5 result */
654 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
656 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
660 strlcpy(name
, "unknown", sizeof(name
));
662 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
664 _cupsMD5Init(&md5_state
);
665 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
666 _cupsMD5Finish(&md5_state
, md5_digest
);
668 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]);
673 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
675 return (strlen(buffer
));
680 * '_httpFreeCredentials()' - Free internal credentials.
684 _httpFreeCredentials(
685 http_tls_credentials_t credentials
) /* I - Internal credentials */
690 CFRelease(credentials
);
695 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
700 int /* O - 0 on success, -1 on error */
702 const char *path
, /* I - Keychain/PKCS#12 path */
703 cups_array_t
**credentials
, /* IO - Credentials */
704 const char *common_name
) /* I - Common name for credentials */
706 #ifdef HAVE_SECKEYCHAINOPEN
707 OSStatus err
; /* Error info */
708 char filename
[1024]; /* Filename for keychain */
709 SecKeychainRef keychain
= NULL
;/* Keychain reference */
710 SecIdentitySearchRef search
= NULL
; /* Search reference */
711 SecCertificateRef cert
= NULL
; /* Certificate */
712 CFDataRef data
; /* Certificate data */
713 SecPolicyRef policy
= NULL
; /* Policy ref */
714 CFStringRef cfcommon_name
= NULL
;
716 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
717 CFArrayRef list
= NULL
; /* Keychain list */
720 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
729 const char *home
= getenv("HOME"); /* HOME environment variable */
731 if (getuid() && home
)
732 snprintf(filename
, sizeof(filename
), "%s/Library/Keychains/login.keychain", home
);
734 strlcpy(filename
, "/Library/Keychains/System.keychain", sizeof(filename
));
738 DEBUG_printf(("1httpLoadCredentials: Using default path \"%s\".", path
));
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.
818 int /* O - -1 on error, 0 on success */
820 const char *path
, /* I - Keychain/PKCS#12 path */
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.");
853 const char *home
= getenv("HOME"); /* HOME environment variable */
855 if (getuid() && home
)
856 snprintf(filename
, sizeof(filename
), "%s/Library/Keychains/login.keychain", home
);
858 strlcpy(filename
, "/Library/Keychains/System.keychain", sizeof(filename
));
862 DEBUG_printf(("1httpSaveCredentials: Using default path \"%s\".", path
));
865 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
867 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err
));
871 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
873 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
877 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
879 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
883 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
884 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
885 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
887 /* Note: SecItemAdd consumes "attrs"... */
888 err
= SecItemAdd(attrs
, NULL
);
889 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
902 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
912 #endif /* HAVE_SECKEYCHAINOPEN */
917 * '_httpTLSInitialize()' - Initialize the TLS stack.
921 _httpTLSInitialize(void)
930 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
934 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
936 size_t bytes
; /* Bytes that are available */
939 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
947 * '_httpTLSRead()' - Read from a SSL/TLS connection.
950 int /* O - Bytes read */
951 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
952 char *buf
, /* I - Buffer to store data */
953 int len
) /* I - Length of buffer */
955 int result
; /* Return value */
956 OSStatus error
; /* Error info */
957 size_t processed
; /* Number of bytes processed */
960 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
961 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
966 result
= (int)processed
;
969 case errSSLWouldBlock
:
971 result
= (int)processed
;
979 case errSSLClosedGraceful
:
982 result
= (int)processed
;
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",
1060 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1063 * Client: set client-side credentials, if any...
1066 if (cg
->client_cert_cb
)
1068 error
= SSLSetSessionOption(http
->tls
,
1069 kSSLSessionOptionBreakOnCertRequested
, true);
1070 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1071 "error=%d", (int)error
));
1075 error
= http_cdsa_set_credentials(http
);
1076 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1083 * Server: find/create a certificate for TLS...
1086 if (http
->fields
[HTTP_FIELD_HOST
][0])
1089 * Use hostname for TLS upgrade...
1092 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1097 * Resolve hostname from connection address...
1100 http_addr_t addr
; /* Connection address */
1101 socklen_t addrlen
; /* Length of address */
1103 addrlen
= sizeof(addr
);
1104 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1106 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1109 else if (httpAddrLocalhost(&addr
))
1113 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1114 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1118 #ifdef HAVE_SECKEYCHAINOPEN
1119 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1120 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1123 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1124 else if (tls_common_name
)
1125 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1127 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1129 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1131 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1133 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1134 http
->error
= errno
= EINVAL
;
1135 http
->status
= HTTP_STATUS_ERROR
;
1136 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1141 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1143 #endif /* HAVE_SECKEYCHAINOPEN */
1145 if (!http
->tls_credentials
)
1147 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1148 http
->error
= errno
= EINVAL
;
1149 http
->status
= HTTP_STATUS_ERROR
;
1150 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1155 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1157 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1160 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http
->tls_credentials
));
1163 * Let the server know which hostname/domain we are trying to connect to
1164 * in case it wants to serve up a certificate with a matching common name.
1167 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1170 * Client: get the hostname to use for TLS...
1173 if (httpAddrLocalhost(http
->hostaddr
))
1175 strlcpy(hostname
, "localhost", sizeof(hostname
));
1180 * Otherwise make sure the hostname we have does not end in a trailing dot.
1183 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1184 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1189 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1191 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1196 int done
= 0; /* Are we done yet? */
1198 while (!error
&& !done
)
1200 error
= SSLHandshake(http
->tls
);
1202 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1210 case errSSLWouldBlock
:
1211 error
= noErr
; /* Force a retry */
1212 usleep(1000); /* in 1 millisecond */
1215 case errSSLServerAuthCompleted
:
1217 if (cg
->server_cert_cb
)
1219 error
= httpCopyCredentials(http
, &credentials
);
1222 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1223 cg
->server_cert_data
);
1224 httpFreeCredentials(credentials
);
1227 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1228 "returned %d.", (int)error
));
1232 case errSSLClientCertRequested
:
1235 if (cg
->client_cert_cb
)
1238 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1241 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1243 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1245 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1247 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1249 credential
->datalen
= (size_t)CFDataGetLength(data
);
1250 if ((credential
->data
= malloc(credential
->datalen
)))
1252 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1253 credential
->datalen
);
1254 cupsArrayAdd(names
, credential
);
1262 CFRelease(dn_array
);
1267 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1268 cg
->client_cert_data
);
1270 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1271 "returned %d.", (int)error
));
1274 httpFreeCredentials(names
);
1278 case errSSLUnknownRootCert
:
1279 message
= _("Unable to establish a secure connection to host "
1280 "(untrusted certificate).");
1283 case errSSLNoRootCert
:
1284 message
= _("Unable to establish a secure connection to host "
1285 "(self-signed certificate).");
1288 case errSSLCertExpired
:
1289 message
= _("Unable to establish a secure connection to host "
1290 "(expired certificate).");
1293 case errSSLCertNotYetValid
:
1294 message
= _("Unable to establish a secure connection to host "
1295 "(certificate not yet valid).");
1298 case errSSLHostNameMismatch
:
1299 message
= _("Unable to establish a secure connection to host "
1300 "(host name mismatch).");
1303 case errSSLXCertChainInvalid
:
1304 message
= _("Unable to establish a secure connection to host "
1305 "(certificate chain invalid).");
1308 case errSSLConnectionRefused
:
1309 message
= _("Unable to establish a secure connection to host "
1310 "(peer dropped connection before responding).");
1321 http
->error
= error
;
1322 http
->status
= HTTP_STATUS_ERROR
;
1323 errno
= ECONNREFUSED
;
1325 CFRelease(http
->tls
);
1329 * If an error string wasn't set by the callbacks use a generic one...
1333 #ifdef HAVE_CSSMERRORSTRING
1334 message
= cssmErrorString(error
);
1336 message
= _("Unable to establish a secure connection to host.");
1337 #endif /* HAVE_CSSMERRORSTRING */
1339 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1349 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1353 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1355 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1358 CFRelease(http
->tls
);
1360 if (http
->tls_credentials
)
1361 CFRelease(http
->tls_credentials
);
1364 http
->tls_credentials
= NULL
;
1369 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1372 int /* O - Bytes written */
1373 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1374 const char *buf
, /* I - Buffer holding data */
1375 int len
) /* I - Length of buffer */
1377 ssize_t result
; /* Return value */
1378 OSStatus error
; /* Error info */
1379 size_t processed
; /* Number of bytes processed */
1382 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1384 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1389 result
= (int)processed
;
1392 case errSSLWouldBlock
:
1395 result
= (int)processed
;
1404 case errSSLClosedGraceful
:
1408 result
= (int)processed
;
1418 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1420 return ((int)result
);
1424 #ifdef HAVE_SECKEYCHAINOPEN
1426 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1429 static CFArrayRef
/* O - Array of certificates or NULL */
1430 http_cdsa_copy_server(
1431 const char *common_name
) /* I - Server's hostname */
1433 OSStatus err
; /* Error info */
1434 SecIdentitySearchRef search
= NULL
; /* Search reference */
1435 SecIdentityRef identity
= NULL
;/* Identity */
1436 CFArrayRef certificates
= NULL
;
1437 /* Certificate array */
1438 SecPolicyRef policy
= NULL
; /* Policy ref */
1439 CFStringRef cfcommon_name
= NULL
;
1441 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1442 CFArrayRef list
= NULL
; /* Keychain list */
1445 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1447 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1450 CFRelease(cfcommon_name
);
1455 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1458 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1460 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1461 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1462 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1463 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1464 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1468 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1473 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1476 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1484 CFRelease(identity
);
1491 return (certificates
);
1493 #endif /* HAVE_SECKEYCHAINOPEN */
1497 * 'http_cdsa_read()' - Read function for the CDSA library.
1500 static OSStatus
/* O - -1 on error, 0 on success */
1502 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1503 void *data
, /* I - Data buffer */
1504 size_t *dataLength
) /* IO - Number of bytes */
1506 OSStatus result
; /* Return value */
1507 ssize_t bytes
; /* Number of bytes read */
1508 http_t
*http
; /* HTTP connection */
1511 http
= (http_t
*)connection
;
1513 if (!http
->blocking
)
1516 * Make sure we have data before we read...
1519 while (!_httpWait(http
, http
->wait_value
, 0))
1521 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1524 http
->error
= ETIMEDOUT
;
1531 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1533 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1535 if ((size_t)bytes
== *dataLength
)
1541 *dataLength
= (size_t)bytes
;
1542 result
= errSSLWouldBlock
;
1549 result
= errSSLClosedGraceful
;
1550 else if (errno
== EAGAIN
)
1551 result
= errSSLWouldBlock
;
1553 result
= errSSLClosedAbort
;
1561 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1564 static int /* O - Status of connection */
1565 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
1567 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1568 OSStatus error
= 0; /* Error code */
1569 http_tls_credentials_t credentials
= NULL
;
1570 /* TLS credentials */
1573 DEBUG_printf(("7http_tls_set_credentials(%p)", http
));
1576 * Prefer connection specific credentials...
1579 if ((credentials
= http
->tls_credentials
) == NULL
)
1580 credentials
= cg
->tls_credentials
;
1584 error
= SSLSetCertificate(http
->tls
, credentials
);
1585 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1589 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1596 * 'http_cdsa_write()' - Write function for the CDSA library.
1599 static OSStatus
/* O - -1 on error, 0 on success */
1601 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1602 const void *data
, /* I - Data buffer */
1603 size_t *dataLength
) /* IO - Number of bytes */
1605 OSStatus result
; /* Return value */
1606 ssize_t bytes
; /* Number of bytes read */
1607 http_t
*http
; /* HTTP connection */
1610 http
= (http_t
*)connection
;
1614 bytes
= write(http
->fd
, data
, *dataLength
);
1616 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1618 if ((size_t)bytes
== *dataLength
)
1622 else if (bytes
>= 0)
1624 *dataLength
= (size_t)bytes
;
1625 result
= errSSLWouldBlock
;
1631 if (errno
== EAGAIN
)
1632 result
= errSSLWouldBlock
;
1634 result
= errSSLClosedAbort
;