2 * TLS support code for CUPS on macOS.
4 * Copyright 2007-2016 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * file is missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
16 /**** This file is included from tls.c ****/
19 * Include necessary headers...
24 extern char **environ
;
31 static int tls_auto_create
= 0;
32 /* Auto-create self-signed certs? */
33 static char *tls_common_name
= NULL
;
34 /* Default common name */
35 #ifdef HAVE_SECKEYCHAINOPEN
36 static SecKeychainRef tls_keychain
= NULL
;
37 /* Server cert keychain */
39 static SecIdentityRef tls_selfsigned
= NULL
;
40 /* Temporary self-signed cert */
41 #endif /* HAVE_SECKEYCHAINOPEN */
42 static char *tls_keypath
= NULL
;
43 /* Server cert keychain path */
44 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
45 /* Mutex for keychain/certs */
46 static int tls_options
= -1;/* Options for TLS connections */
53 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
54 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
55 #ifdef HAVE_SECKEYCHAINOPEN
56 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
57 #endif /* HAVE_SECKEYCHAINOPEN */
58 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
59 static int http_cdsa_set_credentials(http_t
*http
);
60 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
64 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
66 * @since CUPS 2.0/OS 10.10@
69 int /* O - 1 on success, 0 on failure */
70 cupsMakeServerCredentials(
71 const char *path
, /* I - Keychain path or @code NULL@ for default */
72 const char *common_name
, /* I - Common name */
73 int num_alt_names
, /* I - Number of subject alternate names */
74 const char **alt_names
, /* I - Subject Alternate Names */
75 time_t expiration_date
) /* I - Expiration date */
77 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
78 int status
= 0; /* Return status */
79 OSStatus err
; /* Error code (if any) */
80 CFStringRef cfcommon_name
= NULL
;
81 /* CF string for server name */
82 SecIdentityRef ident
= NULL
; /* Identity */
83 SecKeyRef publicKey
= NULL
,
87 SecCertificateRef cert
= NULL
; /* Self-signed certificate */
88 CFMutableDictionaryRef keyParams
= NULL
;
89 /* Key generation parameters */
92 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
));
97 (void)expiration_date
;
101 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
107 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
111 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
114 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
119 * Create a public/private key pair...
122 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
125 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
129 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
130 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
131 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, cfcommon_name
);
133 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
136 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err
));
141 * Create a self-signed certificate using the public/private key pair...
144 CFIndex usageInt
= kSecKeyUsageAll
;
145 CFNumberRef usage
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &usageInt
);
147 CFNumberRef len
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &lenInt
);
148 CFTypeRef certKeys
[] = { kSecCSRBasicContraintsPathLen
, kSecSubjectAltName
, kSecCertificateKeyUsage
};
149 CFTypeRef certValues
[] = { len
, cfcommon_name
, usage
};
150 CFDictionaryRef certParams
= CFDictionaryCreate(kCFAllocatorDefault
, certKeys
, certValues
, sizeof(certKeys
) / sizeof(certKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
154 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
155 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
156 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
157 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
158 const void *ca_dn_array
[2];
160 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
161 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
163 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
165 cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
168 CFRelease(certParams
);
172 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
176 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
180 _cupsMutexLock(&tls_mutex
);
185 tls_selfsigned
= ident
;
187 _cupsMutexLock(&tls_mutex
);
189 # if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point */
190 CFTypeRef itemKeys
[] = { kSecClass
, kSecAttrLabel
, kSecValueRef
};
191 CFTypeRef itemValues
[] = { kSecClassIdentity
, cfcommon_name
, ident
};
192 CFDictionaryRef itemAttrs
= CFDictionaryCreate(kCFAllocatorDefault
, itemKeys
, itemValues
, sizeof(itemKeys
) / sizeof(itemKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
194 err
= SecItemAdd(itemAttrs
, NULL
);
195 /* SecItemAdd consumes itemAttrs... */
201 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err
));
209 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
212 * Cleanup and return...
218 CFRelease(cfcommon_name
);
221 CFRelease(keyParams
);
227 CFRelease(publicKey
);
230 CFRelease(privateKey
);
232 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status
));
236 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
237 int pid
, /* Process ID of command */
238 status
, /* Status of command */
240 char command
[1024], /* Command */
241 *argv
[5], /* Command-line arguments */
242 *envp
[1000], /* Environment variables */
243 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
244 keychain
[1024], /* Keychain argument */
245 infofile
[1024], /* Type-in information for cert */
246 filename
[1024]; /* Default keychain path */
247 cups_file_t
*fp
; /* Seed/info file */
250 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path
, common_name
, num_alt_names
, (void *)alt_names
, (int)expiration_date
));
256 path
= http_cdsa_default_path(filename
, sizeof(filename
));
259 * Run the "certtool" command to generate a self-signed certificate...
262 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
266 * Create a file with the certificate information fields...
268 * Note: This assumes that the default questions are asked by the certtool
272 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
276 "CUPS Self-Signed Certificate\n"
277 /* Enter key and certificate label */
278 "r\n" /* Generate RSA key pair */
279 "2048\n" /* 2048 bit encryption key */
280 "y\n" /* OK (y = yes) */
281 "b\n" /* Usage (b=signing/encryption) */
282 "2\n" /* Sign with SHA256 */
283 "y\n" /* OK (y = yes) */
284 "%s\n" /* Common name */
285 "\n" /* Country (default) */
286 "\n" /* Organization (default) */
287 "\n" /* Organizational unit (default) */
288 "\n" /* State/Province (default) */
289 "\n" /* Email address */
290 "y\n", /* OK (y = yes) */
294 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
296 argv
[0] = "certtool";
301 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
303 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
304 envp
[i
+ 1] = environ
[i
];
307 posix_spawn_file_actions_t actions
; /* File actions */
309 posix_spawn_file_actions_init(&actions
);
310 posix_spawn_file_actions_addclose(&actions
, 0);
311 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
312 posix_spawn_file_actions_addclose(&actions
, 1);
313 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
314 posix_spawn_file_actions_addclose(&actions
, 2);
315 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
317 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
323 posix_spawn_file_actions_destroy(&actions
);
327 while (waitpid(pid
, &status
, 0) < 0)
335 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
340 * 'cupsSetServerCredentials()' - Set the default server credentials.
342 * Note: The server credentials are used by all threads in the running process.
343 * This function is threadsafe.
345 * @since CUPS 2.0/macOS 10.10@
348 int /* O - 1 on success, 0 on failure */
349 cupsSetServerCredentials(
350 const char *path
, /* I - Keychain path or @code NULL@ for default */
351 const char *common_name
, /* I - Default common name for server */
352 int auto_create
) /* I - 1 = automatically create self-signed certificates */
354 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
356 #ifdef HAVE_SECKEYCHAINOPEN
357 char filename
[1024]; /* Filename for keychain */
358 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
359 OSStatus status
; /* Status code */
363 path
= http_cdsa_default_path(filename
, sizeof(filename
));
365 if ((status
= SecKeychainOpen(path
, &keychain
)) != noErr
)
367 /* TODO: Set cups last error string */
368 DEBUG_printf(("1cupsSetServerCredentials: Unable to open keychain (%d), returning 0.", (int)status
));
372 _cupsMutexLock(&tls_mutex
);
375 * Close any keychain that is currently open...
379 CFRelease(tls_keychain
);
382 _cupsStrFree(tls_keypath
);
385 _cupsStrFree(tls_common_name
);
388 * Save the new keychain...
391 tls_keychain
= keychain
;
392 tls_keypath
= _cupsStrAlloc(path
);
393 tls_auto_create
= auto_create
;
394 tls_common_name
= _cupsStrAlloc(common_name
);
396 _cupsMutexUnlock(&tls_mutex
);
398 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
404 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
408 tls_auto_create
= auto_create
;
409 tls_common_name
= _cupsStrAlloc(common_name
);
412 #endif /* HAVE_SECKEYCHAINOPEN */
417 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
418 * an encrypted connection.
420 * @since CUPS 1.5/macOS 10.7@
423 int /* O - Status of call (0 = success) */
425 http_t
*http
, /* I - Connection to server */
426 cups_array_t
**credentials
) /* O - Array of credentials */
428 OSStatus error
; /* Error code */
429 SecTrustRef peerTrust
; /* Peer trust reference */
430 CFIndex count
; /* Number of credentials */
431 SecCertificateRef secCert
; /* Certificate reference */
432 CFDataRef data
; /* Certificate data */
433 int i
; /* Looping var */
436 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http
, (void *)credentials
));
441 if (!http
|| !http
->tls
|| !credentials
)
444 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
446 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
448 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
450 count
= SecTrustGetCertificateCount(peerTrust
);
452 for (i
= 0; i
< count
; i
++)
454 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
457 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
460 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
462 strlcpy(name
, "unknown", sizeof(name
));
464 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
467 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
469 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
471 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
477 CFRelease(peerTrust
);
485 * '_httpCreateCredentials()' - Create credentials in the internal format.
488 http_tls_credentials_t
/* O - Internal credentials */
489 _httpCreateCredentials(
490 cups_array_t
*credentials
) /* I - Array of credentials */
492 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
493 SecCertificateRef secCert
; /* Certificate reference */
494 http_credential_t
*credential
; /* Credential data */
500 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
501 cupsArrayCount(credentials
),
502 &kCFTypeArrayCallBacks
)) == NULL
)
505 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
507 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
509 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
511 CFArrayAppendValue(peerCerts
, secCert
);
521 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
523 * @since CUPS 2.0/macOS 10.10@
526 int /* O - 1 if valid, 0 otherwise */
527 httpCredentialsAreValidForName(
528 cups_array_t
*credentials
, /* I - Credentials */
529 const char *common_name
) /* I - Name to check */
531 SecCertificateRef secCert
; /* Certificate reference */
532 CFStringRef cfcert_name
= NULL
;
533 /* Certificate's common name (CF string) */
534 char cert_name
[256]; /* Certificate's common name (C string) */
535 int valid
= 1; /* Valid name? */
538 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
542 * Compare the common names...
545 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
548 * Can't get common name, cannot be valid...
553 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
554 _cups_strcasecmp(common_name
, cert_name
))
557 * Not an exact match for the common name, check for wildcard certs...
560 const char *domain
= strchr(common_name
, '.');
561 /* Domain in common name */
563 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
566 * Not a wildcard match.
569 /* TODO: Check subject alternate names */
575 CFRelease(cfcert_name
);
584 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
586 * @since CUPS 2.0/macOS 10.10@
589 http_trust_t
/* O - Level of trust */
590 httpCredentialsGetTrust(
591 cups_array_t
*credentials
, /* I - Credentials */
592 const char *common_name
) /* I - Common name for trust lookup */
594 SecCertificateRef secCert
; /* Certificate reference */
595 http_trust_t trust
= HTTP_TRUST_OK
;
597 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
598 _cups_globals_t
*cg
= _cupsGlobals();
599 /* Per-thread globals */
603 return (HTTP_TRUST_UNKNOWN
);
605 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
606 return (HTTP_TRUST_UNKNOWN
);
608 if (cg
->any_root
< 0)
612 * Look this common name up in the default keychains...
615 httpLoadCredentials(NULL
, &tcreds
, common_name
);
619 char credentials_str
[1024], /* String for incoming credentials */
620 tcreds_str
[1024]; /* String for saved credentials */
622 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
623 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
625 if (strcmp(credentials_str
, tcreds_str
))
628 * Credentials don't match, let's look at the expiration date of the new
629 * credentials and allow if the new ones have a later expiration...
632 if (!cg
->trust_first
)
635 * Do not trust certificates on first use...
638 trust
= HTTP_TRUST_INVALID
;
640 else if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) || !httpCredentialsAreValidForName(credentials
, common_name
))
643 * Either the new credentials are not newly issued, or the common name
644 * does not match the issued certificate...
647 trust
= HTTP_TRUST_INVALID
;
649 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
652 * Save the renewed credentials...
655 trust
= HTTP_TRUST_RENEWED
;
657 httpSaveCredentials(NULL
, credentials
, common_name
);
661 httpFreeCredentials(tcreds
);
663 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
664 trust
= HTTP_TRUST_INVALID
;
666 if (!cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
667 trust
= HTTP_TRUST_EXPIRED
;
668 else if (!cg
->any_root
&& cupsArrayCount(credentials
) == 1)
669 trust
= HTTP_TRUST_INVALID
;
670 else if (!cg
->trust_first
)
671 trust
= HTTP_TRUST_INVALID
;
680 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
682 * @since CUPS 2.0/macOS 10.10@
685 time_t /* O - Expiration date of credentials */
686 httpCredentialsGetExpiration(
687 cups_array_t
*credentials
) /* I - Credentials */
689 SecCertificateRef secCert
; /* Certificate reference */
690 time_t expiration
; /* Expiration date */
693 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
696 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
705 * 'httpCredentialsString()' - Return a string representing the credentials.
707 * @since CUPS 2.0/macOS 10.10@
710 size_t /* O - Total size of credentials string */
711 httpCredentialsString(
712 cups_array_t
*credentials
, /* I - Credentials */
713 char *buffer
, /* I - Buffer or @code NULL@ */
714 size_t bufsize
) /* I - Size of buffer */
716 http_credential_t
*first
; /* First certificate */
717 SecCertificateRef secCert
; /* Certificate reference */
720 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", (void *)credentials
, (void *)buffer
, CUPS_LLCAST bufsize
));
725 if (buffer
&& bufsize
> 0)
728 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
729 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
731 CFStringRef cf_name
; /* CF common name string */
732 char name
[256]; /* Common name associated with cert */
733 time_t expiration
; /* Expiration date of cert */
734 _cups_md5_state_t md5_state
; /* MD5 state */
735 unsigned char md5_digest
[16]; /* MD5 result */
737 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
739 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
743 strlcpy(name
, "unknown", sizeof(name
));
745 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
747 _cupsMD5Init(&md5_state
);
748 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
749 _cupsMD5Finish(&md5_state
, md5_digest
);
751 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]);
756 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
758 return (strlen(buffer
));
763 * '_httpFreeCredentials()' - Free internal credentials.
767 _httpFreeCredentials(
768 http_tls_credentials_t credentials
) /* I - Internal credentials */
773 CFRelease(credentials
);
778 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
780 * @since CUPS 2.0/OS 10.10@
783 int /* O - 0 on success, -1 on error */
785 const char *path
, /* I - Keychain path or @code NULL@ for default */
786 cups_array_t
**credentials
, /* IO - Credentials */
787 const char *common_name
) /* I - Common name for credentials */
789 OSStatus err
; /* Error info */
790 #ifdef HAVE_SECKEYCHAINOPEN
791 char filename
[1024]; /* Filename for keychain */
792 SecKeychainRef keychain
= NULL
;/* Keychain reference */
793 CFArrayRef list
; /* Keychain list */
794 #endif /* HAVE_SECKEYCHAINOPEN */
795 SecCertificateRef cert
= NULL
; /* Certificate */
796 CFDataRef data
; /* Certificate data */
797 SecPolicyRef policy
= NULL
; /* Policy ref */
798 CFStringRef cfcommon_name
= NULL
;
800 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
803 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
810 #ifdef HAVE_SECKEYCHAINOPEN
812 path
= http_cdsa_default_path(filename
, sizeof(filename
));
814 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
820 #endif /* HAVE_SECKEYCHAINOPEN */
822 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
824 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
827 CFRelease(cfcommon_name
);
832 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
835 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
836 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
837 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
838 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
840 #ifdef HAVE_SECKEYCHAINOPEN
841 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
842 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
844 #endif /* HAVE_SECKEYCHAINOPEN */
846 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
851 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
854 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
856 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
858 *credentials
= cupsArrayNew(NULL
, NULL
);
859 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
865 #ifdef HAVE_SECKEYCHAINOPEN
868 #endif /* HAVE_SECKEYCHAINOPEN */
876 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
878 return (*credentials
? 0 : -1);
883 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
885 * @since CUPS 2.0/OS 10.10@
888 int /* O - -1 on error, 0 on success */
890 const char *path
, /* I - Keychain path or @code NULL@ for default */
891 cups_array_t
*credentials
, /* I - Credentials */
892 const char *common_name
) /* I - Common name for credentials */
894 int ret
= -1; /* Return value */
895 OSStatus err
; /* Error info */
896 #ifdef HAVE_SECKEYCHAINOPEN
897 char filename
[1024]; /* Filename for keychain */
898 SecKeychainRef keychain
= NULL
;/* Keychain reference */
899 CFArrayRef list
; /* Keychain list */
900 #endif /* HAVE_SECKEYCHAINOPEN */
901 SecCertificateRef cert
= NULL
; /* Certificate */
902 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
905 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
909 if (!httpCredentialsAreValidForName(credentials
, common_name
))
911 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
915 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
917 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
921 #ifdef HAVE_SECKEYCHAINOPEN
923 path
= http_cdsa_default_path(filename
, sizeof(filename
));
925 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
927 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err
));
934 #endif /* HAVE_SECKEYCHAINOPEN */
936 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
938 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
942 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
943 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
945 #ifdef HAVE_SECKEYCHAINOPEN
946 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
948 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
951 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
953 #endif /* HAVE_SECKEYCHAINOPEN */
955 /* Note: SecItemAdd consumes "attrs"... */
956 err
= SecItemAdd(attrs
, NULL
);
957 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
961 #ifdef HAVE_SECKEYCHAINOPEN
964 #endif /* HAVE_SECKEYCHAINOPEN */
968 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
975 * '_httpTLSInitialize()' - Initialize the TLS stack.
979 _httpTLSInitialize(void)
988 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
992 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
994 size_t bytes
; /* Bytes that are available */
997 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
1005 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1008 int /* O - Bytes read */
1009 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
1010 char *buf
, /* I - Buffer to store data */
1011 int len
) /* I - Length of buffer */
1013 int result
; /* Return value */
1014 OSStatus error
; /* Error info */
1015 size_t processed
; /* Number of bytes processed */
1018 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
1019 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
1024 result
= (int)processed
;
1027 case errSSLWouldBlock
:
1029 result
= (int)processed
;
1037 case errSSLClosedGraceful
:
1040 result
= (int)processed
;
1054 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1058 _httpTLSSetOptions(int options
) /* I - Options */
1060 tls_options
= options
;
1065 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1068 int /* O - 0 on success, -1 on failure */
1069 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
1071 char hostname
[256], /* Hostname */
1072 *hostptr
; /* Pointer into hostname */
1073 _cups_globals_t
*cg
= _cupsGlobals();
1074 /* Pointer to library globals */
1075 OSStatus error
; /* Error code */
1076 const char *message
= NULL
;/* Error message */
1077 cups_array_t
*credentials
; /* Credentials array */
1078 cups_array_t
*names
; /* CUPS distinguished names */
1079 CFArrayRef dn_array
; /* CF distinguished names array */
1080 CFIndex count
; /* Number of credentials */
1081 CFDataRef data
; /* Certificate data */
1082 int i
; /* Looping var */
1083 http_credential_t
*credential
; /* Credential data */
1086 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http
));
1088 if (tls_options
< 0)
1090 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1092 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1095 #ifdef HAVE_SECKEYCHAINOPEN
1096 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1098 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1099 http
->error
= errno
= EINVAL
;
1100 http
->status
= HTTP_STATUS_ERROR
;
1101 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1105 #endif /* HAVE_SECKEYCHAINOPEN */
1107 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1109 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1110 http
->error
= errno
= ENOMEM
;
1111 http
->status
= HTTP_STATUS_ERROR
;
1112 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1117 error
= SSLSetConnection(http
->tls
, http
);
1118 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1122 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1123 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1128 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1130 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error
));
1135 SSLProtocol minProtocol
;
1137 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1138 minProtocol
= kTLSProtocol11
;
1139 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1140 minProtocol
= kSSLProtocol3
;
1142 minProtocol
= kTLSProtocol1
;
1144 error
= SSLSetProtocolVersionMin(http
->tls
, minProtocol
);
1145 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol
, (int)error
));
1148 # if HAVE_SSLSETENABLEDCIPHERS
1151 SSLCipherSuite supported
[100]; /* Supported cipher suites */
1152 size_t num_supported
; /* Number of supported cipher suites */
1153 SSLCipherSuite enabled
[100]; /* Cipher suites to enable */
1154 size_t num_enabled
; /* Number of cipher suites to enable */
1156 num_supported
= sizeof(supported
) / sizeof(supported
[0]);
1157 error
= SSLGetSupportedCiphers(http
->tls
, supported
, &num_supported
);
1161 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported
));
1163 for (i
= 0, num_enabled
= 0; i
< (int)num_supported
&& num_enabled
< (sizeof(enabled
) / sizeof(enabled
[0])); i
++)
1165 switch (supported
[i
])
1167 /* Obviously insecure cipher suites that we never want to use */
1168 case SSL_NULL_WITH_NULL_NULL
:
1169 case SSL_RSA_WITH_NULL_MD5
:
1170 case SSL_RSA_WITH_NULL_SHA
:
1171 case SSL_RSA_EXPORT_WITH_RC4_40_MD5
:
1172 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
1173 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1174 case SSL_RSA_WITH_DES_CBC_SHA
:
1175 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1176 case SSL_DH_DSS_WITH_DES_CBC_SHA
:
1177 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1178 case SSL_DH_RSA_WITH_DES_CBC_SHA
:
1179 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1180 case SSL_DHE_DSS_WITH_DES_CBC_SHA
:
1181 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1182 case SSL_DHE_RSA_WITH_DES_CBC_SHA
:
1183 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
:
1184 case SSL_DH_anon_WITH_RC4_128_MD5
:
1185 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
:
1186 case SSL_DH_anon_WITH_DES_CBC_SHA
:
1187 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
:
1188 case SSL_FORTEZZA_DMS_WITH_NULL_SHA
:
1189 case TLS_DH_anon_WITH_AES_128_CBC_SHA
:
1190 case TLS_DH_anon_WITH_AES_256_CBC_SHA
:
1191 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
1192 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
1193 case TLS_ECDH_anon_WITH_NULL_SHA
:
1194 case TLS_ECDH_anon_WITH_RC4_128_SHA
:
1195 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
:
1196 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA
:
1197 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA
:
1198 case TLS_RSA_WITH_NULL_SHA256
:
1199 case TLS_DH_anon_WITH_AES_128_CBC_SHA256
:
1200 case TLS_DH_anon_WITH_AES_256_CBC_SHA256
:
1201 case TLS_PSK_WITH_NULL_SHA
:
1202 case TLS_DHE_PSK_WITH_NULL_SHA
:
1203 case TLS_RSA_PSK_WITH_NULL_SHA
:
1204 case TLS_DH_anon_WITH_AES_128_GCM_SHA256
:
1205 case TLS_DH_anon_WITH_AES_256_GCM_SHA384
:
1206 case TLS_PSK_WITH_NULL_SHA256
:
1207 case TLS_PSK_WITH_NULL_SHA384
:
1208 case TLS_DHE_PSK_WITH_NULL_SHA256
:
1209 case TLS_DHE_PSK_WITH_NULL_SHA384
:
1210 case TLS_RSA_PSK_WITH_NULL_SHA256
:
1211 case TLS_RSA_PSK_WITH_NULL_SHA384
:
1212 case SSL_RSA_WITH_DES_CBC_MD5
:
1213 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported
[i
]));
1216 /* RC4 cipher suites that should only be used as a last resort */
1217 case SSL_RSA_WITH_RC4_128_MD5
:
1218 case SSL_RSA_WITH_RC4_128_SHA
:
1219 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
1220 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
1221 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
1222 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
1223 case TLS_PSK_WITH_RC4_128_SHA
:
1224 case TLS_DHE_PSK_WITH_RC4_128_SHA
:
1225 case TLS_RSA_PSK_WITH_RC4_128_SHA
:
1226 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1227 enabled
[num_enabled
++] = supported
[i
];
1229 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported
[i
]));
1232 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1233 case TLS_DH_DSS_WITH_AES_128_CBC_SHA
:
1234 case TLS_DH_RSA_WITH_AES_128_CBC_SHA
:
1235 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA
:
1236 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA
:
1237 case TLS_DH_DSS_WITH_AES_256_CBC_SHA
:
1238 case TLS_DH_RSA_WITH_AES_256_CBC_SHA
:
1239 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA
:
1240 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA
:
1241 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
:
1242 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
:
1243 // case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
1244 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
:
1245 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256
:
1246 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256
:
1247 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
:
1248 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
:
1249 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256
:
1250 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256
:
1251 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
:
1252 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
:
1253 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
:
1254 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA
:
1255 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA
:
1256 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1257 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1258 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256
:
1259 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384
:
1260 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1261 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1262 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256
:
1263 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384
:
1264 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
:
1265 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
:
1266 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
:
1267 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
:
1268 if (tls_options
& _HTTP_TLS_ALLOW_DH
)
1269 enabled
[num_enabled
++] = supported
[i
];
1271 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported
[i
]));
1274 /* Anything else we'll assume is secure */
1276 enabled
[num_enabled
++] = supported
[i
];
1281 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled
));
1282 error
= SSLSetEnabledCiphers(http
->tls
, enabled
, num_enabled
);
1285 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1287 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1290 * Client: set client-side credentials, if any...
1293 if (cg
->client_cert_cb
)
1295 error
= SSLSetSessionOption(http
->tls
,
1296 kSSLSessionOptionBreakOnCertRequested
, true);
1297 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1298 "error=%d", (int)error
));
1302 error
= http_cdsa_set_credentials(http
);
1303 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1310 * Server: find/create a certificate for TLS...
1313 if (http
->fields
[HTTP_FIELD_HOST
][0])
1316 * Use hostname for TLS upgrade...
1319 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1324 * Resolve hostname from connection address...
1327 http_addr_t addr
; /* Connection address */
1328 socklen_t addrlen
; /* Length of address */
1330 addrlen
= sizeof(addr
);
1331 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1333 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1336 else if (httpAddrLocalhost(&addr
))
1340 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1341 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1345 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1346 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1349 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1350 else if (tls_common_name
)
1351 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1353 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1355 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1357 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1359 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1360 http
->error
= errno
= EINVAL
;
1361 http
->status
= HTTP_STATUS_ERROR
;
1362 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1367 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1370 if (!http
->tls_credentials
)
1372 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1373 http
->error
= errno
= EINVAL
;
1374 http
->status
= HTTP_STATUS_ERROR
;
1375 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1380 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1382 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1385 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http
->tls_credentials
));
1388 * Let the server know which hostname/domain we are trying to connect to
1389 * in case it wants to serve up a certificate with a matching common name.
1392 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1395 * Client: get the hostname to use for TLS...
1398 if (httpAddrLocalhost(http
->hostaddr
))
1400 strlcpy(hostname
, "localhost", sizeof(hostname
));
1405 * Otherwise make sure the hostname we have does not end in a trailing dot.
1408 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1409 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1414 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1416 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1421 int done
= 0; /* Are we done yet? */
1423 while (!error
&& !done
)
1425 error
= SSLHandshake(http
->tls
);
1427 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1435 case errSSLWouldBlock
:
1436 error
= noErr
; /* Force a retry */
1437 usleep(1000); /* in 1 millisecond */
1440 case errSSLServerAuthCompleted
:
1442 if (cg
->server_cert_cb
)
1444 error
= httpCopyCredentials(http
, &credentials
);
1447 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1448 cg
->server_cert_data
);
1449 httpFreeCredentials(credentials
);
1452 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1453 "returned %d.", (int)error
));
1457 case errSSLClientCertRequested
:
1460 if (cg
->client_cert_cb
)
1463 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1466 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1468 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1470 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1472 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1474 credential
->datalen
= (size_t)CFDataGetLength(data
);
1475 if ((credential
->data
= malloc(credential
->datalen
)))
1477 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1478 credential
->datalen
);
1479 cupsArrayAdd(names
, credential
);
1487 CFRelease(dn_array
);
1492 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1493 cg
->client_cert_data
);
1495 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1496 "returned %d.", (int)error
));
1499 httpFreeCredentials(names
);
1503 case errSSLUnknownRootCert
:
1504 message
= _("Unable to establish a secure connection to host "
1505 "(untrusted certificate).");
1508 case errSSLNoRootCert
:
1509 message
= _("Unable to establish a secure connection to host "
1510 "(self-signed certificate).");
1513 case errSSLCertExpired
:
1514 message
= _("Unable to establish a secure connection to host "
1515 "(expired certificate).");
1518 case errSSLCertNotYetValid
:
1519 message
= _("Unable to establish a secure connection to host "
1520 "(certificate not yet valid).");
1523 case errSSLHostNameMismatch
:
1524 message
= _("Unable to establish a secure connection to host "
1525 "(host name mismatch).");
1528 case errSSLXCertChainInvalid
:
1529 message
= _("Unable to establish a secure connection to host "
1530 "(certificate chain invalid).");
1533 case errSSLConnectionRefused
:
1534 message
= _("Unable to establish a secure connection to host "
1535 "(peer dropped connection before responding).");
1546 http
->error
= error
;
1547 http
->status
= HTTP_STATUS_ERROR
;
1548 errno
= ECONNREFUSED
;
1550 CFRelease(http
->tls
);
1554 * If an error string wasn't set by the callbacks use a generic one...
1558 #ifdef HAVE_CSSMERRORSTRING
1559 message
= cssmErrorString(error
);
1561 message
= _("Unable to establish a secure connection to host.");
1562 #endif /* HAVE_CSSMERRORSTRING */
1564 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1574 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1578 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1580 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1583 CFRelease(http
->tls
);
1585 if (http
->tls_credentials
)
1586 CFRelease(http
->tls_credentials
);
1589 http
->tls_credentials
= NULL
;
1594 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1597 int /* O - Bytes written */
1598 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1599 const char *buf
, /* I - Buffer holding data */
1600 int len
) /* I - Length of buffer */
1602 ssize_t result
; /* Return value */
1603 OSStatus error
; /* Error info */
1604 size_t processed
; /* Number of bytes processed */
1607 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http
, (void *)buf
, len
));
1609 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1614 result
= (int)processed
;
1617 case errSSLWouldBlock
:
1620 result
= (int)processed
;
1629 case errSSLClosedGraceful
:
1633 result
= (int)processed
;
1643 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1645 return ((int)result
);
1650 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1653 static CFArrayRef
/* O - Array of certificates or NULL */
1654 http_cdsa_copy_server(
1655 const char *common_name
) /* I - Server's hostname */
1657 #ifdef HAVE_SECKEYCHAINOPEN
1658 OSStatus err
; /* Error info */
1659 SecIdentityRef identity
= NULL
;/* Identity */
1660 CFArrayRef certificates
= NULL
;
1661 /* Certificate array */
1662 SecPolicyRef policy
= NULL
; /* Policy ref */
1663 CFStringRef cfcommon_name
= NULL
;
1665 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1666 CFArrayRef list
= NULL
; /* Keychain list */
1669 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name
));
1671 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1673 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1677 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
1681 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1683 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
1687 _cupsMutexLock(&tls_mutex
);
1689 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1690 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1691 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1692 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1694 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1695 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1698 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1700 _cupsMutexUnlock(&tls_mutex
);
1704 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err
));
1708 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1710 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
1714 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1716 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
1723 CFRelease(identity
);
1727 CFRelease(cfcommon_name
);
1731 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates
));
1733 return (certificates
);
1736 if (!tls_selfsigned
)
1739 return (CFArrayCreate(NULL
, (const void **)&tls_selfsigned
, 1, &kCFTypeArrayCallBacks
));
1740 #endif /* HAVE_SECKEYCHAINOPEN */
1745 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1748 static SecCertificateRef
/* O - Certificate */
1749 http_cdsa_create_credential(
1750 http_credential_t
*credential
) /* I - Credential */
1755 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1759 #ifdef HAVE_SECKEYCHAINOPEN
1761 * 'http_cdsa_default_path()' - Get the default keychain path.
1764 static const char * /* O - Keychain path */
1765 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1766 size_t bufsize
) /* I - Size of buffer */
1768 const char *home
= getenv("HOME"); /* HOME environment variable */
1771 if (getuid() && home
)
1772 snprintf(buffer
, bufsize
, "%s/Library/Keychains/login.keychain", home
);
1774 strlcpy(buffer
, "/Library/Keychains/System.keychain", bufsize
);
1776 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1780 #endif /* HAVE_SECKEYCHAINOPEN */
1784 * 'http_cdsa_read()' - Read function for the CDSA library.
1787 static OSStatus
/* O - -1 on error, 0 on success */
1789 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1790 void *data
, /* I - Data buffer */
1791 size_t *dataLength
) /* IO - Number of bytes */
1793 OSStatus result
; /* Return value */
1794 ssize_t bytes
; /* Number of bytes read */
1795 http_t
*http
; /* HTTP connection */
1798 http
= (http_t
*)connection
;
1800 if (!http
->blocking
)
1803 * Make sure we have data before we read...
1806 while (!_httpWait(http
, http
->wait_value
, 0))
1808 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1811 http
->error
= ETIMEDOUT
;
1818 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1820 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1822 if ((size_t)bytes
== *dataLength
)
1828 *dataLength
= (size_t)bytes
;
1829 result
= errSSLWouldBlock
;
1836 result
= errSSLClosedGraceful
;
1837 else if (errno
== EAGAIN
)
1838 result
= errSSLWouldBlock
;
1840 result
= errSSLClosedAbort
;
1848 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1851 static int /* O - Status of connection */
1852 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
1854 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1855 OSStatus error
= 0; /* Error code */
1856 http_tls_credentials_t credentials
= NULL
;
1857 /* TLS credentials */
1860 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http
));
1863 * Prefer connection specific credentials...
1866 if ((credentials
= http
->tls_credentials
) == NULL
)
1867 credentials
= cg
->tls_credentials
;
1871 error
= SSLSetCertificate(http
->tls
, credentials
);
1872 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1876 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1883 * 'http_cdsa_write()' - Write function for the CDSA library.
1886 static OSStatus
/* O - -1 on error, 0 on success */
1888 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1889 const void *data
, /* I - Data buffer */
1890 size_t *dataLength
) /* IO - Number of bytes */
1892 OSStatus result
; /* Return value */
1893 ssize_t bytes
; /* Number of bytes read */
1894 http_t
*http
; /* HTTP connection */
1897 http
= (http_t
*)connection
;
1901 bytes
= write(http
->fd
, data
, *dataLength
);
1903 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1905 if ((size_t)bytes
== *dataLength
)
1909 else if (bytes
>= 0)
1911 *dataLength
= (size_t)bytes
;
1912 result
= errSSLWouldBlock
;
1918 if (errno
== EAGAIN
)
1919 result
= errSSLWouldBlock
;
1921 result
= errSSLClosedAbort
;