2 * TLS support code for CUPS on macOS.
4 * Copyright 2007-2016 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * file is missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
16 /**** This file is included from tls.c ****/
19 * Include necessary headers...
24 extern char **environ
;
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 SecKeychainRef tls_keychain
= NULL
;
45 /* Server cert keychain */
47 static SecIdentityRef tls_selfsigned
= NULL
;
48 /* Temporary self-signed cert */
49 #endif /* HAVE_SECKEYCHAINOPEN */
50 static char *tls_keypath
= NULL
;
51 /* Server cert keychain path */
52 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
53 /* Mutex for keychain/certs */
54 static int tls_options
= -1;/* Options for TLS connections */
61 static CFArrayRef
http_cdsa_copy_server(const char *common_name
);
62 static SecCertificateRef
http_cdsa_create_credential(http_credential_t
*credential
);
63 #ifdef HAVE_SECKEYCHAINOPEN
64 static const char *http_cdsa_default_path(char *buffer
, size_t bufsize
);
65 static SecKeychainRef
http_cdsa_open_keychain(const char *path
, char *filename
, size_t filesize
);
66 static SecKeychainRef
http_cdsa_open_system_keychain(void);
67 #endif /* HAVE_SECKEYCHAINOPEN */
68 static OSStatus
http_cdsa_read(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
69 static int http_cdsa_set_credentials(http_t
*http
);
70 static OSStatus
http_cdsa_write(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
74 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
76 * @since CUPS 2.0/OS 10.10@
79 int /* O - 1 on success, 0 on failure */
80 cupsMakeServerCredentials(
81 const char *path
, /* I - Keychain path or @code NULL@ for default */
82 const char *common_name
, /* I - Common name */
83 int num_alt_names
, /* I - Number of subject alternate names */
84 const char **alt_names
, /* I - Subject Alternate Names */
85 time_t expiration_date
) /* I - Expiration date */
87 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
88 int status
= 0; /* Return status */
89 OSStatus err
; /* Error code (if any) */
90 CFStringRef cfcommon_name
= NULL
;
91 /* CF string for server name */
92 SecIdentityRef ident
= NULL
; /* Identity */
93 SecKeyRef publicKey
= NULL
,
97 SecCertificateRef cert
= NULL
; /* Self-signed certificate */
98 CFMutableDictionaryRef keyParams
= NULL
;
99 /* Key generation parameters */
102 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
));
107 (void)expiration_date
;
111 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
117 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
121 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
124 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
129 * Create a public/private key pair...
132 keyParams
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
135 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
139 CFDictionaryAddValue(keyParams
, kSecAttrKeyType
, kSecAttrKeyTypeRSA
);
140 CFDictionaryAddValue(keyParams
, kSecAttrKeySizeInBits
, CFSTR("2048"));
141 CFDictionaryAddValue(keyParams
, kSecAttrLabel
, cfcommon_name
);
143 err
= SecKeyGeneratePair(keyParams
, &publicKey
, &privateKey
);
146 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err
));
151 * Create a self-signed certificate using the public/private key pair...
154 CFIndex usageInt
= kSecKeyUsageAll
;
155 CFNumberRef usage
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &usageInt
);
157 CFNumberRef len
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberCFIndexType
, &lenInt
);
158 CFTypeRef certKeys
[] = { kSecCSRBasicContraintsPathLen
, kSecSubjectAltName
, kSecCertificateKeyUsage
};
159 CFTypeRef certValues
[] = { len
, cfcommon_name
, usage
};
160 CFDictionaryRef certParams
= CFDictionaryCreate(kCFAllocatorDefault
, certKeys
, certValues
, sizeof(certKeys
) / sizeof(certKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
164 const void *ca_o
[] = { kSecOidOrganization
, CFSTR("") };
165 const void *ca_cn
[] = { kSecOidCommonName
, cfcommon_name
};
166 CFArrayRef ca_o_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_o
, 2, NULL
);
167 CFArrayRef ca_cn_dn
= CFArrayCreate(kCFAllocatorDefault
, ca_cn
, 2, NULL
);
168 const void *ca_dn_array
[2];
170 ca_dn_array
[0] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_o_dn
, 1, NULL
);
171 ca_dn_array
[1] = CFArrayCreate(kCFAllocatorDefault
, (const void **)&ca_cn_dn
, 1, NULL
);
173 CFArrayRef subject
= CFArrayCreate(kCFAllocatorDefault
, ca_dn_array
, 2, NULL
);
175 cert
= SecGenerateSelfSignedCertificate(subject
, certParams
, publicKey
, privateKey
);
178 CFRelease(certParams
);
182 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
186 ident
= SecIdentityCreate(kCFAllocatorDefault
, cert
, privateKey
);
190 _cupsMutexLock(&tls_mutex
);
195 tls_selfsigned
= ident
;
197 _cupsMutexLock(&tls_mutex
);
199 # if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point */
200 CFTypeRef itemKeys
[] = { kSecClass
, kSecAttrLabel
, kSecValueRef
};
201 CFTypeRef itemValues
[] = { kSecClassIdentity
, cfcommon_name
, ident
};
202 CFDictionaryRef itemAttrs
= CFDictionaryCreate(kCFAllocatorDefault
, itemKeys
, itemValues
, sizeof(itemKeys
) / sizeof(itemKeys
[0]), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
204 err
= SecItemAdd(itemAttrs
, NULL
);
205 /* SecItemAdd consumes itemAttrs... */
211 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err
));
219 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
222 * Cleanup and return...
228 CFRelease(cfcommon_name
);
231 CFRelease(keyParams
);
237 CFRelease(publicKey
);
240 CFRelease(privateKey
);
242 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status
));
246 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
247 int pid
, /* Process ID of command */
248 status
, /* Status of command */
250 char command
[1024], /* Command */
251 *argv
[5], /* Command-line arguments */
252 *envp
[1000], /* Environment variables */
253 days
[32], /* CERTTOOL_EXPIRATION_DAYS env var */
254 keychain
[1024], /* Keychain argument */
255 infofile
[1024], /* Type-in information for cert */
256 filename
[1024]; /* Default keychain path */
257 cups_file_t
*fp
; /* Seed/info file */
260 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
));
266 path
= http_cdsa_default_path(filename
, sizeof(filename
));
269 * Run the "certtool" command to generate a self-signed certificate...
272 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
276 * Create a file with the certificate information fields...
278 * Note: This assumes that the default questions are asked by the certtool
282 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
286 "CUPS Self-Signed Certificate\n"
287 /* Enter key and certificate label */
288 "r\n" /* Generate RSA key pair */
289 "2048\n" /* 2048 bit encryption key */
290 "y\n" /* OK (y = yes) */
291 "b\n" /* Usage (b=signing/encryption) */
292 "2\n" /* Sign with SHA256 */
293 "y\n" /* OK (y = yes) */
294 "%s\n" /* Common name */
295 "\n" /* Country (default) */
296 "\n" /* Organization (default) */
297 "\n" /* Organizational unit (default) */
298 "\n" /* State/Province (default) */
299 "\n" /* Email address */
300 "y\n", /* OK (y = yes) */
304 snprintf(keychain
, sizeof(keychain
), "k=%s", path
);
306 argv
[0] = "certtool";
311 snprintf(days
, sizeof(days
), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date
- time(NULL
) + 86399) / 86400));
313 for (i
= 0; i
< (int)(sizeof(envp
) / sizeof(envp
[0]) - 2) && environ
[i
]; i
++)
314 envp
[i
+ 1] = environ
[i
];
317 posix_spawn_file_actions_t actions
; /* File actions */
319 posix_spawn_file_actions_init(&actions
);
320 posix_spawn_file_actions_addclose(&actions
, 0);
321 posix_spawn_file_actions_addopen(&actions
, 0, infofile
, O_RDONLY
, 0);
322 posix_spawn_file_actions_addclose(&actions
, 1);
323 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
324 posix_spawn_file_actions_addclose(&actions
, 2);
325 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
327 if (posix_spawn(&pid
, command
, &actions
, NULL
, argv
, envp
))
333 posix_spawn_file_actions_destroy(&actions
);
337 while (waitpid(pid
, &status
, 0) < 0)
345 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
350 * 'cupsSetServerCredentials()' - Set the default server credentials.
352 * Note: The server credentials are used by all threads in the running process.
353 * This function is threadsafe.
355 * @since CUPS 2.0/macOS 10.10@
358 int /* O - 1 on success, 0 on failure */
359 cupsSetServerCredentials(
360 const char *path
, /* I - Keychain path or @code NULL@ for default */
361 const char *common_name
, /* I - Default common name for server */
362 int auto_create
) /* I - 1 = automatically create self-signed certificates */
364 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
366 #ifdef HAVE_SECKEYCHAINOPEN
367 char filename
[1024]; /* Keychain filename */
368 SecKeychainRef keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
372 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain.");
376 _cupsMutexLock(&tls_mutex
);
379 * Close any keychain that is currently open...
383 CFRelease(tls_keychain
);
386 _cupsStrFree(tls_keypath
);
389 _cupsStrFree(tls_common_name
);
392 * Save the new keychain...
395 tls_keychain
= keychain
;
396 tls_keypath
= _cupsStrAlloc(filename
);
397 tls_auto_create
= auto_create
;
398 tls_common_name
= _cupsStrAlloc(common_name
);
400 _cupsMutexUnlock(&tls_mutex
);
402 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
408 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
412 tls_auto_create
= auto_create
;
413 tls_common_name
= _cupsStrAlloc(common_name
);
416 #endif /* HAVE_SECKEYCHAINOPEN */
421 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
422 * an encrypted connection.
424 * @since CUPS 1.5/macOS 10.7@
427 int /* O - Status of call (0 = success) */
429 http_t
*http
, /* I - Connection to server */
430 cups_array_t
**credentials
) /* O - Array of credentials */
432 OSStatus error
; /* Error code */
433 SecTrustRef peerTrust
; /* Peer trust reference */
434 CFIndex count
; /* Number of credentials */
435 SecCertificateRef secCert
; /* Certificate reference */
436 CFDataRef data
; /* Certificate data */
437 int i
; /* Looping var */
440 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http
, (void *)credentials
));
445 if (!http
|| !http
->tls
|| !credentials
)
448 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
450 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust
)));
452 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
454 count
= SecTrustGetCertificateCount(peerTrust
);
456 for (i
= 0; i
< count
; i
++)
458 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
461 CFStringRef cf_name
= SecCertificateCopySubjectSummary(secCert
);
464 CFStringGetCString(cf_name
, name
, sizeof(name
), kCFStringEncodingUTF8
);
466 strlcpy(name
, "unknown", sizeof(name
));
468 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i
, name
));
471 if ((data
= SecCertificateCopyData(secCert
)) != NULL
)
473 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
475 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
481 CFRelease(peerTrust
);
489 * '_httpCreateCredentials()' - Create credentials in the internal format.
492 http_tls_credentials_t
/* O - Internal credentials */
493 _httpCreateCredentials(
494 cups_array_t
*credentials
) /* I - Array of credentials */
496 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
497 SecCertificateRef secCert
; /* Certificate reference */
498 http_credential_t
*credential
; /* Credential data */
504 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
505 cupsArrayCount(credentials
),
506 &kCFTypeArrayCallBacks
)) == NULL
)
509 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
511 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
513 if ((secCert
= http_cdsa_create_credential(credential
)) != NULL
)
515 CFArrayAppendValue(peerCerts
, secCert
);
525 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
527 * @since CUPS 2.0/macOS 10.10@
530 int /* O - 1 if valid, 0 otherwise */
531 httpCredentialsAreValidForName(
532 cups_array_t
*credentials
, /* I - Credentials */
533 const char *common_name
) /* I - Name to check */
535 SecCertificateRef secCert
; /* Certificate reference */
536 CFStringRef cfcert_name
= NULL
;
537 /* Certificate's common name (CF string) */
538 char cert_name
[256]; /* Certificate's common name (C string) */
539 int valid
= 1; /* Valid name? */
542 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
546 * Compare the common names...
549 if ((cfcert_name
= SecCertificateCopySubjectSummary(secCert
)) == NULL
)
552 * Can't get common name, cannot be valid...
557 else if (CFStringGetCString(cfcert_name
, cert_name
, sizeof(cert_name
), kCFStringEncodingUTF8
) &&
558 _cups_strcasecmp(common_name
, cert_name
))
561 * Not an exact match for the common name, check for wildcard certs...
564 const char *domain
= strchr(common_name
, '.');
565 /* Domain in common name */
567 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
570 * Not a wildcard match.
573 /* TODO: Check subject alternate names */
579 CFRelease(cfcert_name
);
588 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
590 * @since CUPS 2.0/macOS 10.10@
593 http_trust_t
/* O - Level of trust */
594 httpCredentialsGetTrust(
595 cups_array_t
*credentials
, /* I - Credentials */
596 const char *common_name
) /* I - Common name for trust lookup */
598 SecCertificateRef secCert
; /* Certificate reference */
599 http_trust_t trust
= HTTP_TRUST_OK
;
601 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
602 _cups_globals_t
*cg
= _cupsGlobals();
603 /* Per-thread globals */
608 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No common name specified."), 1);
609 return (HTTP_TRUST_UNKNOWN
);
612 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
614 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create credentials from array."), 1);
615 return (HTTP_TRUST_UNKNOWN
);
618 if (cg
->any_root
< 0)
622 * Look this common name up in the default keychains...
625 httpLoadCredentials(NULL
, &tcreds
, common_name
);
629 char credentials_str
[1024], /* String for incoming credentials */
630 tcreds_str
[1024]; /* String for saved credentials */
632 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
633 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
635 if (strcmp(credentials_str
, tcreds_str
))
638 * Credentials don't match, let's look at the expiration date of the new
639 * credentials and allow if the new ones have a later expiration...
642 if (!cg
->trust_first
)
645 * Do not trust certificates on first use...
648 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
650 trust
= HTTP_TRUST_INVALID
;
652 else if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
))
655 * The new credentials are not newly issued...
658 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are older than stored credentials."), 1);
660 trust
= HTTP_TRUST_INVALID
;
662 else if (!httpCredentialsAreValidForName(credentials
, common_name
))
665 * The common name does not match the issued certificate...
668 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are not valid for name."), 1);
670 trust
= HTTP_TRUST_INVALID
;
672 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
675 * Save the renewed credentials...
678 trust
= HTTP_TRUST_RENEWED
;
680 httpSaveCredentials(NULL
, credentials
, common_name
);
684 httpFreeCredentials(tcreds
);
686 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
688 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No stored credentials, not valid for name."), 1);
689 trust
= HTTP_TRUST_INVALID
;
691 else if (!cg
->trust_first
)
693 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
694 trust
= HTTP_TRUST_INVALID
;
697 if (trust
== HTTP_TRUST_OK
&& !cg
->expired_certs
&& !SecCertificateIsValid(secCert
, CFAbsoluteTimeGetCurrent()))
699 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials have expired."), 1);
700 trust
= HTTP_TRUST_EXPIRED
;
703 if (trust
== HTTP_TRUST_OK
&& !cg
->any_root
&& cupsArrayCount(credentials
) == 1)
705 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Self-signed credentials are blocked."), 1);
706 trust
= HTTP_TRUST_INVALID
;
716 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
718 * @since CUPS 2.0/macOS 10.10@
721 time_t /* O - Expiration date of credentials */
722 httpCredentialsGetExpiration(
723 cups_array_t
*credentials
) /* I - Credentials */
725 SecCertificateRef secCert
; /* Certificate reference */
726 time_t expiration
; /* Expiration date */
729 if ((secCert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
732 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
741 * 'httpCredentialsString()' - Return a string representing the credentials.
743 * @since CUPS 2.0/macOS 10.10@
746 size_t /* O - Total size of credentials string */
747 httpCredentialsString(
748 cups_array_t
*credentials
, /* I - Credentials */
749 char *buffer
, /* I - Buffer or @code NULL@ */
750 size_t bufsize
) /* I - Size of buffer */
752 http_credential_t
*first
; /* First certificate */
753 SecCertificateRef secCert
; /* Certificate reference */
756 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", (void *)credentials
, (void *)buffer
, CUPS_LLCAST bufsize
));
761 if (buffer
&& bufsize
> 0)
764 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
765 (secCert
= http_cdsa_create_credential(first
)) != NULL
)
767 CFStringRef cf_name
; /* CF common name string */
768 char name
[256]; /* Common name associated with cert */
769 time_t expiration
; /* Expiration date of cert */
770 _cups_md5_state_t md5_state
; /* MD5 state */
771 unsigned char md5_digest
[16]; /* MD5 result */
773 if ((cf_name
= SecCertificateCopySubjectSummary(secCert
)) != NULL
)
775 CFStringGetCString(cf_name
, name
, (CFIndex
)sizeof(name
), kCFStringEncodingUTF8
);
779 strlcpy(name
, "unknown", sizeof(name
));
781 expiration
= (time_t)(SecCertificateNotValidAfter(secCert
) + kCFAbsoluteTimeIntervalSince1970
);
783 _cupsMD5Init(&md5_state
);
784 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
785 _cupsMD5Finish(&md5_state
, md5_digest
);
787 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]);
792 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
794 return (strlen(buffer
));
799 * '_httpFreeCredentials()' - Free internal credentials.
803 _httpFreeCredentials(
804 http_tls_credentials_t credentials
) /* I - Internal credentials */
809 CFRelease(credentials
);
814 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
816 * @since CUPS 2.0/OS 10.10@
819 int /* O - 0 on success, -1 on error */
821 const char *path
, /* I - Keychain path or @code NULL@ for default */
822 cups_array_t
**credentials
, /* IO - Credentials */
823 const char *common_name
) /* I - Common name for credentials */
825 OSStatus err
; /* Error info */
826 #ifdef HAVE_SECKEYCHAINOPEN
827 char filename
[1024]; /* Filename for keychain */
828 SecKeychainRef keychain
= NULL
,/* Keychain reference */
829 syschain
= NULL
;/* System keychain */
830 CFArrayRef list
; /* Keychain list */
831 #endif /* HAVE_SECKEYCHAINOPEN */
832 SecCertificateRef cert
= NULL
; /* Certificate */
833 CFDataRef data
; /* Certificate data */
834 SecPolicyRef policy
= NULL
; /* Policy ref */
835 CFStringRef cfcommon_name
= NULL
;
837 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
840 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
847 #ifdef HAVE_SECKEYCHAINOPEN
848 keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
853 syschain
= http_cdsa_open_system_keychain();
858 #endif /* HAVE_SECKEYCHAINOPEN */
860 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
862 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
865 CFRelease(cfcommon_name
);
870 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
873 CFDictionaryAddValue(query
, kSecClass
, kSecClassCertificate
);
874 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
875 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
876 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
878 #ifdef HAVE_SECKEYCHAINOPEN
881 const void *values
[2] = { syschain
, keychain
};
883 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)values
, 2, &kCFTypeArrayCallBacks
);
886 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
);
887 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
889 #endif /* HAVE_SECKEYCHAINOPEN */
891 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&cert
);
896 if (CFGetTypeID(cert
) != SecCertificateGetTypeID())
899 if ((data
= SecCertificateCopyData(cert
)) != NULL
)
901 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data
)));
903 *credentials
= cupsArrayNew(NULL
, NULL
);
904 httpAddCredential(*credentials
, CFDataGetBytePtr(data
), (size_t)CFDataGetLength(data
));
910 #ifdef HAVE_SECKEYCHAINOPEN
916 #endif /* HAVE_SECKEYCHAINOPEN */
924 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
926 return (*credentials
? 0 : -1);
931 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
933 * @since CUPS 2.0/OS 10.10@
936 int /* O - -1 on error, 0 on success */
938 const char *path
, /* I - Keychain path or @code NULL@ for default */
939 cups_array_t
*credentials
, /* I - Credentials */
940 const char *common_name
) /* I - Common name for credentials */
942 int ret
= -1; /* Return value */
943 OSStatus err
; /* Error info */
944 #ifdef HAVE_SECKEYCHAINOPEN
945 char filename
[1024]; /* Filename for keychain */
946 SecKeychainRef keychain
= NULL
;/* Keychain reference */
947 CFArrayRef list
; /* Keychain list */
948 #endif /* HAVE_SECKEYCHAINOPEN */
949 SecCertificateRef cert
= NULL
; /* Certificate */
950 CFMutableDictionaryRef attrs
= NULL
; /* Attributes for add */
953 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, (void *)credentials
, common_name
));
957 if (!httpCredentialsAreValidForName(credentials
, common_name
))
959 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
963 if ((cert
= http_cdsa_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
965 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
969 #ifdef HAVE_SECKEYCHAINOPEN
970 keychain
= http_cdsa_open_keychain(path
, filename
, sizeof(filename
));
978 #endif /* HAVE_SECKEYCHAINOPEN */
980 if ((attrs
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)) == NULL
)
982 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
986 CFDictionaryAddValue(attrs
, kSecClass
, kSecClassCertificate
);
987 CFDictionaryAddValue(attrs
, kSecValueRef
, cert
);
989 #ifdef HAVE_SECKEYCHAINOPEN
990 if ((list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&keychain
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
992 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
995 CFDictionaryAddValue(attrs
, kSecMatchSearchList
, list
);
997 #endif /* HAVE_SECKEYCHAINOPEN */
999 /* Note: SecItemAdd consumes "attrs"... */
1000 err
= SecItemAdd(attrs
, NULL
);
1001 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err
));
1005 #ifdef HAVE_SECKEYCHAINOPEN
1007 CFRelease(keychain
);
1008 #endif /* HAVE_SECKEYCHAINOPEN */
1012 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
1019 * '_httpTLSInitialize()' - Initialize the TLS stack.
1023 _httpTLSInitialize(void)
1032 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1036 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
1038 size_t bytes
; /* Bytes that are available */
1041 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
))
1049 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1052 int /* O - Bytes read */
1053 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
1054 char *buf
, /* I - Buffer to store data */
1055 int len
) /* I - Length of buffer */
1057 int result
; /* Return value */
1058 OSStatus error
; /* Error info */
1059 size_t processed
; /* Number of bytes processed */
1062 error
= SSLRead(http
->tls
, buf
, (size_t)len
, &processed
);
1063 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error
,
1068 result
= (int)processed
;
1071 case errSSLWouldBlock
:
1073 result
= (int)processed
;
1081 case errSSLClosedGraceful
:
1084 result
= (int)processed
;
1098 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1102 _httpTLSSetOptions(int options
) /* I - Options */
1104 tls_options
= options
;
1109 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1112 int /* O - 0 on success, -1 on failure */
1113 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
1115 char hostname
[256], /* Hostname */
1116 *hostptr
; /* Pointer into hostname */
1117 _cups_globals_t
*cg
= _cupsGlobals();
1118 /* Pointer to library globals */
1119 OSStatus error
; /* Error code */
1120 const char *message
= NULL
;/* Error message */
1121 cups_array_t
*credentials
; /* Credentials array */
1122 cups_array_t
*names
; /* CUPS distinguished names */
1123 CFArrayRef dn_array
; /* CF distinguished names array */
1124 CFIndex count
; /* Number of credentials */
1125 CFDataRef data
; /* Certificate data */
1126 int i
; /* Looping var */
1127 http_credential_t
*credential
; /* Credential data */
1130 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http
));
1132 if (tls_options
< 0)
1134 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1136 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1139 #ifdef HAVE_SECKEYCHAINOPEN
1140 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keychain
)
1142 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1143 http
->error
= errno
= EINVAL
;
1144 http
->status
= HTTP_STATUS_ERROR
;
1145 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1149 #endif /* HAVE_SECKEYCHAINOPEN */
1151 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, http
->mode
== _HTTP_MODE_CLIENT
? kSSLClientSide
: kSSLServerSide
, kSSLStreamType
)) == NULL
)
1153 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1154 http
->error
= errno
= ENOMEM
;
1155 http
->status
= HTTP_STATUS_ERROR
;
1156 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1161 error
= SSLSetConnection(http
->tls
, http
);
1162 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error
));
1166 error
= SSLSetIOFuncs(http
->tls
, http_cdsa_read
, http_cdsa_write
);
1167 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error
));
1172 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
1174 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error
));
1179 SSLProtocol minProtocol
;
1181 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1182 minProtocol
= kTLSProtocol11
;
1183 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1184 minProtocol
= kSSLProtocol3
;
1186 minProtocol
= kTLSProtocol1
;
1188 error
= SSLSetProtocolVersionMin(http
->tls
, minProtocol
);
1189 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol
, (int)error
));
1192 # if HAVE_SSLSETENABLEDCIPHERS
1195 SSLCipherSuite supported
[100]; /* Supported cipher suites */
1196 size_t num_supported
; /* Number of supported cipher suites */
1197 SSLCipherSuite enabled
[100]; /* Cipher suites to enable */
1198 size_t num_enabled
; /* Number of cipher suites to enable */
1200 num_supported
= sizeof(supported
) / sizeof(supported
[0]);
1201 error
= SSLGetSupportedCiphers(http
->tls
, supported
, &num_supported
);
1205 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported
));
1207 for (i
= 0, num_enabled
= 0; i
< (int)num_supported
&& num_enabled
< (sizeof(enabled
) / sizeof(enabled
[0])); i
++)
1209 switch (supported
[i
])
1211 /* Obviously insecure cipher suites that we never want to use */
1212 case SSL_NULL_WITH_NULL_NULL
:
1213 case SSL_RSA_WITH_NULL_MD5
:
1214 case SSL_RSA_WITH_NULL_SHA
:
1215 case SSL_RSA_EXPORT_WITH_RC4_40_MD5
:
1216 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
1217 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1218 case SSL_RSA_WITH_DES_CBC_SHA
:
1219 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1220 case SSL_DH_DSS_WITH_DES_CBC_SHA
:
1221 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1222 case SSL_DH_RSA_WITH_DES_CBC_SHA
:
1223 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
:
1224 case SSL_DHE_DSS_WITH_DES_CBC_SHA
:
1225 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
:
1226 case SSL_DHE_RSA_WITH_DES_CBC_SHA
:
1227 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
:
1228 case SSL_DH_anon_WITH_RC4_128_MD5
:
1229 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
:
1230 case SSL_DH_anon_WITH_DES_CBC_SHA
:
1231 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
:
1232 case SSL_FORTEZZA_DMS_WITH_NULL_SHA
:
1233 case TLS_DH_anon_WITH_AES_128_CBC_SHA
:
1234 case TLS_DH_anon_WITH_AES_256_CBC_SHA
:
1235 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
1236 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
1237 case TLS_ECDH_anon_WITH_NULL_SHA
:
1238 case TLS_ECDH_anon_WITH_RC4_128_SHA
:
1239 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
:
1240 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA
:
1241 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA
:
1242 case TLS_RSA_WITH_NULL_SHA256
:
1243 case TLS_DH_anon_WITH_AES_128_CBC_SHA256
:
1244 case TLS_DH_anon_WITH_AES_256_CBC_SHA256
:
1245 case TLS_PSK_WITH_NULL_SHA
:
1246 case TLS_DHE_PSK_WITH_NULL_SHA
:
1247 case TLS_RSA_PSK_WITH_NULL_SHA
:
1248 case TLS_DH_anon_WITH_AES_128_GCM_SHA256
:
1249 case TLS_DH_anon_WITH_AES_256_GCM_SHA384
:
1250 case TLS_PSK_WITH_NULL_SHA256
:
1251 case TLS_PSK_WITH_NULL_SHA384
:
1252 case TLS_DHE_PSK_WITH_NULL_SHA256
:
1253 case TLS_DHE_PSK_WITH_NULL_SHA384
:
1254 case TLS_RSA_PSK_WITH_NULL_SHA256
:
1255 case TLS_RSA_PSK_WITH_NULL_SHA384
:
1256 case SSL_RSA_WITH_DES_CBC_MD5
:
1257 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported
[i
]));
1260 /* RC4 cipher suites that should only be used as a last resort */
1261 case SSL_RSA_WITH_RC4_128_MD5
:
1262 case SSL_RSA_WITH_RC4_128_SHA
:
1263 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
1264 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
1265 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
1266 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
1267 case TLS_PSK_WITH_RC4_128_SHA
:
1268 case TLS_DHE_PSK_WITH_RC4_128_SHA
:
1269 case TLS_RSA_PSK_WITH_RC4_128_SHA
:
1270 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1271 enabled
[num_enabled
++] = supported
[i
];
1273 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported
[i
]));
1276 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1277 case TLS_DH_DSS_WITH_AES_128_CBC_SHA
:
1278 case TLS_DH_RSA_WITH_AES_128_CBC_SHA
:
1279 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA
:
1280 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA
:
1281 case TLS_DH_DSS_WITH_AES_256_CBC_SHA
:
1282 case TLS_DH_RSA_WITH_AES_256_CBC_SHA
:
1283 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA
:
1284 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA
:
1285 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
:
1286 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
:
1287 // case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
1288 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
:
1289 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256
:
1290 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256
:
1291 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
:
1292 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
:
1293 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256
:
1294 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256
:
1295 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
:
1296 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
:
1297 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
:
1298 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA
:
1299 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA
:
1300 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1301 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1302 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256
:
1303 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384
:
1304 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1305 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1306 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256
:
1307 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384
:
1308 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
:
1309 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
:
1310 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
:
1311 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
:
1312 if (tls_options
& _HTTP_TLS_ALLOW_DH
)
1313 enabled
[num_enabled
++] = supported
[i
];
1315 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported
[i
]));
1318 /* Anything else we'll assume is secure */
1320 enabled
[num_enabled
++] = supported
[i
];
1325 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled
));
1326 error
= SSLSetEnabledCiphers(http
->tls
, enabled
, num_enabled
);
1329 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1331 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1334 * Client: set client-side credentials, if any...
1337 if (cg
->client_cert_cb
)
1339 error
= SSLSetSessionOption(http
->tls
,
1340 kSSLSessionOptionBreakOnCertRequested
, true);
1341 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1342 "error=%d", (int)error
));
1346 error
= http_cdsa_set_credentials(http
);
1347 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1354 * Server: find/create a certificate for TLS...
1357 if (http
->fields
[HTTP_FIELD_HOST
][0])
1360 * Use hostname for TLS upgrade...
1363 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1368 * Resolve hostname from connection address...
1371 http_addr_t addr
; /* Connection address */
1372 socklen_t addrlen
; /* Length of address */
1374 addrlen
= sizeof(addr
);
1375 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1377 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1380 else if (httpAddrLocalhost(&addr
))
1384 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1385 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1389 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1390 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1393 http
->tls_credentials
= http_cdsa_copy_server(hostname
);
1394 else if (tls_common_name
)
1395 http
->tls_credentials
= http_cdsa_copy_server(tls_common_name
);
1397 if (!http
->tls_credentials
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1399 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1401 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1403 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1404 http
->error
= errno
= EINVAL
;
1405 http
->status
= HTTP_STATUS_ERROR
;
1406 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1411 http
->tls_credentials
= http_cdsa_copy_server(hostname
[0] ? hostname
: tls_common_name
);
1414 if (!http
->tls_credentials
)
1416 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1417 http
->error
= errno
= EINVAL
;
1418 http
->status
= HTTP_STATUS_ERROR
;
1419 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to find server credentials."), 1);
1424 error
= SSLSetCertificate(http
->tls
, http
->tls_credentials
);
1426 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error
));
1429 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http
->tls_credentials
));
1432 * Let the server know which hostname/domain we are trying to connect to
1433 * in case it wants to serve up a certificate with a matching common name.
1436 if (!error
&& http
->mode
== _HTTP_MODE_CLIENT
)
1439 * Client: get the hostname to use for TLS...
1442 if (httpAddrLocalhost(http
->hostaddr
))
1444 strlcpy(hostname
, "localhost", sizeof(hostname
));
1449 * Otherwise make sure the hostname we have does not end in a trailing dot.
1452 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1453 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1458 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
1460 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error
));
1465 int done
= 0; /* Are we done yet? */
1467 while (!error
&& !done
)
1469 error
= SSLHandshake(http
->tls
);
1471 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error
));
1479 case errSSLWouldBlock
:
1480 error
= noErr
; /* Force a retry */
1481 usleep(1000); /* in 1 millisecond */
1484 case errSSLServerAuthCompleted
:
1486 if (cg
->server_cert_cb
)
1488 error
= httpCopyCredentials(http
, &credentials
);
1491 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
1492 cg
->server_cert_data
);
1493 httpFreeCredentials(credentials
);
1496 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1497 "returned %d.", (int)error
));
1501 case errSSLClientCertRequested
:
1504 if (cg
->client_cert_cb
)
1507 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
1510 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
1512 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
1514 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
1516 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
1518 credential
->datalen
= (size_t)CFDataGetLength(data
);
1519 if ((credential
->data
= malloc(credential
->datalen
)))
1521 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
1522 credential
->datalen
);
1523 cupsArrayAdd(names
, credential
);
1531 CFRelease(dn_array
);
1536 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
1537 cg
->client_cert_data
);
1539 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1540 "returned %d.", (int)error
));
1543 httpFreeCredentials(names
);
1547 case errSSLUnknownRootCert
:
1548 message
= _("Unable to establish a secure connection to host "
1549 "(untrusted certificate).");
1552 case errSSLNoRootCert
:
1553 message
= _("Unable to establish a secure connection to host "
1554 "(self-signed certificate).");
1557 case errSSLCertExpired
:
1558 message
= _("Unable to establish a secure connection to host "
1559 "(expired certificate).");
1562 case errSSLCertNotYetValid
:
1563 message
= _("Unable to establish a secure connection to host "
1564 "(certificate not yet valid).");
1567 case errSSLHostNameMismatch
:
1568 message
= _("Unable to establish a secure connection to host "
1569 "(host name mismatch).");
1572 case errSSLXCertChainInvalid
:
1573 message
= _("Unable to establish a secure connection to host "
1574 "(certificate chain invalid).");
1577 case errSSLConnectionRefused
:
1578 message
= _("Unable to establish a secure connection to host "
1579 "(peer dropped connection before responding).");
1590 http
->error
= error
;
1591 http
->status
= HTTP_STATUS_ERROR
;
1592 errno
= ECONNREFUSED
;
1594 CFRelease(http
->tls
);
1598 * If an error string wasn't set by the callbacks use a generic one...
1602 #ifdef HAVE_CSSMERRORSTRING
1603 message
= cssmErrorString(error
);
1605 message
= _("Unable to establish a secure connection to host.");
1606 #endif /* HAVE_CSSMERRORSTRING */
1608 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
1618 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1622 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1624 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
1627 CFRelease(http
->tls
);
1629 if (http
->tls_credentials
)
1630 CFRelease(http
->tls_credentials
);
1633 http
->tls_credentials
= NULL
;
1638 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1641 int /* O - Bytes written */
1642 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1643 const char *buf
, /* I - Buffer holding data */
1644 int len
) /* I - Length of buffer */
1646 ssize_t result
; /* Return value */
1647 OSStatus error
; /* Error info */
1648 size_t processed
; /* Number of bytes processed */
1651 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http
, (void *)buf
, len
));
1653 error
= SSLWrite(http
->tls
, buf
, (size_t)len
, &processed
);
1658 result
= (int)processed
;
1661 case errSSLWouldBlock
:
1664 result
= (int)processed
;
1673 case errSSLClosedGraceful
:
1677 result
= (int)processed
;
1687 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result
));
1689 return ((int)result
);
1694 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1697 static CFArrayRef
/* O - Array of certificates or NULL */
1698 http_cdsa_copy_server(
1699 const char *common_name
) /* I - Server's hostname */
1701 #ifdef HAVE_SECKEYCHAINOPEN
1702 OSStatus err
; /* Error info */
1703 SecIdentityRef identity
= NULL
;/* Identity */
1704 CFArrayRef certificates
= NULL
;
1705 /* Certificate array */
1706 SecPolicyRef policy
= NULL
; /* Policy ref */
1707 CFStringRef cfcommon_name
= NULL
;
1709 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
1710 CFArrayRef list
= NULL
; /* Keychain list */
1711 SecKeychainRef syschain
= NULL
;/* System keychain */
1714 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name
));
1716 cfcommon_name
= CFStringCreateWithCString(kCFAllocatorDefault
, common_name
, kCFStringEncodingUTF8
);
1718 policy
= SecPolicyCreateSSL(1, cfcommon_name
);
1722 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
1726 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
)))
1728 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
1732 _cupsMutexLock(&tls_mutex
);
1734 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
1735 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
1736 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
1737 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
1739 syschain
= http_cdsa_open_system_keychain();
1743 const void *values
[2] = { syschain
, tls_keychain
};
1745 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)values
, 2, &kCFTypeArrayCallBacks
);
1748 list
= CFArrayCreate(kCFAllocatorDefault
, (const void **)&tls_keychain
, 1, &kCFTypeArrayCallBacks
);
1750 CFDictionaryAddValue(query
, kSecMatchSearchList
, list
);
1753 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
1755 _cupsMutexUnlock(&tls_mutex
);
1759 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err
));
1763 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
1765 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
1769 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
)) == NULL
)
1771 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
1778 CFRelease(syschain
);
1780 CFRelease(identity
);
1784 CFRelease(cfcommon_name
);
1788 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates
));
1790 return (certificates
);
1793 if (!tls_selfsigned
)
1796 return (CFArrayCreate(NULL
, (const void **)&tls_selfsigned
, 1, &kCFTypeArrayCallBacks
));
1797 #endif /* HAVE_SECKEYCHAINOPEN */
1802 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1805 static SecCertificateRef
/* O - Certificate */
1806 http_cdsa_create_credential(
1807 http_credential_t
*credential
) /* I - Credential */
1812 return (SecCertificateCreateWithBytes(kCFAllocatorDefault
, credential
->data
, (CFIndex
)credential
->datalen
));
1816 #ifdef HAVE_SECKEYCHAINOPEN
1818 * 'http_cdsa_default_path()' - Get the default keychain path.
1821 static const char * /* O - Keychain path */
1822 http_cdsa_default_path(char *buffer
, /* I - Path buffer */
1823 size_t bufsize
) /* I - Size of buffer */
1825 const char *home
= getenv("HOME"); /* HOME environment variable */
1829 * Determine the default keychain path. Note that the login and system
1830 * keychains are no longer accessible to user applications starting in macOS
1831 * 10.11.4 (!), so we need to create our own keychain just for CUPS.
1834 if (getuid() && home
)
1835 snprintf(buffer
, bufsize
, "%s/.cups/ssl.keychain", home
);
1837 strlcpy(buffer
, "/etc/cups/ssl.keychain", bufsize
);
1839 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer
));
1846 * 'http_cdsa_open_keychain()' - Open (or create) a keychain.
1849 static SecKeychainRef
/* O - Keychain or NULL */
1850 http_cdsa_open_keychain(
1851 const char *path
, /* I - Path to keychain */
1852 char *filename
, /* I - Keychain filename */
1853 size_t filesize
) /* I - Size of filename buffer */
1855 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
1856 OSStatus err
; /* Error code */
1857 Boolean interaction
; /* Interaction allowed? */
1858 SecKeychainStatus status
= 0; /* Keychain status */
1862 * Get the keychain filename...
1866 path
= http_cdsa_default_path(filename
, filesize
);
1868 strlcpy(filename
, path
, filesize
);
1871 * Save the interaction setting and disable while we open the keychain...
1874 SecKeychainGetUserInteractionAllowed(&interaction
);
1875 SecKeychainSetUserInteractionAllowed(FALSE
);
1877 if (access(path
, R_OK
))
1880 * Create a new keychain at the given path...
1883 err
= SecKeychainCreate(path
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, FALSE
, NULL
, &keychain
);
1888 * Open the existing keychain and unlock as needed...
1891 err
= SecKeychainOpen(path
, &keychain
);
1894 err
= SecKeychainGetStatus(keychain
, &status
);
1896 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
))
1897 err
= SecKeychainUnlock(keychain
, _CUPS_CDSA_PASSLEN
, _CUPS_CDSA_PASSWORD
, TRUE
);
1901 * Restore interaction setting...
1904 SecKeychainSetUserInteractionAllowed(interaction
);
1907 * Release the keychain if we had any errors...
1912 /* TODO: Set cups last error string */
1913 DEBUG_printf(("4http_cdsa_open_keychain: Unable to open keychain (%d), returning NULL.", (int)err
));
1917 CFRelease(keychain
);
1923 * Return the keychain or NULL...
1931 * 'http_cdsa_open_system_keychain()' - Open the System keychain.
1934 static SecKeychainRef
1935 http_cdsa_open_system_keychain(void)
1937 SecKeychainRef keychain
= NULL
;/* Temporary keychain */
1938 OSStatus err
; /* Error code */
1939 Boolean interaction
; /* Interaction allowed? */
1940 SecKeychainStatus status
= 0; /* Keychain status */
1944 * Save the interaction setting and disable while we open the keychain...
1947 SecKeychainGetUserInteractionAllowed(&interaction
);
1948 SecKeychainSetUserInteractionAllowed(TRUE
);
1950 err
= SecKeychainOpen("/Library/Keychains/System.keychain", &keychain
);
1953 err
= SecKeychainGetStatus(keychain
, &status
);
1955 if (err
== noErr
&& !(status
& kSecUnlockStateStatus
))
1956 err
= errSecInteractionNotAllowed
;
1959 * Restore interaction setting...
1962 SecKeychainSetUserInteractionAllowed(interaction
);
1965 * Release the keychain if we had any errors...
1970 /* TODO: Set cups last error string */
1971 DEBUG_printf(("4http_cdsa_open_system_keychain: Unable to open keychain (%d), returning NULL.", (int)err
));
1975 CFRelease(keychain
);
1981 * Return the keychain or NULL...
1986 #endif /* HAVE_SECKEYCHAINOPEN */
1990 * 'http_cdsa_read()' - Read function for the CDSA library.
1993 static OSStatus
/* O - -1 on error, 0 on success */
1995 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1996 void *data
, /* I - Data buffer */
1997 size_t *dataLength
) /* IO - Number of bytes */
1999 OSStatus result
; /* Return value */
2000 ssize_t bytes
; /* Number of bytes read */
2001 http_t
*http
; /* HTTP connection */
2004 http
= (http_t
*)connection
;
2006 if (!http
->blocking
)
2009 * Make sure we have data before we read...
2012 while (!_httpWait(http
, http
->wait_value
, 0))
2014 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2017 http
->error
= ETIMEDOUT
;
2024 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2026 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2028 if ((size_t)bytes
== *dataLength
)
2034 *dataLength
= (size_t)bytes
;
2035 result
= errSSLWouldBlock
;
2042 result
= errSSLClosedGraceful
;
2043 else if (errno
== EAGAIN
)
2044 result
= errSSLWouldBlock
;
2046 result
= errSSLClosedAbort
;
2054 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
2057 static int /* O - Status of connection */
2058 http_cdsa_set_credentials(http_t
*http
) /* I - HTTP connection */
2060 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2061 OSStatus error
= 0; /* Error code */
2062 http_tls_credentials_t credentials
= NULL
;
2063 /* TLS credentials */
2066 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http
));
2069 * Prefer connection specific credentials...
2072 if ((credentials
= http
->tls_credentials
) == NULL
)
2073 credentials
= cg
->tls_credentials
;
2077 error
= SSLSetCertificate(http
->tls
, credentials
);
2078 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
2082 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
2089 * 'http_cdsa_write()' - Write function for the CDSA library.
2092 static OSStatus
/* O - -1 on error, 0 on success */
2094 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2095 const void *data
, /* I - Data buffer */
2096 size_t *dataLength
) /* IO - Number of bytes */
2098 OSStatus result
; /* Return value */
2099 ssize_t bytes
; /* Number of bytes read */
2100 http_t
*http
; /* HTTP connection */
2103 http
= (http_t
*)connection
;
2107 bytes
= write(http
->fd
, data
, *dataLength
);
2109 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2111 if ((size_t)bytes
== *dataLength
)
2115 else if (bytes
>= 0)
2117 *dataLength
= (size_t)bytes
;
2118 result
= errSSLWouldBlock
;
2124 if (errno
== EAGAIN
)
2125 result
= errSSLWouldBlock
;
2127 result
= errSSLClosedAbort
;