2 * TLS support code for CUPS on OS X.
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 */
38 #endif /* HAVE_SECKEYCHAINOPEN */
39 static char *tls_keypath
= NULL
;
40 /* Server cert keychain path */
41 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
42 /* Mutex for keychain/certs */
43 static int tls_options
= -1;/* Options for TLS connections */
50 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
51 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
52 #ifdef HAVE_SECKEYCHAINOPEN
53 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
54 #endif /* HAVE_SECKEYCHAINOPEN */
55 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
56 static int http_cdsa_set_credentials(http_t
*http
);
57 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
61 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
63 * @since CUPS 2.0/OS 10.10@
66 int /* O - 1 on success, 0 on failure */
67 cupsMakeServerCredentials(
68 const char *path
, /* I - Keychain path or @code NULL@ for default */
69 const char *common_name
, /* I - Common name */
70 int num_alt_names
, /* I - Number of subject alternate names */
71 const char **alt_names
, /* I - Subject Alternate Names */
72 time_t expiration_date
) /* I - Expiration date */
74 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
75 int status
= 0; /* Return status */
76 OSStatus err
; /* Error code (if any) */
77 CFStringRef cfcommon_name
= NULL
;
78 /* CF string for server name */
79 SecIdentityRef ident
= NULL
; /* Identity */
80 SecKeyRef publicKey
= NULL
,
84 SecCertificateRef cert
= NULL
; /* Self-signed certificate */
85 CFMutableDictionaryRef keyParams
= NULL
;
86 /* Key generation parameters */
89 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path
, common_name
, num_alt_names
, alt_names
, (int)expiration_date
));
94 (void)expiration_date
;
98 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
102 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
107 * Create a public/private key pair...
110 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
114 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
115 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
116 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, CFSTR("CUPS Self-Signed Certificate"));
118 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
123 * Create a self-signed certificate using the public/private key pair...
126 CFIndex usageInt
= kSecKeyUsageAll
;
127 CFNumberRef usage
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &usageInt
);
129 CFNumberRef len
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &lenInt
);
130 CFTypeRef certKeys
[] = { kSecCSRBasicContraintsPathLen
, kSecSubjectAltName
, kSecCertificateKeyUsage
};
131 CFTypeRef certValues
[] = { len
, cfcommon_name
, usage
};
132 CFDictionaryRef certParams
= CFDictionaryCreate(kCFAllocatorDefault
, certKeys
, certValues
, sizeof(certKeys
) / sizeof(certKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
136 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
137 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
138 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
139 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
140 const void *ca_dn_array
[2];
142 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
143 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
145 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
147 cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
150 CFRelease(certParams
);
155 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
159 CFTypeRef itemKeys
[] = { kSecClass
, kSecAttrLabel
, kSecValueRef
};
160 CFTypeRef itemValues
[] = { kSecClassIdentity
, cfcommon_name
, ident
};
161 CFDictionaryRef itemAttrs
= CFDictionaryCreate(kCFAllocatorDefault
, itemKeys
, itemValues
, sizeof(itemKeys
) / sizeof(itemKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
163 err
= SecItemAdd(itemAttrs
, NULL
);
164 CFRelease(itemAttrs
);
173 * Cleanup and return...
179 CFRelease(cfcommon_name
);
182 CFRelease(keyParams
);
191 CFRelease(publicKey
);
194 CFRelease(publicKey
);
198 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
199 int pid
, /* Process ID of command */
200 status
, /* Status of command */
202 char command
[1024], /* Command */
203 *argv
[5], /* Command-line arguments */
204 *envp
[1000], /* Environment variables */
205 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
206 keychain
[1024], /* Keychain argument */
207 infofile
[1024], /* Type-in information for cert */
208 filename
[1024]; /* Default keychain path */
209 cups_file_t
*fp
; /* Seed/info file */
212 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
));
218 path
= http_cdsa_default_path(filename
, sizeof(filename
));
221 * Run the "certtool" command to generate a self-signed certificate...
224 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
228 * Create a file with the certificate information fields...
230 * Note: This assumes that the default questions are asked by the certtool
234 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
238 "CUPS Self-Signed Certificate\n"
239 /* Enter key and certificate label */
240 "r\n" /* Generate RSA key pair */
241 "2048\n" /* 2048 bit encryption key */
242 "y\n" /* OK (y = yes) */
243 "b\n" /* Usage (b=signing/encryption) */
244 "2\n" /* Sign with SHA256 */
245 "y\n" /* OK (y = yes) */
246 "%s\n" /* Common name */
247 "\n" /* Country (default) */
248 "\n" /* Organization (default) */
249 "\n" /* Organizational unit (default) */
250 "\n" /* State/Province (default) */
251 "\n" /* Email address */
252 "y\n", /* OK (y = yes) */
256 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
258 argv
[0] = "certtool";
263 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
265 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
266 envp
[i
+ 1] = environ
[i
];
269 posix_spawn_file_actions_t actions
; /* File actions */
271 posix_spawn_file_actions_init(&actions
);
272 posix_spawn_file_actions_addclose(&actions
, 0);
273 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
274 posix_spawn_file_actions_addclose(&actions
, 1);
275 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
276 posix_spawn_file_actions_addclose(&actions
, 2);
277 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
279 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
285 posix_spawn_file_actions_destroy(&actions
);
289 while (waitpid(pid
, &status
, 0) < 0)
297 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
302 * 'cupsSetServerCredentials()' - Set the default server credentials.
304 * Note: The server credentials are used by all threads in the running process.
305 * This function is threadsafe.
307 * @since CUPS 2.0/OS X 10.10@
310 int /* O - 1 on success, 0 on failure */
311 cupsSetServerCredentials(
312 const char *path
, /* I - Keychain path or @code NULL@ for default */
313 const char *common_name
, /* I - Default common name for server */
314 int auto_create
) /* I - 1 = automatically create self-signed certificates */
316 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
318 #ifdef HAVE_SECKEYCHAINOPEN
319 char filename
[1024]; /* Filename for keychain */
320 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
321 OSStatus status
; /* Status code */
325 path
= http_cdsa_default_path(filename
, sizeof(filename
));
327 if ((status
= SecKeychainOpen(path
, &keychain
)) != noErr
)
329 /* TODO: Set cups last error string */
330 DEBUG_printf(("1cupsSetServerCredentials: Unable to open keychain (%d), returning 0.", (int)status
));
334 _cupsMutexLock(&tls_mutex
);
337 * Close any keychain that is currently open...
341 CFRelease(tls_keychain
);
344 _cupsStrFree(tls_keypath
);
347 _cupsStrFree(tls_common_name
);
350 * Save the new keychain...
353 tls_keychain
= keychain
;
354 tls_keypath
= _cupsStrAlloc(path
);
355 tls_auto_create
= auto_create
;
356 tls_common_name
= _cupsStrAlloc(common_name
);
358 _cupsMutexUnlock(&tls_mutex
);
360 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
366 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
370 tls_auto_create
= auto_create
;
371 tls_common_name
= _cupsStrAlloc(common_name
);
374 #endif /* HAVE_SECKEYCHAINOPEN */
379 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
380 * an encrypted connection.
382 * @since CUPS 1.5/OS X 10.7@
385 int /* O - Status of call (0 = success) */
387 http_t
*http
, /* I - Connection to server */
388 cups_array_t
**credentials
) /* O - Array of credentials */
390 OSStatus error
; /* Error code */
391 SecTrustRef peerTrust
; /* Peer trust reference */
392 CFIndex count
; /* Number of credentials */
393 SecCertificateRef secCert
; /* Certificate reference */
394 CFDataRef data
; /* Certificate data */
395 int i
; /* Looping var */
398 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http
, (void *)credentials
));
403 if (!http
|| !http
->tls
|| !credentials
)
406 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
408 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
410 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
412 count
= SecTrustGetCertificateCount(peerTrust
);
414 for (i
= 0; i
< count
; i
++)
416 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
419 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
422 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
424 strlcpy(name
, "unknown", sizeof(name
));
426 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
429 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
431 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
433 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
439 CFRelease(peerTrust
);
447 * '_httpCreateCredentials()' - Create credentials in the internal format.
450 http_tls_credentials_t
/* O - Internal credentials */
451 _httpCreateCredentials(
452 cups_array_t
*credentials
) /* I - Array of credentials */
454 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
455 SecCertificateRef secCert
; /* Certificate reference */
456 http_credential_t
*credential
; /* Credential data */
462 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
463 cupsArrayCount(credentials
),
464 &kCFTypeArrayCallBacks
)) == NULL
)
467 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
469 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
471 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
473 CFArrayAppendValue(peerCerts
, secCert
);
483 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
485 * @since CUPS 2.0/OS X 10.10@
488 int /* O - 1 if valid, 0 otherwise */
489 httpCredentialsAreValidForName(
490 cups_array_t
*credentials
, /* I - Credentials */
491 const char *common_name
) /* I - Name to check */
493 SecCertificateRef secCert
; /* Certificate reference */
494 CFStringRef cfcert_name
= NULL
;
495 /* Certificate's common name (CF string) */
496 char cert_name
[256]; /* Certificate's common name (C string) */
497 int valid
= 1; /* Valid name? */
500 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
504 * Compare the common names...
507 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
510 * Can't get common name, cannot be valid...
515 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
516 _cups_strcasecmp(common_name
, cert_name
))
519 * Not an exact match for the common name, check for wildcard certs...
522 const char *domain
= strchr(common_name
, '.');
523 /* Domain in common name */
525 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
528 * Not a wildcard match.
531 /* TODO: Check subject alternate names */
537 CFRelease(cfcert_name
);
546 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
548 * @since CUPS 2.0/OS X 10.10@
551 http_trust_t
/* O - Level of trust */
552 httpCredentialsGetTrust(
553 cups_array_t
*credentials
, /* I - Credentials */
554 const char *common_name
) /* I - Common name for trust lookup */
556 SecCertificateRef secCert
; /* Certificate reference */
557 http_trust_t trust
= HTTP_TRUST_OK
;
559 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
560 _cups_globals_t
*cg
= _cupsGlobals();
561 /* Per-thread globals */
565 return (HTTP_TRUST_UNKNOWN
);
567 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
568 return (HTTP_TRUST_UNKNOWN
);
570 if (cg
->any_root
< 0)
574 * Look this common name up in the default keychains...
577 httpLoadCredentials(NULL
, &tcreds
, common_name
);
581 char credentials_str
[1024], /* String for incoming credentials */
582 tcreds_str
[1024]; /* String for saved credentials */
584 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
585 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
587 if (strcmp(credentials_str
, tcreds_str
))
590 * Credentials don't match, let's look at the expiration date of the new
591 * credentials and allow if the new ones have a later expiration...
594 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
595 !httpCredentialsAreValidForName(credentials
, common_name
))
598 * Either the new credentials are not newly issued, or the common name
599 * does not match the issued certificate...
602 trust
= HTTP_TRUST_INVALID
;
604 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
607 * Save the renewed credentials...
610 trust
= HTTP_TRUST_RENEWED
;
612 httpSaveCredentials(NULL
, credentials
, common_name
);
616 httpFreeCredentials(tcreds
);
618 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
619 trust
= HTTP_TRUST_INVALID
;
621 if (!cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
622 trust
= HTTP_TRUST_EXPIRED
;
623 else if (!cg
->any_root
&& cupsArrayCount(credentials
) == 1)
624 trust
= HTTP_TRUST_INVALID
;
633 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
635 * @since CUPS 2.0/OS X 10.10@
638 time_t /* O - Expiration date of credentials */
639 httpCredentialsGetExpiration(
640 cups_array_t
*credentials
) /* I - Credentials */
642 SecCertificateRef secCert
; /* Certificate reference */
643 time_t expiration
; /* Expiration date */
646 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
649 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
658 * 'httpCredentialsString()' - Return a string representing the credentials.
660 * @since CUPS 2.0/OS X 10.10@
663 size_t /* O - Total size of credentials string */
664 httpCredentialsString(
665 cups_array_t
*credentials
, /* I - Credentials */
666 char *buffer
, /* I - Buffer or @code NULL@ */
667 size_t bufsize
) /* I - Size of buffer */
669 http_credential_t
*first
; /* First certificate */
670 SecCertificateRef secCert
; /* Certificate reference */
673 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", (void *)credentials
, (void *)buffer
, CUPS_LLCAST bufsize
));
678 if (buffer
&& bufsize
> 0)
681 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
682 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
684 CFStringRef cf_name
; /* CF common name string */
685 char name
[256]; /* Common name associated with cert */
686 time_t expiration
; /* Expiration date of cert */
687 _cups_md5_state_t md5_state
; /* MD5 state */
688 unsigned char md5_digest
[16]; /* MD5 result */
690 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
692 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
696 strlcpy(name
, "unknown", sizeof(name
));
698 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
700 _cupsMD5Init(&md5_state
);
701 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
702 _cupsMD5Finish(&md5_state
, md5_digest
);
704 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]);
709 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
711 return (strlen(buffer
));
716 * '_httpFreeCredentials()' - Free internal credentials.
720 _httpFreeCredentials(
721 http_tls_credentials_t credentials
) /* I - Internal credentials */
726 CFRelease(credentials
);
731 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
733 * @since CUPS 2.0/OS 10.10@
736 int /* O - 0 on success, -1 on error */
738 const char *path
, /* I - Keychain path or @code NULL@ for default */
739 cups_array_t
**credentials
, /* IO - Credentials */
740 const char *common_name
) /* I - Common name for credentials */
742 OSStatus err
; /* Error info */
743 #ifdef HAVE_SECKEYCHAINOPEN
744 char filename
[1024]; /* Filename for keychain */
745 SecKeychainRef keychain
= NULL
;/* Keychain reference */
746 CFArrayRef list
; /* Keychain list */
747 #endif /* HAVE_SECKEYCHAINOPEN */
748 SecCertificateRef cert
= NULL
; /* Certificate */
749 CFDataRef data
; /* Certificate data */
750 SecPolicyRef policy
= NULL
; /* Policy ref */
751 CFStringRef cfcommon_name
= NULL
;
753 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
756 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
763 #ifdef HAVE_SECKEYCHAINOPEN
765 path
= http_cdsa_default_path(filename
, sizeof(filename
));
767 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
773 #endif /* HAVE_SECKEYCHAINOPEN */
775 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
777 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
780 CFRelease(cfcommon_name
);
785 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
788 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
789 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
790 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
791 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
793 #ifdef HAVE_SECKEYCHAINOPEN
794 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
795 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
797 #endif /* HAVE_SECKEYCHAINOPEN */
799 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
804 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
807 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
809 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
811 *credentials
= cupsArrayNew(NULL
, NULL
);
812 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
818 #ifdef HAVE_SECKEYCHAINOPEN
821 #endif /* HAVE_SECKEYCHAINOPEN */
829 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
831 return (*credentials
? 0 : -1);
836 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
838 * @since CUPS 2.0/OS 10.10@
841 int /* O - -1 on error, 0 on success */
843 const char *path
, /* I - Keychain path or @code NULL@ for default */
844 cups_array_t
*credentials
, /* I - Credentials */
845 const char *common_name
) /* I - Common name for credentials */
847 int ret
= -1; /* Return value */
848 OSStatus err
; /* Error info */
849 #ifdef HAVE_SECKEYCHAINOPEN
850 char filename
[1024]; /* Filename for keychain */
851 SecKeychainRef keychain
= NULL
;/* Keychain reference */
852 CFArrayRef list
; /* Keychain list */
853 #endif /* HAVE_SECKEYCHAINOPEN */
854 SecCertificateRef cert
= NULL
; /* Certificate */
855 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
858 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
862 if (!httpCredentialsAreValidForName(credentials
, common_name
))
864 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
868 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
870 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
874 #ifdef HAVE_SECKEYCHAINOPEN
876 path
= http_cdsa_default_path(filename
, sizeof(filename
));
878 if ((err
= SecKeychainOpen(path
, &keychain
)) != noErr
)
880 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err
));
887 #endif /* HAVE_SECKEYCHAINOPEN */
889 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
891 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
895 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
896 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
898 #ifdef HAVE_SECKEYCHAINOPEN
899 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
901 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
904 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
906 #endif /* HAVE_SECKEYCHAINOPEN */
908 /* Note: SecItemAdd consumes "attrs"... */
909 err
= SecItemAdd(attrs
, NULL
);
910 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
914 #ifdef HAVE_SECKEYCHAINOPEN
917 #endif /* HAVE_SECKEYCHAINOPEN */
921 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
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 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1011 _httpTLSSetOptions(int options
) /* I - Options */
1013 tls_options
= options
;
1018 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1021 int /* O - 0 on success, -1 on failure */
1022 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
1024 char hostname
[256], /* Hostname */
1025 *hostptr
; /* Pointer into hostname */
1026 _cups_globals_t
*cg
= _cupsGlobals();
1027 /* Pointer to library globals */
1028 OSStatus error
; /* Error code */
1029 const char *message
= NULL
;/* Error message */
1030 cups_array_t
*credentials
; /* Credentials array */
1031 cups_array_t
*names
; /* CUPS distinguished names */
1032 CFArrayRef dn_array
; /* CF distinguished names array */
1033 CFIndex count
; /* Number of credentials */
1034 CFDataRef data
; /* Certificate data */
1035 int i
; /* Looping var */
1036 http_credential_t
*credential
; /* Credential data */
1039 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http
));
1041 if (tls_options
< 0)
1043 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1045 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1048 #ifdef HAVE_SECKEYCHAINOPEN
1049 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1051 if (http
->mode
== _HTTP_MODE_SERVER
)
1052 #endif /* HAVE_SECKEYCHAINOPEN */
1054 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1055 http
->error
= errno
= EINVAL
;
1056 http
->status
= HTTP_STATUS_ERROR
;
1057 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1062 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1064 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1065 http
->error
= errno
= ENOMEM
;
1066 http
->status
= HTTP_STATUS_ERROR
;
1067 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1072 error
= SSLSetConnection(http
->tls
, http
);
1073 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1077 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1078 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1083 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1085 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error
));
1090 SSLProtocol minProtocol
;
1092 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1093 minProtocol
= kTLSProtocol11
;
1094 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1095 minProtocol
= kSSLProtocol3
;
1097 minProtocol
= kTLSProtocol1
;
1099 error
= SSLSetProtocolVersionMin(http
->tls
, minProtocol
);
1100 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol
, (int)error
));
1103 # if HAVE_SSLSETENABLEDCIPHERS
1106 SSLCipherSuite supported
[100]; /* Supported cipher suites */
1107 size_t num_supported
; /* Number of supported cipher suites */
1108 SSLCipherSuite enabled
[100]; /* Cipher suites to enable */
1109 size_t num_enabled
; /* Number of cipher suites to enable */
1111 num_supported
= sizeof(supported
) / sizeof(supported
[0]);
1112 error
= SSLGetSupportedCiphers(http
->tls
, supported
, &num_supported
);
1116 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported
));
1118 for (i
= 0, num_enabled
= 0; i
< (int)num_supported
&& num_enabled
< (sizeof(enabled
) / sizeof(enabled
[0])); i
++)
1120 switch (supported
[i
])
1122 /* Obviously insecure cipher suites that we never want to use */
1123 case SSL_NULL_WITH_NULL_NULL
:
1124 case SSL_RSA_WITH_NULL_MD5
:
1125 case SSL_RSA_WITH_NULL_SHA
:
1126 case SSL_RSA_EXPORT_WITH_RC4_40_MD5
:
1127 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
1128 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1129 case SSL_RSA_WITH_DES_CBC_SHA
:
1130 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1131 case SSL_DH_DSS_WITH_DES_CBC_SHA
:
1132 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1133 case SSL_DH_RSA_WITH_DES_CBC_SHA
:
1134 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1135 case SSL_DHE_DSS_WITH_DES_CBC_SHA
:
1136 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1137 case SSL_DHE_RSA_WITH_DES_CBC_SHA
:
1138 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
:
1139 case SSL_DH_anon_WITH_RC4_128_MD5
:
1140 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
:
1141 case SSL_DH_anon_WITH_DES_CBC_SHA
:
1142 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
:
1143 case SSL_FORTEZZA_DMS_WITH_NULL_SHA
:
1144 case TLS_DH_anon_WITH_AES_128_CBC_SHA
:
1145 case TLS_DH_anon_WITH_AES_256_CBC_SHA
:
1146 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
1147 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
1148 case TLS_ECDH_anon_WITH_NULL_SHA
:
1149 case TLS_ECDH_anon_WITH_RC4_128_SHA
:
1150 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
:
1151 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA
:
1152 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA
:
1153 case TLS_RSA_WITH_NULL_SHA256
:
1154 case TLS_DH_anon_WITH_AES_128_CBC_SHA256
:
1155 case TLS_DH_anon_WITH_AES_256_CBC_SHA256
:
1156 case TLS_PSK_WITH_NULL_SHA
:
1157 case TLS_DHE_PSK_WITH_NULL_SHA
:
1158 case TLS_RSA_PSK_WITH_NULL_SHA
:
1159 case TLS_DH_anon_WITH_AES_128_GCM_SHA256
:
1160 case TLS_DH_anon_WITH_AES_256_GCM_SHA384
:
1161 case TLS_PSK_WITH_NULL_SHA256
:
1162 case TLS_PSK_WITH_NULL_SHA384
:
1163 case TLS_DHE_PSK_WITH_NULL_SHA256
:
1164 case TLS_DHE_PSK_WITH_NULL_SHA384
:
1165 case TLS_RSA_PSK_WITH_NULL_SHA256
:
1166 case TLS_RSA_PSK_WITH_NULL_SHA384
:
1167 case SSL_RSA_WITH_DES_CBC_MD5
:
1168 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported
[i
]));
1171 /* RC4 cipher suites that should only be used as a last resort */
1172 case SSL_RSA_WITH_RC4_128_MD5
:
1173 case SSL_RSA_WITH_RC4_128_SHA
:
1174 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
1175 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
1176 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
1177 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
1178 case TLS_PSK_WITH_RC4_128_SHA
:
1179 case TLS_DHE_PSK_WITH_RC4_128_SHA
:
1180 case TLS_RSA_PSK_WITH_RC4_128_SHA
:
1181 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1182 enabled
[num_enabled
++] = supported
[i
];
1184 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported
[i
]));
1187 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1188 case TLS_DH_DSS_WITH_AES_128_CBC_SHA
:
1189 case TLS_DH_RSA_WITH_AES_128_CBC_SHA
:
1190 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA
:
1191 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA
:
1192 case TLS_DH_DSS_WITH_AES_256_CBC_SHA
:
1193 case TLS_DH_RSA_WITH_AES_256_CBC_SHA
:
1194 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA
:
1195 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA
:
1196 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
:
1197 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
:
1198 // case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
1199 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
:
1200 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256
:
1201 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256
:
1202 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
:
1203 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
:
1204 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256
:
1205 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256
:
1206 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
:
1207 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
:
1208 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
:
1209 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA
:
1210 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA
:
1211 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1212 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1213 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256
:
1214 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384
:
1215 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1216 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1217 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256
:
1218 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384
:
1219 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
:
1220 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
:
1221 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
:
1222 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
:
1223 if (tls_options
& _HTTP_TLS_ALLOW_DH
)
1224 enabled
[num_enabled
++] = supported
[i
];
1226 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported
[i
]));
1229 /* Anything else we'll assume is secure */
1231 enabled
[num_enabled
++] = supported
[i
];
1236 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled
));
1237 error
= SSLSetEnabledCiphers(http
->tls
, enabled
, num_enabled
);
1240 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1242 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1245 * Client: set client-side credentials, if any...
1248 if (cg
->client_cert_cb
)
1250 error
= SSLSetSessionOption(http
->tls
,
1251 kSSLSessionOptionBreakOnCertRequested
, true);
1252 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1253 "error=%d", (int)error
));
1257 error
= http_cdsa_set_credentials(http
);
1258 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1265 * Server: find/create a certificate for TLS...
1268 if (http
->fields
[HTTP_FIELD_HOST
][0])
1271 * Use hostname for TLS upgrade...
1274 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1279 * Resolve hostname from connection address...
1282 http_addr_t addr
; /* Connection address */
1283 socklen_t addrlen
; /* Length of address */
1285 addrlen
= sizeof(addr
);
1286 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1288 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1291 else if (httpAddrLocalhost(&addr
))
1295 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1296 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1300 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1301 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1304 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1305 else if (tls_common_name
)
1306 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1308 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1310 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1312 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1314 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1315 http
->error
= errno
= EINVAL
;
1316 http
->status
= HTTP_STATUS_ERROR
;
1317 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1322 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1325 if (!http
->tls_credentials
)
1327 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1328 http
->error
= errno
= EINVAL
;
1329 http
->status
= HTTP_STATUS_ERROR
;
1330 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1335 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1337 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1340 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http
->tls_credentials
));
1343 * Let the server know which hostname/domain we are trying to connect to
1344 * in case it wants to serve up a certificate with a matching common name.
1347 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1350 * Client: get the hostname to use for TLS...
1353 if (httpAddrLocalhost(http
->hostaddr
))
1355 strlcpy(hostname
, "localhost", sizeof(hostname
));
1360 * Otherwise make sure the hostname we have does not end in a trailing dot.
1363 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1364 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1369 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1371 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1376 int done
= 0; /* Are we done yet? */
1378 while (!error
&& !done
)
1380 error
= SSLHandshake(http
->tls
);
1382 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1390 case errSSLWouldBlock
:
1391 error
= noErr
; /* Force a retry */
1392 usleep(1000); /* in 1 millisecond */
1395 case errSSLServerAuthCompleted
:
1397 if (cg
->server_cert_cb
)
1399 error
= httpCopyCredentials(http
, &credentials
);
1402 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1403 cg
->server_cert_data
);
1404 httpFreeCredentials(credentials
);
1407 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1408 "returned %d.", (int)error
));
1412 case errSSLClientCertRequested
:
1415 if (cg
->client_cert_cb
)
1418 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1421 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1423 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1425 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1427 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1429 credential
->datalen
= (size_t)CFDataGetLength(data
);
1430 if ((credential
->data
= malloc(credential
->datalen
)))
1432 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1433 credential
->datalen
);
1434 cupsArrayAdd(names
, credential
);
1442 CFRelease(dn_array
);
1447 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1448 cg
->client_cert_data
);
1450 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1451 "returned %d.", (int)error
));
1454 httpFreeCredentials(names
);
1458 case errSSLUnknownRootCert
:
1459 message
= _("Unable to establish a secure connection to host "
1460 "(untrusted certificate).");
1463 case errSSLNoRootCert
:
1464 message
= _("Unable to establish a secure connection to host "
1465 "(self-signed certificate).");
1468 case errSSLCertExpired
:
1469 message
= _("Unable to establish a secure connection to host "
1470 "(expired certificate).");
1473 case errSSLCertNotYetValid
:
1474 message
= _("Unable to establish a secure connection to host "
1475 "(certificate not yet valid).");
1478 case errSSLHostNameMismatch
:
1479 message
= _("Unable to establish a secure connection to host "
1480 "(host name mismatch).");
1483 case errSSLXCertChainInvalid
:
1484 message
= _("Unable to establish a secure connection to host "
1485 "(certificate chain invalid).");
1488 case errSSLConnectionRefused
:
1489 message
= _("Unable to establish a secure connection to host "
1490 "(peer dropped connection before responding).");
1501 http
->error
= error
;
1502 http
->status
= HTTP_STATUS_ERROR
;
1503 errno
= ECONNREFUSED
;
1505 CFRelease(http
->tls
);
1509 * If an error string wasn't set by the callbacks use a generic one...
1513 #ifdef HAVE_CSSMERRORSTRING
1514 message
= cssmErrorString(error
);
1516 message
= _("Unable to establish a secure connection to host.");
1517 #endif /* HAVE_CSSMERRORSTRING */
1519 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1529 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1533 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1535 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1538 CFRelease(http
->tls
);
1540 if (http
->tls_credentials
)
1541 CFRelease(http
->tls_credentials
);
1544 http
->tls_credentials
= NULL
;
1549 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1552 int /* O - Bytes written */
1553 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1554 const char *buf
, /* I - Buffer holding data */
1555 int len
) /* I - Length of buffer */
1557 ssize_t result
; /* Return value */
1558 OSStatus error
; /* Error info */
1559 size_t processed
; /* Number of bytes processed */
1562 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http
, (void *)buf
, len
));
1564 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1569 result
= (int)processed
;
1572 case errSSLWouldBlock
:
1575 result
= (int)processed
;
1584 case errSSLClosedGraceful
:
1588 result
= (int)processed
;
1598 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1600 return ((int)result
);
1605 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1608 static CFArrayRef
/* O - Array of certificates or NULL */
1609 http_cdsa_copy_server(
1610 const char *common_name
) /* I - Server's hostname */
1612 OSStatus err
; /* Error info */
1613 SecIdentityRef identity
= NULL
;/* Identity */
1614 CFArrayRef certificates
= NULL
;
1615 /* Certificate array */
1616 SecPolicyRef policy
= NULL
; /* Policy ref */
1617 CFStringRef cfcommon_name
= NULL
;
1619 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1620 #ifdef HAVE_SECKEYCHAINOPEN
1621 CFArrayRef list
= NULL
; /* Keychain list */
1622 #endif /* HAVE_SECKEYCHAINOPEN */
1625 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1627 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1630 CFRelease(cfcommon_name
);
1635 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1638 _cupsMutexLock(&tls_mutex
);
1640 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1641 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1642 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1643 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1645 #ifdef HAVE_SECKEYCHAINOPEN
1646 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1647 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1649 #endif /* HAVE_SECKEYCHAINOPEN */
1651 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1653 _cupsMutexUnlock(&tls_mutex
);
1658 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1661 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1667 CFRelease(identity
);
1673 return (certificates
);
1678 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1681 static SecCertificateRef
/* O - Certificate */
1682 http_cdsa_create_credential(
1683 http_credential_t
*credential
) /* I - Credential */
1688 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1692 #ifdef HAVE_SECKEYCHAINOPEN
1694 * 'http_cdsa_default_path()' - Get the default keychain path.
1697 static const char * /* O - Keychain path */
1698 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1699 size_t bufsize
) /* I - Size of buffer */
1701 const char *home
= getenv("HOME"); /* HOME environment variable */
1704 if (getuid() && home
)
1705 snprintf(buffer
, bufsize
, "%s/Library/Keychains/login.keychain", home
);
1707 strlcpy(buffer
, "/Library/Keychains/System.keychain", bufsize
);
1709 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1713 #endif /* HAVE_SECKEYCHAINOPEN */
1717 * 'http_cdsa_read()' - Read function for the CDSA library.
1720 static OSStatus
/* O - -1 on error, 0 on success */
1722 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1723 void *data
, /* I - Data buffer */
1724 size_t *dataLength
) /* IO - Number of bytes */
1726 OSStatus result
; /* Return value */
1727 ssize_t bytes
; /* Number of bytes read */
1728 http_t
*http
; /* HTTP connection */
1731 http
= (http_t
*)connection
;
1733 if (!http
->blocking
)
1736 * Make sure we have data before we read...
1739 while (!_httpWait(http
, http
->wait_value
, 0))
1741 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1744 http
->error
= ETIMEDOUT
;
1751 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1753 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1755 if ((size_t)bytes
== *dataLength
)
1761 *dataLength
= (size_t)bytes
;
1762 result
= errSSLWouldBlock
;
1769 result
= errSSLClosedGraceful
;
1770 else if (errno
== EAGAIN
)
1771 result
= errSSLWouldBlock
;
1773 result
= errSSLClosedAbort
;
1781 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1784 static int /* O - Status of connection */
1785 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
1787 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1788 OSStatus error
= 0; /* Error code */
1789 http_tls_credentials_t credentials
= NULL
;
1790 /* TLS credentials */
1793 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http
));
1796 * Prefer connection specific credentials...
1799 if ((credentials
= http
->tls_credentials
) == NULL
)
1800 credentials
= cg
->tls_credentials
;
1804 error
= SSLSetCertificate(http
->tls
, credentials
);
1805 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1809 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1816 * 'http_cdsa_write()' - Write function for the CDSA library.
1819 static OSStatus
/* O - -1 on error, 0 on success */
1821 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1822 const void *data
, /* I - Data buffer */
1823 size_t *dataLength
) /* IO - Number of bytes */
1825 OSStatus result
; /* Return value */
1826 ssize_t bytes
; /* Number of bytes read */
1827 http_t
*http
; /* HTTP connection */
1830 http
= (http_t
*)connection
;
1834 bytes
= write(http
->fd
, data
, *dataLength
);
1836 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1838 if ((size_t)bytes
== *dataLength
)
1842 else if (bytes
>= 0)
1844 *dataLength
= (size_t)bytes
;
1845 result
= errSSLWouldBlock
;
1851 if (errno
== EAGAIN
)
1852 result
= errSSLWouldBlock
;
1854 result
= errSSLClosedAbort
;