2 * TLS support code for CUPS on macOS.
4 * Copyright © 2007-2018 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
10 /**** This file is included from tls.c ****/
13 * Include necessary headers...
18 extern char **environ
; /* @private@ */
22 * Constants, very secure stuff...
25 #define _CUPS_CDSA_PASSWORD "42" /* CUPS keychain password */
26 #define _CUPS_CDSA_PASSLEN 2 /* Length of keychain password */
33 static int tls_auto_create
= 0;
34 /* Auto-create self-signed certs? */
35 static char *tls_common_name
= NULL
;
36 /* Default common name */
37 #ifdef HAVE_SECKEYCHAINOPEN
38 static int tls_cups_keychain
= 0;
39 /* Opened the CUPS keychain? */
40 static SecKeychainRef tls_keychain
= NULL
;
41 /* Server cert keychain */
43 static SecIdentityRef tls_selfsigned
= NULL
;
44 /* Temporary self-signed cert */
45 #endif /* HAVE_SECKEYCHAINOPEN */
46 static char *tls_keypath
= NULL
;
47 /* Server cert keychain path */
48 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
49 /* Mutex for keychain/certs */
50 static int tls_options
= -1,/* Options for TLS connections */
51 tls_min_version
= _HTTP_TLS_1_0
,
52 tls_max_version
= _HTTP_TLS_MAX
;
59 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
60 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
61 #ifdef HAVE_SECKEYCHAINOPEN
62 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
63 static SecKeychainRef
http_cdsa_open_keychain(const char *path
, char *filename
, size_t filesize
);
64 static SecKeychainRef
http_cdsa_open_system_keychain(void);
65 #endif /* HAVE_SECKEYCHAINOPEN */
66 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
67 static int http_cdsa_set_credentials(http_t
*http
);
68 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
72 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
74 * @since CUPS 2.0/OS 10.10@
77 int /* O - 1 on success, 0 on failure */
78 cupsMakeServerCredentials(
79 const char *path
, /* I - Keychain path or @code NULL@ for default */
80 const char *common_name
, /* I - Common name */
81 int num_alt_names
, /* I - Number of subject alternate names */
82 const char **alt_names
, /* I - Subject Alternate Names */
83 time_t expiration_date
) /* I - Expiration date */
85 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
86 int status
= 0; /* Return status */
87 OSStatus err
; /* Error code (if any) */
88 CFStringRef cfcommon_name
= NULL
;
89 /* CF string for server name */
90 SecIdentityRef ident
= NULL
; /* Identity */
91 SecKeyRef publicKey
= NULL
,
95 SecCertificateRef cert
= NULL
; /* Self-signed certificate */
96 CFMutableDictionaryRef keyParams
= NULL
;
97 /* Key generation parameters */
100 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
));
105 (void)expiration_date
;
109 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
115 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
119 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
122 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
127 * Create a public/private key pair...
130 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
133 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
137 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
138 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
139 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, cfcommon_name
);
141 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
144 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err
));
149 * Create a self-signed certificate using the public/private key pair...
152 CFIndex usageInt
= kSecKeyUsageAll
;
153 CFNumberRef usage
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &usageInt
);
155 CFNumberRef len
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &lenInt
);
156 CFTypeRef certKeys
[] = { kSecCSRBasicContraintsPathLen
, kSecSubjectAltName
, kSecCertificateKeyUsage
};
157 CFTypeRef certValues
[] = { len
, cfcommon_name
, usage
};
158 CFDictionaryRef certParams
= CFDictionaryCreate(kCFAllocatorDefault
, certKeys
, certValues
, sizeof(certKeys
) / sizeof(certKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
162 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
163 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
164 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
165 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
166 const void *ca_dn_array
[2];
168 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
169 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
171 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
173 cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
176 CFRelease(certParams
);
180 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
184 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
188 _cupsMutexLock(&tls_mutex
);
193 tls_selfsigned
= ident
;
195 _cupsMutexLock(&tls_mutex
);
197 # if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point */
198 CFTypeRef itemKeys
[] = { kSecClass
, kSecAttrLabel
, kSecValueRef
};
199 CFTypeRef itemValues
[] = { kSecClassIdentity
, cfcommon_name
, ident
};
200 CFDictionaryRef itemAttrs
= CFDictionaryCreate(kCFAllocatorDefault
, itemKeys
, itemValues
, sizeof(itemKeys
) / sizeof(itemKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
202 err
= SecItemAdd(itemAttrs
, NULL
);
203 /* SecItemAdd consumes itemAttrs... */
209 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err
));
217 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
220 * Cleanup and return...
226 CFRelease(cfcommon_name
);
229 CFRelease(keyParams
);
235 CFRelease(publicKey
);
238 CFRelease(privateKey
);
240 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status
));
244 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
245 int pid
, /* Process ID of command */
246 status
, /* Status of command */
248 char command
[1024], /* Command */
249 *argv
[5], /* Command-line arguments */
250 *envp
[1000], /* Environment variables */
251 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
252 keychain
[1024], /* Keychain argument */
253 infofile
[1024], /* Type-in information for cert */
254 filename
[1024]; /* Default keychain path */
255 cups_file_t
*fp
; /* Seed/info file */
258 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
));
264 path
= http_cdsa_default_path(filename
, sizeof(filename
));
267 * Run the "certtool" command to generate a self-signed certificate...
270 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
274 * Create a file with the certificate information fields...
276 * Note: This assumes that the default questions are asked by the certtool
280 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
284 "CUPS Self-Signed Certificate\n"
285 /* Enter key and certificate label */
286 "r\n" /* Generate RSA key pair */
287 "2048\n" /* 2048 bit encryption key */
288 "y\n" /* OK (y = yes) */
289 "b\n" /* Usage (b=signing/encryption) */
290 "2\n" /* Sign with SHA256 */
291 "y\n" /* OK (y = yes) */
292 "%s\n" /* Common name */
293 "\n" /* Country (default) */
294 "\n" /* Organization (default) */
295 "\n" /* Organizational unit (default) */
296 "\n" /* State/Province (default) */
297 "\n" /* Email address */
298 "y\n", /* OK (y = yes) */
302 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
304 argv
[0] = "certtool";
309 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
311 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
312 envp
[i
+ 1] = environ
[i
];
315 posix_spawn_file_actions_t actions
; /* File actions */
317 posix_spawn_file_actions_init(&actions
);
318 posix_spawn_file_actions_addclose(&actions
, 0);
319 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
320 posix_spawn_file_actions_addclose(&actions
, 1);
321 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
322 posix_spawn_file_actions_addclose(&actions
, 2);
323 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
325 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
331 posix_spawn_file_actions_destroy(&actions
);
335 while (waitpid(pid
, &status
, 0) < 0)
343 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
348 * 'cupsSetServerCredentials()' - Set the default server credentials.
350 * Note: The server credentials are used by all threads in the running process.
351 * This function is threadsafe.
353 * @since CUPS 2.0/macOS 10.10@
356 int /* O - 1 on success, 0 on failure */
357 cupsSetServerCredentials(
358 const char *path
, /* I - Keychain path or @code NULL@ for default */
359 const char *common_name
, /* I - Default common name for server */
360 int auto_create
) /* I - 1 = automatically create self-signed certificates */
362 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
364 #ifdef HAVE_SECKEYCHAINOPEN
365 char filename
[1024]; /* Keychain filename */
366 SecKeychainRef keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
370 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain.");
374 _cupsMutexLock(&tls_mutex
);
377 * Close any keychain that is currently open...
381 CFRelease(tls_keychain
);
384 _cupsStrFree(tls_keypath
);
387 _cupsStrFree(tls_common_name
);
390 * Save the new keychain...
393 tls_keychain
= keychain
;
394 tls_keypath
= _cupsStrAlloc(filename
);
395 tls_auto_create
= auto_create
;
396 tls_common_name
= _cupsStrAlloc(common_name
);
398 _cupsMutexUnlock(&tls_mutex
);
400 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
406 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
410 tls_auto_create
= auto_create
;
411 tls_common_name
= _cupsStrAlloc(common_name
);
414 #endif /* HAVE_SECKEYCHAINOPEN */
419 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
420 * an encrypted connection.
422 * @since CUPS 1.5/macOS 10.7@
425 int /* O - Status of call (0 = success) */
427 http_t
*http
, /* I - Connection to server */
428 cups_array_t
**credentials
) /* O - Array of credentials */
430 OSStatus error
; /* Error code */
431 SecTrustRef peerTrust
; /* Peer trust reference */
432 CFIndex count
; /* Number of credentials */
433 SecCertificateRef secCert
; /* Certificate reference */
434 CFDataRef data
; /* Certificate data */
435 int i
; /* Looping var */
438 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http
, (void *)credentials
));
443 if (!http
|| !http
->tls
|| !credentials
)
446 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
448 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
450 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
452 count
= SecTrustGetCertificateCount(peerTrust
);
454 for (i
= 0; i
< count
; i
++)
456 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
459 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
462 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
464 strlcpy(name
, "unknown", sizeof(name
));
466 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
469 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
471 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
473 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
479 CFRelease(peerTrust
);
487 * '_httpCreateCredentials()' - Create credentials in the internal format.
490 http_tls_credentials_t
/* O - Internal credentials */
491 _httpCreateCredentials(
492 cups_array_t
*credentials
) /* I - Array of credentials */
494 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
495 SecCertificateRef secCert
; /* Certificate reference */
496 http_credential_t
*credential
; /* Credential data */
502 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
503 cupsArrayCount(credentials
),
504 &kCFTypeArrayCallBacks
)) == NULL
)
507 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
509 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
511 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
513 CFArrayAppendValue(peerCerts
, secCert
);
523 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
525 * @since CUPS 2.0/macOS 10.10@
528 int /* O - 1 if valid, 0 otherwise */
529 httpCredentialsAreValidForName(
530 cups_array_t
*credentials
, /* I - Credentials */
531 const char *common_name
) /* I - Name to check */
533 SecCertificateRef secCert
; /* Certificate reference */
534 CFStringRef cfcert_name
= NULL
;
535 /* Certificate's common name (CF string) */
536 char cert_name
[256]; /* Certificate's common name (C string) */
537 int valid
= 1; /* Valid name? */
540 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
544 * Compare the common names...
547 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
550 * Can't get common name, cannot be valid...
555 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
556 _cups_strcasecmp(common_name
, cert_name
))
559 * Not an exact match for the common name, check for wildcard certs...
562 const char *domain
= strchr(common_name
, '.');
563 /* Domain in common name */
565 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
568 * Not a wildcard match.
571 /* TODO: Check subject alternate names */
577 CFRelease(cfcert_name
);
586 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
588 * @since CUPS 2.0/macOS 10.10@
591 http_trust_t
/* O - Level of trust */
592 httpCredentialsGetTrust(
593 cups_array_t
*credentials
, /* I - Credentials */
594 const char *common_name
) /* I - Common name for trust lookup */
596 SecCertificateRef secCert
; /* Certificate reference */
597 http_trust_t trust
= HTTP_TRUST_OK
;
599 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
600 _cups_globals_t
*cg
= _cupsGlobals();
601 /* Per-thread globals */
606 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No common name specified."), 1);
607 return (HTTP_TRUST_UNKNOWN
);
610 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
612 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create credentials from array."), 1);
613 return (HTTP_TRUST_UNKNOWN
);
616 if (cg
->any_root
< 0)
620 * Look this common name up in the default keychains...
623 httpLoadCredentials(NULL
, &tcreds
, common_name
);
627 char credentials_str
[1024], /* String for incoming credentials */
628 tcreds_str
[1024]; /* String for saved credentials */
630 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
631 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
633 if (strcmp(credentials_str
, tcreds_str
))
636 * Credentials don't match, let's look at the expiration date of the new
637 * credentials and allow if the new ones have a later expiration...
640 if (!cg
->trust_first
)
643 * Do not trust certificates on first use...
646 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
648 trust
= HTTP_TRUST_INVALID
;
650 else if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
))
653 * The new credentials are not newly issued...
656 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are older than stored credentials."), 1);
658 trust
= HTTP_TRUST_INVALID
;
660 else if (!httpCredentialsAreValidForName(credentials
, common_name
))
663 * The common name does not match the issued certificate...
666 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are not valid for name."), 1);
668 trust
= HTTP_TRUST_INVALID
;
670 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
673 * Save the renewed credentials...
676 trust
= HTTP_TRUST_RENEWED
;
678 httpSaveCredentials(NULL
, credentials
, common_name
);
682 httpFreeCredentials(tcreds
);
684 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
686 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No stored credentials, not valid for name."), 1);
687 trust
= HTTP_TRUST_INVALID
;
689 else if (!cg
->trust_first
)
692 * See if we have a site CA certificate we can compare...
695 if (!httpLoadCredentials(NULL
, &tcreds
, "site"))
697 if (cupsArrayCount(credentials
) != (cupsArrayCount(tcreds
) + 1))
700 * Certificate isn't directly generated from the CA cert...
703 trust
= HTTP_TRUST_INVALID
;
708 * Do a tail comparison of the two certificates...
711 http_credential_t
*a
, *b
; /* Certificates */
713 for (a
= (http_credential_t
*)cupsArrayFirst(tcreds
), b
= (http_credential_t
*)cupsArrayIndex(credentials
, 1);
715 a
= (http_credential_t
*)cupsArrayNext(tcreds
), b
= (http_credential_t
*)cupsArrayNext(credentials
))
716 if (a
->datalen
!= b
->datalen
|| memcmp(a
->data
, b
->data
, a
->datalen
))
720 trust
= HTTP_TRUST_INVALID
;
723 if (trust
!= HTTP_TRUST_OK
)
724 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials do not validate against site CA certificate."), 1);
728 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
729 trust
= HTTP_TRUST_INVALID
;
733 if (trust
== HTTP_TRUST_OK
&& !cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
735 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials have expired."), 1);
736 trust
= HTTP_TRUST_EXPIRED
;
739 if (trust
== HTTP_TRUST_OK
&& !cg
->any_root
&& cupsArrayCount(credentials
) == 1)
741 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Self-signed credentials are blocked."), 1);
742 trust
= HTTP_TRUST_INVALID
;
752 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
754 * @since CUPS 2.0/macOS 10.10@
757 time_t /* O - Expiration date of credentials */
758 httpCredentialsGetExpiration(
759 cups_array_t
*credentials
) /* I - Credentials */
761 SecCertificateRef secCert
; /* Certificate reference */
762 time_t expiration
; /* Expiration date */
765 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
768 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
777 * 'httpCredentialsString()' - Return a string representing the credentials.
779 * @since CUPS 2.0/macOS 10.10@
782 size_t /* O - Total size of credentials string */
783 httpCredentialsString(
784 cups_array_t
*credentials
, /* I - Credentials */
785 char *buffer
, /* I - Buffer or @code NULL@ */
786 size_t bufsize
) /* I - Size of buffer */
788 http_credential_t
*first
; /* First certificate */
789 SecCertificateRef secCert
; /* Certificate reference */
792 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", (void *)credentials
, (void *)buffer
, CUPS_LLCAST bufsize
));
797 if (buffer
&& bufsize
> 0)
800 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
801 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
803 CFStringRef cf_name
; /* CF common name string */
804 char name
[256]; /* Common name associated with cert */
805 time_t expiration
; /* Expiration date of cert */
806 unsigned char md5_digest
[16]; /* MD5 result */
808 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
810 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
814 strlcpy(name
, "unknown", sizeof(name
));
816 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
818 cupsHashData("md5", first
->data
, first
->datalen
, md5_digest
, sizeof(md5_digest
));
820 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]);
825 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
827 return (strlen(buffer
));
832 * '_httpFreeCredentials()' - Free internal credentials.
836 _httpFreeCredentials(
837 http_tls_credentials_t credentials
) /* I - Internal credentials */
842 CFRelease(credentials
);
847 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
849 * @since CUPS 2.0/OS 10.10@
852 int /* O - 0 on success, -1 on error */
854 const char *path
, /* I - Keychain path or @code NULL@ for default */
855 cups_array_t
**credentials
, /* IO - Credentials */
856 const char *common_name
) /* I - Common name for credentials */
858 OSStatus err
; /* Error info */
859 #ifdef HAVE_SECKEYCHAINOPEN
860 char filename
[1024]; /* Filename for keychain */
861 SecKeychainRef keychain
= NULL
,/* Keychain reference */
862 syschain
= NULL
;/* System keychain */
863 CFArrayRef list
; /* Keychain list */
864 #endif /* HAVE_SECKEYCHAINOPEN */
865 SecCertificateRef cert
= NULL
; /* Certificate */
866 CFDataRef data
; /* Certificate data */
867 SecPolicyRef policy
= NULL
; /* Policy ref */
868 CFStringRef cfcommon_name
= NULL
;
870 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
873 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
880 #ifdef HAVE_SECKEYCHAINOPEN
881 keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
886 syschain
= http_cdsa_open_system_keychain();
891 #endif /* HAVE_SECKEYCHAINOPEN */
893 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
895 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
898 CFRelease(cfcommon_name
);
903 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
906 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
907 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
908 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
909 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
911 #ifdef HAVE_SECKEYCHAINOPEN
914 const void *values
[2] = { syschain
, keychain
};
916 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)values
, 2, &kCFTypeArrayCallBacks
);
919 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
920 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
922 #endif /* HAVE_SECKEYCHAINOPEN */
924 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
929 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
932 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
934 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
936 *credentials
= cupsArrayNew(NULL
, NULL
);
937 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
943 #ifdef HAVE_SECKEYCHAINOPEN
949 #endif /* HAVE_SECKEYCHAINOPEN */
957 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
959 return (*credentials
? 0 : -1);
964 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
966 * @since CUPS 2.0/OS 10.10@
969 int /* O - -1 on error, 0 on success */
971 const char *path
, /* I - Keychain path or @code NULL@ for default */
972 cups_array_t
*credentials
, /* I - Credentials */
973 const char *common_name
) /* I - Common name for credentials */
975 int ret
= -1; /* Return value */
976 OSStatus err
; /* Error info */
977 #ifdef HAVE_SECKEYCHAINOPEN
978 char filename
[1024]; /* Filename for keychain */
979 SecKeychainRef keychain
= NULL
;/* Keychain reference */
980 CFArrayRef list
; /* Keychain list */
981 #endif /* HAVE_SECKEYCHAINOPEN */
982 SecCertificateRef cert
= NULL
; /* Certificate */
983 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
986 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
990 if (!httpCredentialsAreValidForName(credentials
, common_name
))
992 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
996 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
998 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
1002 #ifdef HAVE_SECKEYCHAINOPEN
1003 keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
1011 #endif /* HAVE_SECKEYCHAINOPEN */
1013 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
1015 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
1019 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
1020 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
1022 #ifdef HAVE_SECKEYCHAINOPEN
1023 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1025 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
1028 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
1030 #endif /* HAVE_SECKEYCHAINOPEN */
1032 /* Note: SecItemAdd consumes "attrs"... */
1033 err
= SecItemAdd(attrs
, NULL
);
1034 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
1038 #ifdef HAVE_SECKEYCHAINOPEN
1040 CFRelease(keychain
);
1041 #endif /* HAVE_SECKEYCHAINOPEN */
1045 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
1052 * '_httpTLSInitialize()' - Initialize the TLS stack.
1056 _httpTLSInitialize(void)
1065 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1069 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
1071 size_t bytes
; /* Bytes that are available */
1074 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
1082 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1085 int /* O - Bytes read */
1086 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
1087 char *buf
, /* I - Buffer to store data */
1088 int len
) /* I - Length of buffer */
1090 int result
; /* Return value */
1091 OSStatus error
; /* Error info */
1092 size_t processed
; /* Number of bytes processed */
1095 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
1096 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
1101 result
= (int)processed
;
1104 case errSSLWouldBlock
:
1106 result
= (int)processed
;
1114 case errSSLClosedGraceful
:
1117 result
= (int)processed
;
1131 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1135 _httpTLSSetOptions(int options
, /* I - Options */
1136 int min_version
, /* I - Minimum TLS version */
1137 int max_version
) /* I - Maximum TLS version */
1139 if (!(options
& _HTTP_TLS_SET_DEFAULT
) || tls_options
< 0)
1141 tls_options
= options
;
1142 tls_min_version
= min_version
;
1143 tls_max_version
= max_version
;
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_min_version=%d, tls_max_version=%d", tls_options
, tls_min_version
, tls_max_version
));
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 static const SSLProtocol protocols
[] = /* Min/max protocol versions */
1225 kTLSProtocol12
, /* TODO: update to 1.3 when 1.3 is supported */
1226 kTLSProtocol12
/* TODO: update to 1.3 when 1.3 is supported */
1229 error
= SSLSetProtocolVersionMin(http
->tls
, protocols
[tls_min_version
]);
1230 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", protocols
[tls_min_version
], (int)error
));
1234 error
= SSLSetProtocolVersionMax(http
->tls
, protocols
[tls_max_version
]);
1235 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMax(%d), error=%d", protocols
[tls_max_version
], (int)error
));
1239 # if HAVE_SSLSETENABLEDCIPHERS
1242 SSLCipherSuite supported
[100]; /* Supported cipher suites */
1243 size_t num_supported
; /* Number of supported cipher suites */
1244 SSLCipherSuite enabled
[100]; /* Cipher suites to enable */
1245 size_t num_enabled
; /* Number of cipher suites to enable */
1247 num_supported
= sizeof(supported
) / sizeof(supported
[0]);
1248 error
= SSLGetSupportedCiphers(http
->tls
, supported
, &num_supported
);
1252 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported
));
1254 for (i
= 0, num_enabled
= 0; i
< (int)num_supported
&& num_enabled
< (sizeof(enabled
) / sizeof(enabled
[0])); i
++)
1256 switch (supported
[i
])
1258 /* Obviously insecure cipher suites that we never want to use */
1259 case SSL_NULL_WITH_NULL_NULL
:
1260 case SSL_RSA_WITH_NULL_MD5
:
1261 case SSL_RSA_WITH_NULL_SHA
:
1262 case SSL_RSA_EXPORT_WITH_RC4_40_MD5
:
1263 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
1264 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1265 case SSL_RSA_WITH_DES_CBC_SHA
:
1266 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1267 case SSL_DH_DSS_WITH_DES_CBC_SHA
:
1268 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1269 case SSL_DH_RSA_WITH_DES_CBC_SHA
:
1270 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1271 case SSL_DHE_DSS_WITH_DES_CBC_SHA
:
1272 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1273 case SSL_DHE_RSA_WITH_DES_CBC_SHA
:
1274 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
:
1275 case SSL_DH_anon_WITH_RC4_128_MD5
:
1276 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
:
1277 case SSL_DH_anon_WITH_DES_CBC_SHA
:
1278 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
:
1279 case SSL_FORTEZZA_DMS_WITH_NULL_SHA
:
1280 case TLS_DH_anon_WITH_AES_128_CBC_SHA
:
1281 case TLS_DH_anon_WITH_AES_256_CBC_SHA
:
1282 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
1283 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
1284 case TLS_ECDH_anon_WITH_NULL_SHA
:
1285 case TLS_ECDH_anon_WITH_RC4_128_SHA
:
1286 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
:
1287 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA
:
1288 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA
:
1289 case TLS_RSA_WITH_NULL_SHA256
:
1290 case TLS_DH_anon_WITH_AES_128_CBC_SHA256
:
1291 case TLS_DH_anon_WITH_AES_256_CBC_SHA256
:
1292 case TLS_PSK_WITH_NULL_SHA
:
1293 case TLS_DHE_PSK_WITH_NULL_SHA
:
1294 case TLS_RSA_PSK_WITH_NULL_SHA
:
1295 case TLS_DH_anon_WITH_AES_128_GCM_SHA256
:
1296 case TLS_DH_anon_WITH_AES_256_GCM_SHA384
:
1297 case TLS_PSK_WITH_NULL_SHA256
:
1298 case TLS_PSK_WITH_NULL_SHA384
:
1299 case TLS_DHE_PSK_WITH_NULL_SHA256
:
1300 case TLS_DHE_PSK_WITH_NULL_SHA384
:
1301 case TLS_RSA_PSK_WITH_NULL_SHA256
:
1302 case TLS_RSA_PSK_WITH_NULL_SHA384
:
1303 case SSL_RSA_WITH_DES_CBC_MD5
:
1304 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported
[i
]));
1307 /* RC4 cipher suites that should only be used as a last resort */
1308 case SSL_RSA_WITH_RC4_128_MD5
:
1309 case SSL_RSA_WITH_RC4_128_SHA
:
1310 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
1311 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
1312 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
1313 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
1314 case TLS_PSK_WITH_RC4_128_SHA
:
1315 case TLS_DHE_PSK_WITH_RC4_128_SHA
:
1316 case TLS_RSA_PSK_WITH_RC4_128_SHA
:
1317 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1318 enabled
[num_enabled
++] = supported
[i
];
1320 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported
[i
]));
1323 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1324 case TLS_DH_DSS_WITH_AES_128_CBC_SHA
:
1325 case TLS_DH_RSA_WITH_AES_128_CBC_SHA
:
1326 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA
:
1327 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA
:
1328 case TLS_DH_DSS_WITH_AES_256_CBC_SHA
:
1329 case TLS_DH_RSA_WITH_AES_256_CBC_SHA
:
1330 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA
:
1331 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA
:
1332 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
:
1333 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
:
1334 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
:
1335 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256
:
1336 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256
:
1337 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
:
1338 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
:
1339 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256
:
1340 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256
:
1341 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
:
1342 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
:
1343 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
:
1344 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA
:
1345 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA
:
1346 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
:
1347 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
:
1348 if (tls_options
& _HTTP_TLS_DENY_CBC
)
1350 DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported
[i
]));
1354 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1355 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1356 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256
:
1357 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384
:
1358 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1359 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1360 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256
:
1361 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384
:
1362 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
:
1363 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
:
1364 if (tls_options
& _HTTP_TLS_ALLOW_DH
)
1365 enabled
[num_enabled
++] = supported
[i
];
1367 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported
[i
]));
1370 case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
:
1371 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
:
1372 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
:
1373 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
:
1374 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
:
1375 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
:
1376 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
:
1377 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
:
1378 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
:
1379 case TLS_RSA_WITH_3DES_EDE_CBC_SHA
:
1380 case TLS_RSA_WITH_AES_128_CBC_SHA
:
1381 case TLS_RSA_WITH_AES_256_CBC_SHA
:
1382 if (tls_options
& _HTTP_TLS_DENY_CBC
)
1384 DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported
[i
]));
1388 /* Anything else we'll assume is "secure" */
1390 enabled
[num_enabled
++] = supported
[i
];
1395 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled
));
1396 error
= SSLSetEnabledCiphers(http
->tls
, enabled
, num_enabled
);
1399 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1401 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1404 * Client: set client-side credentials, if any...
1407 if (cg
->client_cert_cb
)
1409 error
= SSLSetSessionOption(http
->tls
,
1410 kSSLSessionOptionBreakOnCertRequested
, true);
1411 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1412 "error=%d", (int)error
));
1416 error
= http_cdsa_set_credentials(http
);
1417 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1424 * Server: find/create a certificate for TLS...
1427 if (http
->fields
[HTTP_FIELD_HOST
])
1430 * Use hostname for TLS upgrade...
1433 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1438 * Resolve hostname from connection address...
1441 http_addr_t addr
; /* Connection address */
1442 socklen_t addrlen
; /* Length of address */
1444 addrlen
= sizeof(addr
);
1445 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1447 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1450 else if (httpAddrLocalhost(&addr
))
1454 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1455 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1459 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1460 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1463 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1464 else if (tls_common_name
)
1465 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1467 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1469 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1471 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1473 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1474 http
->error
= errno
= EINVAL
;
1475 http
->status
= HTTP_STATUS_ERROR
;
1476 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1481 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1484 if (!http
->tls_credentials
)
1486 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1487 http
->error
= errno
= EINVAL
;
1488 http
->status
= HTTP_STATUS_ERROR
;
1489 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1494 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1496 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1499 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http
->tls_credentials
));
1502 * Let the server know which hostname/domain we are trying to connect to
1503 * in case it wants to serve up a certificate with a matching common name.
1506 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1509 * Client: get the hostname to use for TLS...
1512 if (httpAddrLocalhost(http
->hostaddr
))
1514 strlcpy(hostname
, "localhost", sizeof(hostname
));
1519 * Otherwise make sure the hostname we have does not end in a trailing dot.
1522 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1523 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1528 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1530 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1535 int done
= 0; /* Are we done yet? */
1536 double old_timeout
; /* Old timeout value */
1537 http_timeout_cb_t old_cb
; /* Old timeout callback */
1538 void *old_data
; /* Old timeout data */
1541 * Enforce a minimum timeout of 10 seconds for the TLS handshake...
1544 old_timeout
= http
->timeout_value
;
1545 old_cb
= http
->timeout_cb
;
1546 old_data
= http
->timeout_data
;
1548 if (!old_cb
|| old_timeout
< 10.0)
1550 DEBUG_puts("4_httpTLSStart: Setting timeout to 10 seconds.");
1551 httpSetTimeout(http
, 10.0, NULL
, NULL
);
1555 * Do the TLS handshake...
1558 while (!error
&& !done
)
1560 error
= SSLHandshake(http
->tls
);
1562 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1570 case errSSLWouldBlock
:
1571 error
= noErr
; /* Force a retry */
1572 usleep(1000); /* in 1 millisecond */
1575 case errSSLServerAuthCompleted
:
1577 if (cg
->server_cert_cb
)
1579 error
= httpCopyCredentials(http
, &credentials
);
1582 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1583 cg
->server_cert_data
);
1584 httpFreeCredentials(credentials
);
1587 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1588 "returned %d.", (int)error
));
1592 case errSSLClientCertRequested
:
1595 if (cg
->client_cert_cb
)
1598 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1601 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1603 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1605 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1607 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1609 credential
->datalen
= (size_t)CFDataGetLength(data
);
1610 if ((credential
->data
= malloc(credential
->datalen
)))
1612 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1613 credential
->datalen
);
1614 cupsArrayAdd(names
, credential
);
1622 CFRelease(dn_array
);
1627 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1628 cg
->client_cert_data
);
1630 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1631 "returned %d.", (int)error
));
1634 httpFreeCredentials(names
);
1638 case errSSLUnknownRootCert
:
1639 message
= _("Unable to establish a secure connection to host "
1640 "(untrusted certificate).");
1643 case errSSLNoRootCert
:
1644 message
= _("Unable to establish a secure connection to host "
1645 "(self-signed certificate).");
1648 case errSSLCertExpired
:
1649 message
= _("Unable to establish a secure connection to host "
1650 "(expired certificate).");
1653 case errSSLCertNotYetValid
:
1654 message
= _("Unable to establish a secure connection to host "
1655 "(certificate not yet valid).");
1658 case errSSLHostNameMismatch
:
1659 message
= _("Unable to establish a secure connection to host "
1660 "(host name mismatch).");
1663 case errSSLXCertChainInvalid
:
1664 message
= _("Unable to establish a secure connection to host "
1665 "(certificate chain invalid).");
1668 case errSSLConnectionRefused
:
1669 message
= _("Unable to establish a secure connection to host "
1670 "(peer dropped connection before responding).");
1679 * Restore the previous timeout settings...
1682 httpSetTimeout(http
, old_timeout
, old_cb
, old_data
);
1687 http
->error
= error
;
1688 http
->status
= HTTP_STATUS_ERROR
;
1689 errno
= ECONNREFUSED
;
1691 CFRelease(http
->tls
);
1695 * If an error string wasn't set by the callbacks use a generic one...
1699 #ifdef HAVE_CSSMERRORSTRING
1700 message
= cssmErrorString(error
);
1702 message
= _("Unable to establish a secure connection to host.");
1703 #endif /* HAVE_CSSMERRORSTRING */
1705 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1715 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1719 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1721 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1724 CFRelease(http
->tls
);
1726 if (http
->tls_credentials
)
1727 CFRelease(http
->tls_credentials
);
1730 http
->tls_credentials
= NULL
;
1735 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1738 int /* O - Bytes written */
1739 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1740 const char *buf
, /* I - Buffer holding data */
1741 int len
) /* I - Length of buffer */
1743 ssize_t result
; /* Return value */
1744 OSStatus error
; /* Error info */
1745 size_t processed
; /* Number of bytes processed */
1748 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http
, (void *)buf
, len
));
1750 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1755 result
= (int)processed
;
1758 case errSSLWouldBlock
:
1761 result
= (int)processed
;
1770 case errSSLClosedGraceful
:
1774 result
= (int)processed
;
1784 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1786 return ((int)result
);
1791 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1794 static CFArrayRef
/* O - Array of certificates or NULL */
1795 http_cdsa_copy_server(
1796 const char *common_name
) /* I - Server's hostname */
1798 #ifdef HAVE_SECKEYCHAINOPEN
1799 OSStatus err
; /* Error info */
1800 SecIdentityRef identity
= NULL
;/* Identity */
1801 CFArrayRef certificates
= NULL
;
1802 /* Certificate array */
1803 SecPolicyRef policy
= NULL
; /* Policy ref */
1804 CFStringRef cfcommon_name
= NULL
;
1806 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1807 CFArrayRef list
= NULL
; /* Keychain list */
1808 SecKeychainRef syschain
= NULL
;/* System keychain */
1809 SecKeychainStatus status
= 0; /* Keychain status */
1812 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name
));
1814 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1816 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1820 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
1824 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1826 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
1830 _cupsMutexLock(&tls_mutex
);
1832 err
= SecKeychainGetStatus(tls_keychain
, &status
);
1834 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
) && tls_cups_keychain
)
1835 SecKeychainUnlock(tls_keychain
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, TRUE
);
1837 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1838 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1839 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1840 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1842 syschain
= http_cdsa_open_system_keychain();
1846 const void *values
[2] = { syschain
, tls_keychain
};
1848 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)values
, 2, &kCFTypeArrayCallBacks
);
1851 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1853 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1856 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1858 _cupsMutexUnlock(&tls_mutex
);
1862 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err
));
1866 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1868 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
1872 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1874 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
1881 CFRelease(syschain
);
1883 CFRelease(identity
);
1887 CFRelease(cfcommon_name
);
1891 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates
));
1893 return (certificates
);
1896 if (!tls_selfsigned
)
1899 return (CFArrayCreate(NULL
, (const void **)&tls_selfsigned
, 1, &kCFTypeArrayCallBacks
));
1900 #endif /* HAVE_SECKEYCHAINOPEN */
1905 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1908 static SecCertificateRef
/* O - Certificate */
1909 http_cdsa_create_credential(
1910 http_credential_t
*credential
) /* I - Credential */
1915 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1919 #ifdef HAVE_SECKEYCHAINOPEN
1921 * 'http_cdsa_default_path()' - Get the default keychain path.
1924 static const char * /* O - Keychain path */
1925 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1926 size_t bufsize
) /* I - Size of buffer */
1928 const char *home
= getenv("HOME"); /* HOME environment variable */
1932 * Determine the default keychain path. Note that the login and system
1933 * keychains are no longer accessible to user applications starting in macOS
1934 * 10.11.4 (!), so we need to create our own keychain just for CUPS.
1937 if (getuid() && home
)
1938 snprintf(buffer
, bufsize
, "%s/.cups/ssl.keychain", home
);
1940 strlcpy(buffer
, "/etc/cups/ssl.keychain", bufsize
);
1942 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1949 * 'http_cdsa_open_keychain()' - Open (or create) a keychain.
1952 static SecKeychainRef
/* O - Keychain or NULL */
1953 http_cdsa_open_keychain(
1954 const char *path
, /* I - Path to keychain */
1955 char *filename
, /* I - Keychain filename */
1956 size_t filesize
) /* I - Size of filename buffer */
1958 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
1959 OSStatus err
; /* Error code */
1960 Boolean interaction
; /* Interaction allowed? */
1961 SecKeychainStatus status
= 0; /* Keychain status */
1965 * Get the keychain filename...
1970 path
= http_cdsa_default_path(filename
, filesize
);
1971 tls_cups_keychain
= 1;
1975 strlcpy(filename
, path
, filesize
);
1976 tls_cups_keychain
= 0;
1980 * Save the interaction setting and disable while we open the keychain...
1983 SecKeychainGetUserInteractionAllowed(&interaction
);
1984 SecKeychainSetUserInteractionAllowed(FALSE
);
1986 if (access(path
, R_OK
) && tls_cups_keychain
)
1989 * Create a new keychain at the given path...
1992 err
= SecKeychainCreate(path
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, FALSE
, NULL
, &keychain
);
1997 * Open the existing keychain and unlock as needed...
2000 err
= SecKeychainOpen(path
, &keychain
);
2003 err
= SecKeychainGetStatus(keychain
, &status
);
2005 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
) && tls_cups_keychain
)
2006 err
= SecKeychainUnlock(keychain
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, TRUE
);
2010 * Restore interaction setting...
2013 SecKeychainSetUserInteractionAllowed(interaction
);
2016 * Release the keychain if we had any errors...
2021 /* TODO: Set cups last error string */
2022 DEBUG_printf(("4http_cdsa_open_keychain: Unable to open keychain (%d), returning NULL.", (int)err
));
2026 CFRelease(keychain
);
2032 * Return the keychain or NULL...
2040 * 'http_cdsa_open_system_keychain()' - Open the System keychain.
2043 static SecKeychainRef
2044 http_cdsa_open_system_keychain(void)
2046 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
2047 OSStatus err
; /* Error code */
2048 Boolean interaction
; /* Interaction allowed? */
2049 SecKeychainStatus status
= 0; /* Keychain status */
2053 * Save the interaction setting and disable while we open the keychain...
2056 SecKeychainGetUserInteractionAllowed(&interaction
);
2057 SecKeychainSetUserInteractionAllowed(TRUE
);
2059 err
= SecKeychainOpen("/Library/Keychains/System.keychain", &keychain
);
2062 err
= SecKeychainGetStatus(keychain
, &status
);
2064 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
))
2065 err
= errSecInteractionNotAllowed
;
2068 * Restore interaction setting...
2071 SecKeychainSetUserInteractionAllowed(interaction
);
2074 * Release the keychain if we had any errors...
2079 /* TODO: Set cups last error string */
2080 DEBUG_printf(("4http_cdsa_open_system_keychain: Unable to open keychain (%d), returning NULL.", (int)err
));
2084 CFRelease(keychain
);
2090 * Return the keychain or NULL...
2095 #endif /* HAVE_SECKEYCHAINOPEN */
2099 * 'http_cdsa_read()' - Read function for the CDSA library.
2102 static OSStatus
/* O - -1 on error, 0 on success */
2104 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2105 void *data
, /* I - Data buffer */
2106 size_t *dataLength
) /* IO - Number of bytes */
2108 OSStatus result
; /* Return value */
2109 ssize_t bytes
; /* Number of bytes read */
2110 http_t
*http
; /* HTTP connection */
2113 http
= (http_t
*)connection
;
2115 if (!http
->blocking
|| http
->timeout_value
> 0.0)
2118 * Make sure we have data before we read...
2121 while (!_httpWait(http
, http
->wait_value
, 0))
2123 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2126 http
->error
= ETIMEDOUT
;
2133 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2135 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2137 if ((size_t)bytes
== *dataLength
)
2143 *dataLength
= (size_t)bytes
;
2144 result
= errSSLWouldBlock
;
2151 result
= errSSLClosedGraceful
;
2152 else if (errno
== EAGAIN
)
2153 result
= errSSLWouldBlock
;
2155 result
= errSSLClosedAbort
;
2163 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
2166 static int /* O - Status of connection */
2167 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
2169 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2170 OSStatus error
= 0; /* Error code */
2171 http_tls_credentials_t credentials
= NULL
;
2172 /* TLS credentials */
2175 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http
));
2178 * Prefer connection specific credentials...
2181 if ((credentials
= http
->tls_credentials
) == NULL
)
2182 credentials
= cg
->tls_credentials
;
2186 error
= SSLSetCertificate(http
->tls
, credentials
);
2187 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
2191 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
2198 * 'http_cdsa_write()' - Write function for the CDSA library.
2201 static OSStatus
/* O - -1 on error, 0 on success */
2203 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2204 const void *data
, /* I - Data buffer */
2205 size_t *dataLength
) /* IO - Number of bytes */
2207 OSStatus result
; /* Return value */
2208 ssize_t bytes
; /* Number of bytes read */
2209 http_t
*http
; /* HTTP connection */
2212 http
= (http_t
*)connection
;
2216 bytes
= write(http
->fd
, data
, *dataLength
);
2218 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2220 if ((size_t)bytes
== *dataLength
)
2224 else if (bytes
>= 0)
2226 *dataLength
= (size_t)bytes
;
2227 result
= errSSLWouldBlock
;
2233 if (errno
== EAGAIN
)
2234 result
= errSSLWouldBlock
;
2236 result
= errSSLClosedAbort
;