2 * TLS support code for CUPS on macOS.
4 * Copyright 2007-2017 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 * 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
; /* @private@ */
28 * Constants, very secure stuff...
31 #define _CUPS_CDSA_PASSWORD "42" /* CUPS keychain password */
32 #define _CUPS_CDSA_PASSLEN 2 /* Length of keychain password */
39 static int tls_auto_create
= 0;
40 /* Auto-create self-signed certs? */
41 static char *tls_common_name
= NULL
;
42 /* Default common name */
43 #ifdef HAVE_SECKEYCHAINOPEN
44 static int tls_cups_keychain
= 0;
45 /* Opened the CUPS keychain? */
46 static SecKeychainRef tls_keychain
= NULL
;
47 /* Server cert keychain */
49 static SecIdentityRef tls_selfsigned
= NULL
;
50 /* Temporary self-signed cert */
51 #endif /* HAVE_SECKEYCHAINOPEN */
52 static char *tls_keypath
= NULL
;
53 /* Server cert keychain path */
54 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
55 /* Mutex for keychain/certs */
56 static int tls_options
= -1;/* Options for TLS connections */
63 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
64 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
65 #ifdef HAVE_SECKEYCHAINOPEN
66 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
67 static SecKeychainRef
http_cdsa_open_keychain(const char *path
, char *filename
, size_t filesize
);
68 static SecKeychainRef
http_cdsa_open_system_keychain(void);
69 #endif /* HAVE_SECKEYCHAINOPEN */
70 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
71 static int http_cdsa_set_credentials(http_t
*http
);
72 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
76 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
78 * @since CUPS 2.0/OS 10.10@
81 int /* O - 1 on success, 0 on failure */
82 cupsMakeServerCredentials(
83 const char *path
, /* I - Keychain path or @code NULL@ for default */
84 const char *common_name
, /* I - Common name */
85 int num_alt_names
, /* I - Number of subject alternate names */
86 const char **alt_names
, /* I - Subject Alternate Names */
87 time_t expiration_date
) /* I - Expiration date */
89 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
90 int status
= 0; /* Return status */
91 OSStatus err
; /* Error code (if any) */
92 CFStringRef cfcommon_name
= NULL
;
93 /* CF string for server name */
94 SecIdentityRef ident
= NULL
; /* Identity */
95 SecKeyRef publicKey
= NULL
,
99 SecCertificateRef cert
= NULL
; /* Self-signed certificate */
100 CFMutableDictionaryRef keyParams
= NULL
;
101 /* Key generation parameters */
104 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
));
109 (void)expiration_date
;
113 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
119 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
123 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
126 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
131 * Create a public/private key pair...
134 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
137 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
141 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
142 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
143 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, cfcommon_name
);
145 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
148 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err
));
153 * Create a self-signed certificate using the public/private key pair...
156 CFIndex usageInt
= kSecKeyUsageAll
;
157 CFNumberRef usage
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &usageInt
);
159 CFNumberRef len
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &lenInt
);
160 CFTypeRef certKeys
[] = { kSecCSRBasicContraintsPathLen
, kSecSubjectAltName
, kSecCertificateKeyUsage
};
161 CFTypeRef certValues
[] = { len
, cfcommon_name
, usage
};
162 CFDictionaryRef certParams
= CFDictionaryCreate(kCFAllocatorDefault
, certKeys
, certValues
, sizeof(certKeys
) / sizeof(certKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
166 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
167 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
168 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
169 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
170 const void *ca_dn_array
[2];
172 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
173 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
175 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
177 cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
180 CFRelease(certParams
);
184 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
188 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
192 _cupsMutexLock(&tls_mutex
);
197 tls_selfsigned
= ident
;
199 _cupsMutexLock(&tls_mutex
);
201 # if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point */
202 CFTypeRef itemKeys
[] = { kSecClass
, kSecAttrLabel
, kSecValueRef
};
203 CFTypeRef itemValues
[] = { kSecClassIdentity
, cfcommon_name
, ident
};
204 CFDictionaryRef itemAttrs
= CFDictionaryCreate(kCFAllocatorDefault
, itemKeys
, itemValues
, sizeof(itemKeys
) / sizeof(itemKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
206 err
= SecItemAdd(itemAttrs
, NULL
);
207 /* SecItemAdd consumes itemAttrs... */
213 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err
));
221 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
224 * Cleanup and return...
230 CFRelease(cfcommon_name
);
233 CFRelease(keyParams
);
239 CFRelease(publicKey
);
242 CFRelease(privateKey
);
244 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status
));
248 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
249 int pid
, /* Process ID of command */
250 status
, /* Status of command */
252 char command
[1024], /* Command */
253 *argv
[5], /* Command-line arguments */
254 *envp
[1000], /* Environment variables */
255 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
256 keychain
[1024], /* Keychain argument */
257 infofile
[1024], /* Type-in information for cert */
258 filename
[1024]; /* Default keychain path */
259 cups_file_t
*fp
; /* Seed/info file */
262 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
));
268 path
= http_cdsa_default_path(filename
, sizeof(filename
));
271 * Run the "certtool" command to generate a self-signed certificate...
274 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
278 * Create a file with the certificate information fields...
280 * Note: This assumes that the default questions are asked by the certtool
284 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
288 "CUPS Self-Signed Certificate\n"
289 /* Enter key and certificate label */
290 "r\n" /* Generate RSA key pair */
291 "2048\n" /* 2048 bit encryption key */
292 "y\n" /* OK (y = yes) */
293 "b\n" /* Usage (b=signing/encryption) */
294 "2\n" /* Sign with SHA256 */
295 "y\n" /* OK (y = yes) */
296 "%s\n" /* Common name */
297 "\n" /* Country (default) */
298 "\n" /* Organization (default) */
299 "\n" /* Organizational unit (default) */
300 "\n" /* State/Province (default) */
301 "\n" /* Email address */
302 "y\n", /* OK (y = yes) */
306 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
308 argv
[0] = "certtool";
313 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
315 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
316 envp
[i
+ 1] = environ
[i
];
319 posix_spawn_file_actions_t actions
; /* File actions */
321 posix_spawn_file_actions_init(&actions
);
322 posix_spawn_file_actions_addclose(&actions
, 0);
323 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
324 posix_spawn_file_actions_addclose(&actions
, 1);
325 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
326 posix_spawn_file_actions_addclose(&actions
, 2);
327 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
329 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
335 posix_spawn_file_actions_destroy(&actions
);
339 while (waitpid(pid
, &status
, 0) < 0)
347 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
352 * 'cupsSetServerCredentials()' - Set the default server credentials.
354 * Note: The server credentials are used by all threads in the running process.
355 * This function is threadsafe.
357 * @since CUPS 2.0/macOS 10.10@
360 int /* O - 1 on success, 0 on failure */
361 cupsSetServerCredentials(
362 const char *path
, /* I - Keychain path or @code NULL@ for default */
363 const char *common_name
, /* I - Default common name for server */
364 int auto_create
) /* I - 1 = automatically create self-signed certificates */
366 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
368 #ifdef HAVE_SECKEYCHAINOPEN
369 char filename
[1024]; /* Keychain filename */
370 SecKeychainRef keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
374 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain.");
378 _cupsMutexLock(&tls_mutex
);
381 * Close any keychain that is currently open...
385 CFRelease(tls_keychain
);
388 _cupsStrFree(tls_keypath
);
391 _cupsStrFree(tls_common_name
);
394 * Save the new keychain...
397 tls_keychain
= keychain
;
398 tls_keypath
= _cupsStrAlloc(filename
);
399 tls_auto_create
= auto_create
;
400 tls_common_name
= _cupsStrAlloc(common_name
);
402 _cupsMutexUnlock(&tls_mutex
);
404 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
410 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
414 tls_auto_create
= auto_create
;
415 tls_common_name
= _cupsStrAlloc(common_name
);
418 #endif /* HAVE_SECKEYCHAINOPEN */
423 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
424 * an encrypted connection.
426 * @since CUPS 1.5/macOS 10.7@
429 int /* O - Status of call (0 = success) */
431 http_t
*http
, /* I - Connection to server */
432 cups_array_t
**credentials
) /* O - Array of credentials */
434 OSStatus error
; /* Error code */
435 SecTrustRef peerTrust
; /* Peer trust reference */
436 CFIndex count
; /* Number of credentials */
437 SecCertificateRef secCert
; /* Certificate reference */
438 CFDataRef data
; /* Certificate data */
439 int i
; /* Looping var */
442 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http
, (void *)credentials
));
447 if (!http
|| !http
->tls
|| !credentials
)
450 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
452 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
454 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
456 count
= SecTrustGetCertificateCount(peerTrust
);
458 for (i
= 0; i
< count
; i
++)
460 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
463 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
466 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
468 strlcpy(name
, "unknown", sizeof(name
));
470 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
473 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
475 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
477 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
483 CFRelease(peerTrust
);
491 * '_httpCreateCredentials()' - Create credentials in the internal format.
494 http_tls_credentials_t
/* O - Internal credentials */
495 _httpCreateCredentials(
496 cups_array_t
*credentials
) /* I - Array of credentials */
498 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
499 SecCertificateRef secCert
; /* Certificate reference */
500 http_credential_t
*credential
; /* Credential data */
506 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
507 cupsArrayCount(credentials
),
508 &kCFTypeArrayCallBacks
)) == NULL
)
511 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
513 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
515 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
517 CFArrayAppendValue(peerCerts
, secCert
);
527 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
529 * @since CUPS 2.0/macOS 10.10@
532 int /* O - 1 if valid, 0 otherwise */
533 httpCredentialsAreValidForName(
534 cups_array_t
*credentials
, /* I - Credentials */
535 const char *common_name
) /* I - Name to check */
537 SecCertificateRef secCert
; /* Certificate reference */
538 CFStringRef cfcert_name
= NULL
;
539 /* Certificate's common name (CF string) */
540 char cert_name
[256]; /* Certificate's common name (C string) */
541 int valid
= 1; /* Valid name? */
544 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
548 * Compare the common names...
551 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
554 * Can't get common name, cannot be valid...
559 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
560 _cups_strcasecmp(common_name
, cert_name
))
563 * Not an exact match for the common name, check for wildcard certs...
566 const char *domain
= strchr(common_name
, '.');
567 /* Domain in common name */
569 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
572 * Not a wildcard match.
575 /* TODO: Check subject alternate names */
581 CFRelease(cfcert_name
);
590 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
592 * @since CUPS 2.0/macOS 10.10@
595 http_trust_t
/* O - Level of trust */
596 httpCredentialsGetTrust(
597 cups_array_t
*credentials
, /* I - Credentials */
598 const char *common_name
) /* I - Common name for trust lookup */
600 SecCertificateRef secCert
; /* Certificate reference */
601 http_trust_t trust
= HTTP_TRUST_OK
;
603 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
604 _cups_globals_t
*cg
= _cupsGlobals();
605 /* Per-thread globals */
610 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No common name specified."), 1);
611 return (HTTP_TRUST_UNKNOWN
);
614 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
616 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create credentials from array."), 1);
617 return (HTTP_TRUST_UNKNOWN
);
620 if (cg
->any_root
< 0)
624 * Look this common name up in the default keychains...
627 httpLoadCredentials(NULL
, &tcreds
, common_name
);
631 char credentials_str
[1024], /* String for incoming credentials */
632 tcreds_str
[1024]; /* String for saved credentials */
634 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
635 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
637 if (strcmp(credentials_str
, tcreds_str
))
640 * Credentials don't match, let's look at the expiration date of the new
641 * credentials and allow if the new ones have a later expiration...
644 if (!cg
->trust_first
)
647 * Do not trust certificates on first use...
650 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
652 trust
= HTTP_TRUST_INVALID
;
654 else if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
))
657 * The new credentials are not newly issued...
660 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are older than stored credentials."), 1);
662 trust
= HTTP_TRUST_INVALID
;
664 else if (!httpCredentialsAreValidForName(credentials
, common_name
))
667 * The common name does not match the issued certificate...
670 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are not valid for name."), 1);
672 trust
= HTTP_TRUST_INVALID
;
674 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
677 * Save the renewed credentials...
680 trust
= HTTP_TRUST_RENEWED
;
682 httpSaveCredentials(NULL
, credentials
, common_name
);
686 httpFreeCredentials(tcreds
);
688 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
690 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No stored credentials, not valid for name."), 1);
691 trust
= HTTP_TRUST_INVALID
;
693 else if (!cg
->trust_first
)
696 * See if we have a site CA certificate we can compare...
699 if (!httpLoadCredentials(NULL
, &tcreds
, "site"))
701 if (cupsArrayCount(credentials
) != (cupsArrayCount(tcreds
) + 1))
704 * Certificate isn't directly generated from the CA cert...
707 trust
= HTTP_TRUST_INVALID
;
712 * Do a tail comparison of the two certificates...
715 http_credential_t
*a
, *b
; /* Certificates */
717 for (a
= (http_credential_t
*)cupsArrayFirst(tcreds
), b
= (http_credential_t
*)cupsArrayIndex(credentials
, 1);
719 a
= (http_credential_t
*)cupsArrayNext(tcreds
), b
= (http_credential_t
*)cupsArrayNext(credentials
))
720 if (a
->datalen
!= b
->datalen
|| memcmp(a
->data
, b
->data
, a
->datalen
))
724 trust
= HTTP_TRUST_INVALID
;
727 if (trust
!= HTTP_TRUST_OK
)
728 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials do not validate against site CA certificate."), 1);
732 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
733 trust
= HTTP_TRUST_INVALID
;
737 if (trust
== HTTP_TRUST_OK
&& !cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
739 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials have expired."), 1);
740 trust
= HTTP_TRUST_EXPIRED
;
743 if (trust
== HTTP_TRUST_OK
&& !cg
->any_root
&& cupsArrayCount(credentials
) == 1)
745 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Self-signed credentials are blocked."), 1);
746 trust
= HTTP_TRUST_INVALID
;
756 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
758 * @since CUPS 2.0/macOS 10.10@
761 time_t /* O - Expiration date of credentials */
762 httpCredentialsGetExpiration(
763 cups_array_t
*credentials
) /* I - Credentials */
765 SecCertificateRef secCert
; /* Certificate reference */
766 time_t expiration
; /* Expiration date */
769 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
772 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
781 * 'httpCredentialsString()' - Return a string representing the credentials.
783 * @since CUPS 2.0/macOS 10.10@
786 size_t /* O - Total size of credentials string */
787 httpCredentialsString(
788 cups_array_t
*credentials
, /* I - Credentials */
789 char *buffer
, /* I - Buffer or @code NULL@ */
790 size_t bufsize
) /* I - Size of buffer */
792 http_credential_t
*first
; /* First certificate */
793 SecCertificateRef secCert
; /* Certificate reference */
796 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", (void *)credentials
, (void *)buffer
, CUPS_LLCAST bufsize
));
801 if (buffer
&& bufsize
> 0)
804 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
805 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
807 CFStringRef cf_name
; /* CF common name string */
808 char name
[256]; /* Common name associated with cert */
809 time_t expiration
; /* Expiration date of cert */
810 _cups_md5_state_t md5_state
; /* MD5 state */
811 unsigned char md5_digest
[16]; /* MD5 result */
813 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
815 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
819 strlcpy(name
, "unknown", sizeof(name
));
821 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
823 _cupsMD5Init(&md5_state
);
824 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
825 _cupsMD5Finish(&md5_state
, md5_digest
);
827 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]);
832 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
834 return (strlen(buffer
));
839 * '_httpFreeCredentials()' - Free internal credentials.
843 _httpFreeCredentials(
844 http_tls_credentials_t credentials
) /* I - Internal credentials */
849 CFRelease(credentials
);
854 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
856 * @since CUPS 2.0/OS 10.10@
859 int /* O - 0 on success, -1 on error */
861 const char *path
, /* I - Keychain path or @code NULL@ for default */
862 cups_array_t
**credentials
, /* IO - Credentials */
863 const char *common_name
) /* I - Common name for credentials */
865 OSStatus err
; /* Error info */
866 #ifdef HAVE_SECKEYCHAINOPEN
867 char filename
[1024]; /* Filename for keychain */
868 SecKeychainRef keychain
= NULL
,/* Keychain reference */
869 syschain
= NULL
;/* System keychain */
870 CFArrayRef list
; /* Keychain list */
871 #endif /* HAVE_SECKEYCHAINOPEN */
872 SecCertificateRef cert
= NULL
; /* Certificate */
873 CFDataRef data
; /* Certificate data */
874 SecPolicyRef policy
= NULL
; /* Policy ref */
875 CFStringRef cfcommon_name
= NULL
;
877 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
880 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
887 #ifdef HAVE_SECKEYCHAINOPEN
888 keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
893 syschain
= http_cdsa_open_system_keychain();
898 #endif /* HAVE_SECKEYCHAINOPEN */
900 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
902 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
905 CFRelease(cfcommon_name
);
910 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
913 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
914 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
915 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
916 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
918 #ifdef HAVE_SECKEYCHAINOPEN
921 const void *values
[2] = { syschain
, keychain
};
923 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)values
, 2, &kCFTypeArrayCallBacks
);
926 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
927 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
929 #endif /* HAVE_SECKEYCHAINOPEN */
931 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
936 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
939 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
941 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
943 *credentials
= cupsArrayNew(NULL
, NULL
);
944 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
950 #ifdef HAVE_SECKEYCHAINOPEN
956 #endif /* HAVE_SECKEYCHAINOPEN */
964 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
966 return (*credentials
? 0 : -1);
971 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
973 * @since CUPS 2.0/OS 10.10@
976 int /* O - -1 on error, 0 on success */
978 const char *path
, /* I - Keychain path or @code NULL@ for default */
979 cups_array_t
*credentials
, /* I - Credentials */
980 const char *common_name
) /* I - Common name for credentials */
982 int ret
= -1; /* Return value */
983 OSStatus err
; /* Error info */
984 #ifdef HAVE_SECKEYCHAINOPEN
985 char filename
[1024]; /* Filename for keychain */
986 SecKeychainRef keychain
= NULL
;/* Keychain reference */
987 CFArrayRef list
; /* Keychain list */
988 #endif /* HAVE_SECKEYCHAINOPEN */
989 SecCertificateRef cert
= NULL
; /* Certificate */
990 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
993 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
997 if (!httpCredentialsAreValidForName(credentials
, common_name
))
999 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
1003 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
1005 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
1009 #ifdef HAVE_SECKEYCHAINOPEN
1010 keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
1018 #endif /* HAVE_SECKEYCHAINOPEN */
1020 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
1022 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
1026 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
1027 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
1029 #ifdef HAVE_SECKEYCHAINOPEN
1030 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1032 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
1035 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
1037 #endif /* HAVE_SECKEYCHAINOPEN */
1039 /* Note: SecItemAdd consumes "attrs"... */
1040 err
= SecItemAdd(attrs
, NULL
);
1041 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
1045 #ifdef HAVE_SECKEYCHAINOPEN
1047 CFRelease(keychain
);
1048 #endif /* HAVE_SECKEYCHAINOPEN */
1052 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
1059 * '_httpTLSInitialize()' - Initialize the TLS stack.
1063 _httpTLSInitialize(void)
1072 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1076 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
1078 size_t bytes
; /* Bytes that are available */
1081 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
1089 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1092 int /* O - Bytes read */
1093 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
1094 char *buf
, /* I - Buffer to store data */
1095 int len
) /* I - Length of buffer */
1097 int result
; /* Return value */
1098 OSStatus error
; /* Error info */
1099 size_t processed
; /* Number of bytes processed */
1102 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
1103 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
1108 result
= (int)processed
;
1111 case errSSLWouldBlock
:
1113 result
= (int)processed
;
1121 case errSSLClosedGraceful
:
1124 result
= (int)processed
;
1138 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1142 _httpTLSSetOptions(int options
) /* I - Options */
1144 tls_options
= options
;
1149 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1152 int /* O - 0 on success, -1 on failure */
1153 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
1155 char hostname
[256], /* Hostname */
1156 *hostptr
; /* Pointer into hostname */
1157 _cups_globals_t
*cg
= _cupsGlobals();
1158 /* Pointer to library globals */
1159 OSStatus error
; /* Error code */
1160 const char *message
= NULL
;/* Error message */
1161 cups_array_t
*credentials
; /* Credentials array */
1162 cups_array_t
*names
; /* CUPS distinguished names */
1163 CFArrayRef dn_array
; /* CF distinguished names array */
1164 CFIndex count
; /* Number of credentials */
1165 CFDataRef data
; /* Certificate data */
1166 int i
; /* Looping var */
1167 http_credential_t
*credential
; /* Credential data */
1170 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http
));
1172 if (tls_options
< 0)
1174 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1176 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1179 #ifdef HAVE_SECKEYCHAINOPEN
1180 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1182 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1183 http
->error
= errno
= EINVAL
;
1184 http
->status
= HTTP_STATUS_ERROR
;
1185 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1189 #endif /* HAVE_SECKEYCHAINOPEN */
1191 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1193 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1194 http
->error
= errno
= ENOMEM
;
1195 http
->status
= HTTP_STATUS_ERROR
;
1196 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1201 error
= SSLSetConnection(http
->tls
, http
);
1202 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1206 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1207 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1212 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1214 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error
));
1219 SSLProtocol minProtocol
;
1221 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1222 minProtocol
= kTLSProtocol11
;
1223 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1224 minProtocol
= kSSLProtocol3
;
1226 minProtocol
= kTLSProtocol1
;
1228 error
= SSLSetProtocolVersionMin(http
->tls
, minProtocol
);
1229 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol
, (int)error
));
1231 if (!error
&& (tls_options
& _HTTP_TLS_ONLY_TLS10
))
1233 error
= SSLSetProtocolVersionMax(http
->tls
, kTLSProtocol1
);
1234 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMax(kTLSProtocol1), error=%d", (int)error
));
1238 # if HAVE_SSLSETENABLEDCIPHERS
1241 SSLCipherSuite supported
[100]; /* Supported cipher suites */
1242 size_t num_supported
; /* Number of supported cipher suites */
1243 SSLCipherSuite enabled
[100]; /* Cipher suites to enable */
1244 size_t num_enabled
; /* Number of cipher suites to enable */
1246 num_supported
= sizeof(supported
) / sizeof(supported
[0]);
1247 error
= SSLGetSupportedCiphers(http
->tls
, supported
, &num_supported
);
1251 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported
));
1253 for (i
= 0, num_enabled
= 0; i
< (int)num_supported
&& num_enabled
< (sizeof(enabled
) / sizeof(enabled
[0])); i
++)
1255 switch (supported
[i
])
1257 /* Obviously insecure cipher suites that we never want to use */
1258 case SSL_NULL_WITH_NULL_NULL
:
1259 case SSL_RSA_WITH_NULL_MD5
:
1260 case SSL_RSA_WITH_NULL_SHA
:
1261 case SSL_RSA_EXPORT_WITH_RC4_40_MD5
:
1262 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
1263 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1264 case SSL_RSA_WITH_DES_CBC_SHA
:
1265 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1266 case SSL_DH_DSS_WITH_DES_CBC_SHA
:
1267 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1268 case SSL_DH_RSA_WITH_DES_CBC_SHA
:
1269 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1270 case SSL_DHE_DSS_WITH_DES_CBC_SHA
:
1271 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1272 case SSL_DHE_RSA_WITH_DES_CBC_SHA
:
1273 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
:
1274 case SSL_DH_anon_WITH_RC4_128_MD5
:
1275 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
:
1276 case SSL_DH_anon_WITH_DES_CBC_SHA
:
1277 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
:
1278 case SSL_FORTEZZA_DMS_WITH_NULL_SHA
:
1279 case TLS_DH_anon_WITH_AES_128_CBC_SHA
:
1280 case TLS_DH_anon_WITH_AES_256_CBC_SHA
:
1281 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
1282 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
1283 case TLS_ECDH_anon_WITH_NULL_SHA
:
1284 case TLS_ECDH_anon_WITH_RC4_128_SHA
:
1285 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
:
1286 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA
:
1287 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA
:
1288 case TLS_RSA_WITH_NULL_SHA256
:
1289 case TLS_DH_anon_WITH_AES_128_CBC_SHA256
:
1290 case TLS_DH_anon_WITH_AES_256_CBC_SHA256
:
1291 case TLS_PSK_WITH_NULL_SHA
:
1292 case TLS_DHE_PSK_WITH_NULL_SHA
:
1293 case TLS_RSA_PSK_WITH_NULL_SHA
:
1294 case TLS_DH_anon_WITH_AES_128_GCM_SHA256
:
1295 case TLS_DH_anon_WITH_AES_256_GCM_SHA384
:
1296 case TLS_PSK_WITH_NULL_SHA256
:
1297 case TLS_PSK_WITH_NULL_SHA384
:
1298 case TLS_DHE_PSK_WITH_NULL_SHA256
:
1299 case TLS_DHE_PSK_WITH_NULL_SHA384
:
1300 case TLS_RSA_PSK_WITH_NULL_SHA256
:
1301 case TLS_RSA_PSK_WITH_NULL_SHA384
:
1302 case SSL_RSA_WITH_DES_CBC_MD5
:
1303 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported
[i
]));
1306 /* RC4 cipher suites that should only be used as a last resort */
1307 case SSL_RSA_WITH_RC4_128_MD5
:
1308 case SSL_RSA_WITH_RC4_128_SHA
:
1309 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
1310 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
1311 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
1312 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
1313 case TLS_PSK_WITH_RC4_128_SHA
:
1314 case TLS_DHE_PSK_WITH_RC4_128_SHA
:
1315 case TLS_RSA_PSK_WITH_RC4_128_SHA
:
1316 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1317 enabled
[num_enabled
++] = supported
[i
];
1319 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported
[i
]));
1322 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1323 case TLS_DH_DSS_WITH_AES_128_CBC_SHA
:
1324 case TLS_DH_RSA_WITH_AES_128_CBC_SHA
:
1325 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA
:
1326 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA
:
1327 case TLS_DH_DSS_WITH_AES_256_CBC_SHA
:
1328 case TLS_DH_RSA_WITH_AES_256_CBC_SHA
:
1329 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA
:
1330 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA
:
1331 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
:
1332 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
:
1333 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
:
1334 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256
:
1335 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256
:
1336 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
:
1337 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
:
1338 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256
:
1339 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256
:
1340 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
:
1341 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
:
1342 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
:
1343 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA
:
1344 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA
:
1345 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
:
1346 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
:
1347 if (tls_options
& _HTTP_TLS_DENY_CBC
)
1349 DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported
[i
]));
1353 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1354 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1355 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256
:
1356 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384
:
1357 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1358 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1359 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256
:
1360 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384
:
1361 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
:
1362 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
:
1363 if (tls_options
& _HTTP_TLS_ALLOW_DH
)
1364 enabled
[num_enabled
++] = supported
[i
];
1366 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported
[i
]));
1369 case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
:
1370 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
:
1371 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
:
1372 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
:
1373 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
:
1374 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
:
1375 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
:
1376 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
:
1377 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
:
1378 case TLS_RSA_WITH_3DES_EDE_CBC_SHA
:
1379 case TLS_RSA_WITH_AES_128_CBC_SHA
:
1380 case TLS_RSA_WITH_AES_256_CBC_SHA
:
1381 if (tls_options
& _HTTP_TLS_DENY_CBC
)
1383 DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported
[i
]));
1387 /* Anything else we'll assume is "secure" */
1389 enabled
[num_enabled
++] = supported
[i
];
1394 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled
));
1395 error
= SSLSetEnabledCiphers(http
->tls
, enabled
, num_enabled
);
1398 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1400 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1403 * Client: set client-side credentials, if any...
1406 if (cg
->client_cert_cb
)
1408 error
= SSLSetSessionOption(http
->tls
,
1409 kSSLSessionOptionBreakOnCertRequested
, true);
1410 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1411 "error=%d", (int)error
));
1415 error
= http_cdsa_set_credentials(http
);
1416 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1423 * Server: find/create a certificate for TLS...
1426 if (http
->fields
[HTTP_FIELD_HOST
][0])
1429 * Use hostname for TLS upgrade...
1432 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1437 * Resolve hostname from connection address...
1440 http_addr_t addr
; /* Connection address */
1441 socklen_t addrlen
; /* Length of address */
1443 addrlen
= sizeof(addr
);
1444 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1446 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1449 else if (httpAddrLocalhost(&addr
))
1453 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1454 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1458 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1459 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1462 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1463 else if (tls_common_name
)
1464 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1466 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1468 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1470 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1472 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1473 http
->error
= errno
= EINVAL
;
1474 http
->status
= HTTP_STATUS_ERROR
;
1475 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1480 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1483 if (!http
->tls_credentials
)
1485 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1486 http
->error
= errno
= EINVAL
;
1487 http
->status
= HTTP_STATUS_ERROR
;
1488 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1493 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1495 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1498 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http
->tls_credentials
));
1501 * Let the server know which hostname/domain we are trying to connect to
1502 * in case it wants to serve up a certificate with a matching common name.
1505 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1508 * Client: get the hostname to use for TLS...
1511 if (httpAddrLocalhost(http
->hostaddr
))
1513 strlcpy(hostname
, "localhost", sizeof(hostname
));
1518 * Otherwise make sure the hostname we have does not end in a trailing dot.
1521 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1522 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1527 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1529 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1534 int done
= 0; /* Are we done yet? */
1536 while (!error
&& !done
)
1538 error
= SSLHandshake(http
->tls
);
1540 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1548 case errSSLWouldBlock
:
1549 error
= noErr
; /* Force a retry */
1550 usleep(1000); /* in 1 millisecond */
1553 case errSSLServerAuthCompleted
:
1555 if (cg
->server_cert_cb
)
1557 error
= httpCopyCredentials(http
, &credentials
);
1560 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1561 cg
->server_cert_data
);
1562 httpFreeCredentials(credentials
);
1565 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1566 "returned %d.", (int)error
));
1570 case errSSLClientCertRequested
:
1573 if (cg
->client_cert_cb
)
1576 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1579 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1581 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1583 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1585 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1587 credential
->datalen
= (size_t)CFDataGetLength(data
);
1588 if ((credential
->data
= malloc(credential
->datalen
)))
1590 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1591 credential
->datalen
);
1592 cupsArrayAdd(names
, credential
);
1600 CFRelease(dn_array
);
1605 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1606 cg
->client_cert_data
);
1608 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1609 "returned %d.", (int)error
));
1612 httpFreeCredentials(names
);
1616 case errSSLUnknownRootCert
:
1617 message
= _("Unable to establish a secure connection to host "
1618 "(untrusted certificate).");
1621 case errSSLNoRootCert
:
1622 message
= _("Unable to establish a secure connection to host "
1623 "(self-signed certificate).");
1626 case errSSLCertExpired
:
1627 message
= _("Unable to establish a secure connection to host "
1628 "(expired certificate).");
1631 case errSSLCertNotYetValid
:
1632 message
= _("Unable to establish a secure connection to host "
1633 "(certificate not yet valid).");
1636 case errSSLHostNameMismatch
:
1637 message
= _("Unable to establish a secure connection to host "
1638 "(host name mismatch).");
1641 case errSSLXCertChainInvalid
:
1642 message
= _("Unable to establish a secure connection to host "
1643 "(certificate chain invalid).");
1646 case errSSLConnectionRefused
:
1647 message
= _("Unable to establish a secure connection to host "
1648 "(peer dropped connection before responding).");
1659 http
->error
= error
;
1660 http
->status
= HTTP_STATUS_ERROR
;
1661 errno
= ECONNREFUSED
;
1663 CFRelease(http
->tls
);
1667 * If an error string wasn't set by the callbacks use a generic one...
1671 #ifdef HAVE_CSSMERRORSTRING
1672 message
= cssmErrorString(error
);
1674 message
= _("Unable to establish a secure connection to host.");
1675 #endif /* HAVE_CSSMERRORSTRING */
1677 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1687 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1691 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1693 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1696 CFRelease(http
->tls
);
1698 if (http
->tls_credentials
)
1699 CFRelease(http
->tls_credentials
);
1702 http
->tls_credentials
= NULL
;
1707 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1710 int /* O - Bytes written */
1711 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1712 const char *buf
, /* I - Buffer holding data */
1713 int len
) /* I - Length of buffer */
1715 ssize_t result
; /* Return value */
1716 OSStatus error
; /* Error info */
1717 size_t processed
; /* Number of bytes processed */
1720 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http
, (void *)buf
, len
));
1722 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1727 result
= (int)processed
;
1730 case errSSLWouldBlock
:
1733 result
= (int)processed
;
1742 case errSSLClosedGraceful
:
1746 result
= (int)processed
;
1756 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1758 return ((int)result
);
1763 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1766 static CFArrayRef
/* O - Array of certificates or NULL */
1767 http_cdsa_copy_server(
1768 const char *common_name
) /* I - Server's hostname */
1770 #ifdef HAVE_SECKEYCHAINOPEN
1771 OSStatus err
; /* Error info */
1772 SecIdentityRef identity
= NULL
;/* Identity */
1773 CFArrayRef certificates
= NULL
;
1774 /* Certificate array */
1775 SecPolicyRef policy
= NULL
; /* Policy ref */
1776 CFStringRef cfcommon_name
= NULL
;
1778 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1779 CFArrayRef list
= NULL
; /* Keychain list */
1780 SecKeychainRef syschain
= NULL
;/* System keychain */
1781 SecKeychainStatus status
= 0; /* Keychain status */
1784 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name
));
1786 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1788 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1792 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
1796 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1798 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
1802 _cupsMutexLock(&tls_mutex
);
1804 err
= SecKeychainGetStatus(tls_keychain
, &status
);
1806 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
) && tls_cups_keychain
)
1807 SecKeychainUnlock(tls_keychain
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, TRUE
);
1809 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1810 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1811 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1812 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1814 syschain
= http_cdsa_open_system_keychain();
1818 const void *values
[2] = { syschain
, tls_keychain
};
1820 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)values
, 2, &kCFTypeArrayCallBacks
);
1823 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1825 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1828 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1830 _cupsMutexUnlock(&tls_mutex
);
1834 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err
));
1838 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1840 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
1844 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1846 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
1853 CFRelease(syschain
);
1855 CFRelease(identity
);
1859 CFRelease(cfcommon_name
);
1863 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates
));
1865 return (certificates
);
1868 if (!tls_selfsigned
)
1871 return (CFArrayCreate(NULL
, (const void **)&tls_selfsigned
, 1, &kCFTypeArrayCallBacks
));
1872 #endif /* HAVE_SECKEYCHAINOPEN */
1877 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1880 static SecCertificateRef
/* O - Certificate */
1881 http_cdsa_create_credential(
1882 http_credential_t
*credential
) /* I - Credential */
1887 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1891 #ifdef HAVE_SECKEYCHAINOPEN
1893 * 'http_cdsa_default_path()' - Get the default keychain path.
1896 static const char * /* O - Keychain path */
1897 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1898 size_t bufsize
) /* I - Size of buffer */
1900 const char *home
= getenv("HOME"); /* HOME environment variable */
1904 * Determine the default keychain path. Note that the login and system
1905 * keychains are no longer accessible to user applications starting in macOS
1906 * 10.11.4 (!), so we need to create our own keychain just for CUPS.
1909 if (getuid() && home
)
1910 snprintf(buffer
, bufsize
, "%s/.cups/ssl.keychain", home
);
1912 strlcpy(buffer
, "/etc/cups/ssl.keychain", bufsize
);
1914 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1921 * 'http_cdsa_open_keychain()' - Open (or create) a keychain.
1924 static SecKeychainRef
/* O - Keychain or NULL */
1925 http_cdsa_open_keychain(
1926 const char *path
, /* I - Path to keychain */
1927 char *filename
, /* I - Keychain filename */
1928 size_t filesize
) /* I - Size of filename buffer */
1930 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
1931 OSStatus err
; /* Error code */
1932 Boolean interaction
; /* Interaction allowed? */
1933 SecKeychainStatus status
= 0; /* Keychain status */
1937 * Get the keychain filename...
1942 path
= http_cdsa_default_path(filename
, filesize
);
1943 tls_cups_keychain
= 1;
1947 strlcpy(filename
, path
, filesize
);
1948 tls_cups_keychain
= 0;
1952 * Save the interaction setting and disable while we open the keychain...
1955 SecKeychainGetUserInteractionAllowed(&interaction
);
1956 SecKeychainSetUserInteractionAllowed(FALSE
);
1958 if (access(path
, R_OK
) && tls_cups_keychain
)
1961 * Create a new keychain at the given path...
1964 err
= SecKeychainCreate(path
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, FALSE
, NULL
, &keychain
);
1969 * Open the existing keychain and unlock as needed...
1972 err
= SecKeychainOpen(path
, &keychain
);
1975 err
= SecKeychainGetStatus(keychain
, &status
);
1977 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
) && tls_cups_keychain
)
1978 err
= SecKeychainUnlock(keychain
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, TRUE
);
1982 * Restore interaction setting...
1985 SecKeychainSetUserInteractionAllowed(interaction
);
1988 * Release the keychain if we had any errors...
1993 /* TODO: Set cups last error string */
1994 DEBUG_printf(("4http_cdsa_open_keychain: Unable to open keychain (%d), returning NULL.", (int)err
));
1998 CFRelease(keychain
);
2004 * Return the keychain or NULL...
2012 * 'http_cdsa_open_system_keychain()' - Open the System keychain.
2015 static SecKeychainRef
2016 http_cdsa_open_system_keychain(void)
2018 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
2019 OSStatus err
; /* Error code */
2020 Boolean interaction
; /* Interaction allowed? */
2021 SecKeychainStatus status
= 0; /* Keychain status */
2025 * Save the interaction setting and disable while we open the keychain...
2028 SecKeychainGetUserInteractionAllowed(&interaction
);
2029 SecKeychainSetUserInteractionAllowed(TRUE
);
2031 err
= SecKeychainOpen("/Library/Keychains/System.keychain", &keychain
);
2034 err
= SecKeychainGetStatus(keychain
, &status
);
2036 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
))
2037 err
= errSecInteractionNotAllowed
;
2040 * Restore interaction setting...
2043 SecKeychainSetUserInteractionAllowed(interaction
);
2046 * Release the keychain if we had any errors...
2051 /* TODO: Set cups last error string */
2052 DEBUG_printf(("4http_cdsa_open_system_keychain: Unable to open keychain (%d), returning NULL.", (int)err
));
2056 CFRelease(keychain
);
2062 * Return the keychain or NULL...
2067 #endif /* HAVE_SECKEYCHAINOPEN */
2071 * 'http_cdsa_read()' - Read function for the CDSA library.
2074 static OSStatus
/* O - -1 on error, 0 on success */
2076 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2077 void *data
, /* I - Data buffer */
2078 size_t *dataLength
) /* IO - Number of bytes */
2080 OSStatus result
; /* Return value */
2081 ssize_t bytes
; /* Number of bytes read */
2082 http_t
*http
; /* HTTP connection */
2085 http
= (http_t
*)connection
;
2087 if (!http
->blocking
)
2090 * Make sure we have data before we read...
2093 while (!_httpWait(http
, http
->wait_value
, 0))
2095 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2098 http
->error
= ETIMEDOUT
;
2105 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2107 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2109 if ((size_t)bytes
== *dataLength
)
2115 *dataLength
= (size_t)bytes
;
2116 result
= errSSLWouldBlock
;
2123 result
= errSSLClosedGraceful
;
2124 else if (errno
== EAGAIN
)
2125 result
= errSSLWouldBlock
;
2127 result
= errSSLClosedAbort
;
2135 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
2138 static int /* O - Status of connection */
2139 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
2141 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2142 OSStatus error
= 0; /* Error code */
2143 http_tls_credentials_t credentials
= NULL
;
2144 /* TLS credentials */
2147 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http
));
2150 * Prefer connection specific credentials...
2153 if ((credentials
= http
->tls_credentials
) == NULL
)
2154 credentials
= cg
->tls_credentials
;
2158 error
= SSLSetCertificate(http
->tls
, credentials
);
2159 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
2163 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
2170 * 'http_cdsa_write()' - Write function for the CDSA library.
2173 static OSStatus
/* O - -1 on error, 0 on success */
2175 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2176 const void *data
, /* I - Data buffer */
2177 size_t *dataLength
) /* IO - Number of bytes */
2179 OSStatus result
; /* Return value */
2180 ssize_t bytes
; /* Number of bytes read */
2181 http_t
*http
; /* HTTP connection */
2184 http
= (http_t
*)connection
;
2188 bytes
= write(http
->fd
, data
, *dataLength
);
2190 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2192 if ((size_t)bytes
== *dataLength
)
2196 else if (bytes
>= 0)
2198 *dataLength
= (size_t)bytes
;
2199 result
= errSSLWouldBlock
;
2205 if (errno
== EAGAIN
)
2206 result
= errSSLWouldBlock
;
2208 result
= errSSLClosedAbort
;