]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/tls-darwin.c
Update all references to OS X to macOS.
[thirdparty/cups.git] / cups / tls-darwin.c
CommitLineData
2c85b752 1/*
8072030b 2 * TLS support code for CUPS on macOS.
2c85b752 3 *
1ae693e3 4 * Copyright 2007-2016 by Apple Inc.
2c85b752
MS
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
6 *
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/".
12 *
13 * This file is subject to the Apple OS-Developed Software exception.
14 */
15
ebb24a07 16/**** This file is included from tls.c ****/
2c85b752
MS
17
18/*
dafebafd 19 * Include necessary headers...
2c85b752
MS
20 */
21
dafebafd
MS
22#include <spawn.h>
23
24extern char **environ;
25
26
c0459938
MS
27/*
28 * Local globals...
29 */
30
c0459938
MS
31static int tls_auto_create = 0;
32 /* Auto-create self-signed certs? */
33static char *tls_common_name = NULL;
34 /* Default common name */
fc4bbb58 35#ifdef HAVE_SECKEYCHAINOPEN
41e0907c
MS
36static SecKeychainRef tls_keychain = NULL;
37 /* Server cert keychain */
2274d26b
MS
38#else
39static SecIdentityRef tls_selfsigned = NULL;
40 /* Temporary self-signed cert */
fc4bbb58 41#endif /* HAVE_SECKEYCHAINOPEN */
41e0907c
MS
42static char *tls_keypath = NULL;
43 /* Server cert keychain path */
44static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER;
45 /* Mutex for keychain/certs */
4492316e 46static int tls_options = -1;/* Options for TLS connections */
c0459938
MS
47
48
dafebafd
MS
49/*
50 * Local functions...
51 */
2c85b752 52
41e0907c 53static CFArrayRef http_cdsa_copy_server(const char *common_name);
2ece34a9 54static SecCertificateRef http_cdsa_create_credential(http_credential_t *credential);
fc4bbb58 55#ifdef HAVE_SECKEYCHAINOPEN
005f7f1f 56static const char *http_cdsa_default_path(char *buffer, size_t bufsize);
fc4bbb58 57#endif /* HAVE_SECKEYCHAINOPEN */
41e0907c 58static OSStatus http_cdsa_read(SSLConnectionRef connection, void *data, size_t *dataLength);
88f1e9c8 59static int http_cdsa_set_credentials(http_t *http);
41e0907c 60static OSStatus http_cdsa_write(SSLConnectionRef connection, const void *data, size_t *dataLength);
2c85b752
MS
61
62
3af9ac9e
MS
63/*
64 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
65 *
e1f19878 66 * @since CUPS 2.0/OS 10.10@
3af9ac9e
MS
67 */
68
69int /* O - 1 on success, 0 on failure */
70cupsMakeServerCredentials(
f93b32b6 71 const char *path, /* I - Keychain path or @code NULL@ for default */
3af9ac9e
MS
72 const char *common_name, /* I - Common name */
73 int num_alt_names, /* I - Number of subject alternate names */
74 const char **alt_names, /* I - Subject Alternate Names */
75 time_t expiration_date) /* I - Expiration date */
76{
fc4bbb58 77#if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
41e0907c
MS
78 int status = 0; /* Return status */
79 OSStatus err; /* Error code (if any) */
80 CFStringRef cfcommon_name = NULL;
81 /* CF string for server name */
82 SecIdentityRef ident = NULL; /* Identity */
83 SecKeyRef publicKey = NULL,
84 /* Public key */
85 privateKey = NULL;
86 /* Private key */
558883c6 87 SecCertificateRef cert = NULL; /* Self-signed certificate */
41e0907c
MS
88 CFMutableDictionaryRef keyParams = NULL;
89 /* Key generation parameters */
90
91
172bdf5d
MS
92 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
93
fc4bbb58 94 (void)path;
3af9ac9e
MS
95 (void)num_alt_names;
96 (void)alt_names;
97 (void)expiration_date;
98
fc4bbb58
MS
99 if (path)
100 {
101 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
102 return (0);
103 }
f93b32b6 104
2274d26b
MS
105 if (tls_selfsigned)
106 {
107 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
108 return (1);
109 }
110
f93b32b6 111 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
41e0907c 112 if (!cfcommon_name)
2274d26b
MS
113 {
114 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
41e0907c 115 goto cleanup;
2274d26b 116 }
41e0907c
MS
117
118 /*
119 * Create a public/private key pair...
120 */
121
f93b32b6 122 keyParams = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
41e0907c 123 if (!keyParams)
2274d26b
MS
124 {
125 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
41e0907c 126 goto cleanup;
2274d26b 127 }
41e0907c 128
1a7059a0 129 CFDictionaryAddValue(keyParams, kSecAttrKeyType, kSecAttrKeyTypeRSA);
41e0907c 130 CFDictionaryAddValue(keyParams, kSecAttrKeySizeInBits, CFSTR("2048"));
2274d26b 131 CFDictionaryAddValue(keyParams, kSecAttrLabel, cfcommon_name);
41e0907c
MS
132
133 err = SecKeyGeneratePair(keyParams, &publicKey, &privateKey);
134 if (err != noErr)
2274d26b
MS
135 {
136 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err));
41e0907c 137 goto cleanup;
2274d26b 138 }
41e0907c
MS
139
140 /*
141 * Create a self-signed certificate using the public/private key pair...
142 */
143
144 CFIndex usageInt = kSecKeyUsageAll;
558883c6
MS
145 CFNumberRef usage = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &usageInt);
146 CFIndex lenInt = 0;
147 CFNumberRef len = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &lenInt);
fc4bbb58
MS
148 CFTypeRef certKeys[] = { kSecCSRBasicContraintsPathLen, kSecSubjectAltName, kSecCertificateKeyUsage };
149 CFTypeRef certValues[] = { len, cfcommon_name, usage };
150 CFDictionaryRef certParams = CFDictionaryCreate(kCFAllocatorDefault, certKeys, certValues, sizeof(certKeys) / sizeof(certKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
41e0907c 151 CFRelease(usage);
558883c6 152 CFRelease(len);
41e0907c
MS
153
154 const void *ca_o[] = { kSecOidOrganization, CFSTR("") };
155 const void *ca_cn[] = { kSecOidCommonName, cfcommon_name };
156 CFArrayRef ca_o_dn = CFArrayCreate(kCFAllocatorDefault, ca_o, 2, NULL);
157 CFArrayRef ca_cn_dn = CFArrayCreate(kCFAllocatorDefault, ca_cn, 2, NULL);
158 const void *ca_dn_array[2];
159
160 ca_dn_array[0] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_o_dn, 1, NULL);
161 ca_dn_array[1] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_cn_dn, 1, NULL);
162
163 CFArrayRef subject = CFArrayCreate(kCFAllocatorDefault, ca_dn_array, 2, NULL);
fc4bbb58 164
558883c6 165 cert = SecGenerateSelfSignedCertificate(subject, certParams, publicKey, privateKey);
fc4bbb58 166
41e0907c
MS
167 CFRelease(subject);
168 CFRelease(certParams);
169
170 if (!cert)
2274d26b
MS
171 {
172 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
41e0907c 173 goto cleanup;
2274d26b 174 }
41e0907c
MS
175
176 ident = SecIdentityCreate(kCFAllocatorDefault, cert, privateKey);
177
178 if (ident)
fc4bbb58 179 {
2274d26b
MS
180 _cupsMutexLock(&tls_mutex);
181
182 if (tls_selfsigned)
183 CFRelease(ident);
184 else
185 tls_selfsigned = ident;
186
187 _cupsMutexLock(&tls_mutex);
188
189# if 0 /* Someday perhaps SecItemCopyMatching will work for identities, at which point */
fc4bbb58
MS
190 CFTypeRef itemKeys[] = { kSecClass, kSecAttrLabel, kSecValueRef };
191 CFTypeRef itemValues[] = { kSecClassIdentity, cfcommon_name, ident };
192 CFDictionaryRef itemAttrs = CFDictionaryCreate(kCFAllocatorDefault, itemKeys, itemValues, sizeof(itemKeys) / sizeof(itemKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
193
194 err = SecItemAdd(itemAttrs, NULL);
e34d1ec4 195 /* SecItemAdd consumes itemAttrs... */
fc4bbb58 196
2274d26b
MS
197 CFRelease(ident);
198
fc4bbb58 199 if (err != noErr)
2274d26b
MS
200 {
201 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err));
fc4bbb58 202 goto cleanup;
2274d26b
MS
203 }
204# endif /* 0 */
fc4bbb58 205
41e0907c 206 status = 1;
fc4bbb58 207 }
2274d26b
MS
208 else
209 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
41e0907c
MS
210
211 /*
212 * Cleanup and return...
213 */
214
215cleanup:
216
217 if (cfcommon_name)
218 CFRelease(cfcommon_name);
219
220 if (keyParams)
221 CFRelease(keyParams);
222
41e0907c
MS
223 if (cert)
224 CFRelease(cert);
225
226 if (publicKey)
227 CFRelease(publicKey);
228
229 if (privateKey)
2274d26b
MS
230 CFRelease(privateKey);
231
232 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status));
41e0907c
MS
233
234 return (status);
235
fc4bbb58 236#else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
41e0907c 237 int pid, /* Process ID of command */
7d58a105
MS
238 status, /* Status of command */
239 i; /* Looping var */
41e0907c 240 char command[1024], /* Command */
724f2615 241 *argv[5], /* Command-line arguments */
7d58a105
MS
242 *envp[1000], /* Environment variables */
243 days[32], /* CERTTOOL_EXPIRATION_DAYS env var */
41e0907c 244 keychain[1024], /* Keychain argument */
f93b32b6
MS
245 infofile[1024], /* Type-in information for cert */
246 filename[1024]; /* Default keychain path */
41e0907c
MS
247 cups_file_t *fp; /* Seed/info file */
248
249
807315e6 250 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, (void *)alt_names, (int)expiration_date));
172bdf5d 251
41e0907c
MS
252 (void)num_alt_names;
253 (void)alt_names;
41e0907c 254
f93b32b6 255 if (!path)
005f7f1f 256 path = http_cdsa_default_path(filename, sizeof(filename));
f93b32b6 257
41e0907c
MS
258 /*
259 * Run the "certtool" command to generate a self-signed certificate...
260 */
261
262 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
263 return (-1);
264
265 /*
266 * Create a file with the certificate information fields...
267 *
268 * Note: This assumes that the default questions are asked by the certtool
269 * command...
270 */
271
272 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
273 return (-1);
274
275 cupsFilePrintf(fp,
276 "CUPS Self-Signed Certificate\n"
277 /* Enter key and certificate label */
724f2615 278 "r\n" /* Generate RSA key pair */
1ae693e3 279 "2048\n" /* 2048 bit encryption key */
41e0907c
MS
280 "y\n" /* OK (y = yes) */
281 "b\n" /* Usage (b=signing/encryption) */
1ae693e3 282 "2\n" /* Sign with SHA256 */
41e0907c
MS
283 "y\n" /* OK (y = yes) */
284 "%s\n" /* Common name */
285 "\n" /* Country (default) */
286 "\n" /* Organization (default) */
287 "\n" /* Organizational unit (default) */
288 "\n" /* State/Province (default) */
289 "\n" /* Email address */
290 "y\n", /* OK (y = yes) */
291 common_name);
292 cupsFileClose(fp);
293
294 snprintf(keychain, sizeof(keychain), "k=%s", path);
295
296 argv[0] = "certtool";
297 argv[1] = "c";
298 argv[2] = keychain;
299 argv[3] = NULL;
300
7d58a105
MS
301 snprintf(days, sizeof(days), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date - time(NULL) + 86399) / 86400));
302 envp[0] = days;
303 for (i = 0; i < (int)(sizeof(envp) / sizeof(envp[0]) - 2) && environ[i]; i ++)
304 envp[i + 1] = environ[i];
305 envp[i] = NULL;
306
41e0907c
MS
307 posix_spawn_file_actions_t actions; /* File actions */
308
309 posix_spawn_file_actions_init(&actions);
310 posix_spawn_file_actions_addclose(&actions, 0);
311 posix_spawn_file_actions_addopen(&actions, 0, infofile, O_RDONLY, 0);
f93b32b6
MS
312 posix_spawn_file_actions_addclose(&actions, 1);
313 posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0);
314 posix_spawn_file_actions_addclose(&actions, 2);
315 posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
41e0907c 316
7d58a105 317 if (posix_spawn(&pid, command, &actions, NULL, argv, envp))
41e0907c
MS
318 {
319 unlink(infofile);
320 return (-1);
321 }
322
323 posix_spawn_file_actions_destroy(&actions);
324
325 unlink(infofile);
326
327 while (waitpid(pid, &status, 0) < 0)
328 if (errno != EINTR)
329 {
330 status = -1;
331 break;
332 }
333
334 return (!status);
eb66bc71 335#endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
3af9ac9e
MS
336}
337
338
339/*
340 * 'cupsSetServerCredentials()' - Set the default server credentials.
341 *
342 * Note: The server credentials are used by all threads in the running process.
343 * This function is threadsafe.
344 *
8072030b 345 * @since CUPS 2.0/macOS 10.10@
3af9ac9e
MS
346 */
347
348int /* O - 1 on success, 0 on failure */
349cupsSetServerCredentials(
f93b32b6 350 const char *path, /* I - Keychain path or @code NULL@ for default */
3af9ac9e
MS
351 const char *common_name, /* I - Default common name for server */
352 int auto_create) /* I - 1 = automatically create self-signed certificates */
353{
a27a134a
MS
354 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
355
eb66bc71 356#ifdef HAVE_SECKEYCHAINOPEN
f93b32b6 357 char filename[1024]; /* Filename for keychain */
c0459938 358 SecKeychainRef keychain = NULL;/* Temporary keychain */
fcea7df4 359 OSStatus status; /* Status code */
3af9ac9e 360
c0459938 361
f93b32b6 362 if (!path)
005f7f1f 363 path = http_cdsa_default_path(filename, sizeof(filename));
f93b32b6 364
fcea7df4 365 if ((status = SecKeychainOpen(path, &keychain)) != noErr)
c0459938
MS
366 {
367 /* TODO: Set cups last error string */
fcea7df4 368 DEBUG_printf(("1cupsSetServerCredentials: Unable to open keychain (%d), returning 0.", (int)status));
c0459938
MS
369 return (0);
370 }
371
372 _cupsMutexLock(&tls_mutex);
373
374 /*
375 * Close any keychain that is currently open...
376 */
377
378 if (tls_keychain)
379 CFRelease(tls_keychain);
380
41e0907c
MS
381 if (tls_keypath)
382 _cupsStrFree(tls_keypath);
383
c0459938
MS
384 if (tls_common_name)
385 _cupsStrFree(tls_common_name);
386
387 /*
388 * Save the new keychain...
389 */
390
391 tls_keychain = keychain;
41e0907c 392 tls_keypath = _cupsStrAlloc(path);
c0459938
MS
393 tls_auto_create = auto_create;
394 tls_common_name = _cupsStrAlloc(common_name);
395
396 _cupsMutexUnlock(&tls_mutex);
397
a27a134a 398 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
c0459938 399 return (1);
eb66bc71
MS
400
401#else
fc4bbb58
MS
402 if (path)
403 {
404 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
405 return (0);
406 }
407
408 tls_auto_create = auto_create;
409 tls_common_name = _cupsStrAlloc(common_name);
410
411 return (1);
eb66bc71 412#endif /* HAVE_SECKEYCHAINOPEN */
3af9ac9e
MS
413}
414
2c85b752
MS
415
416/*
417 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
418 * an encrypted connection.
419 *
8072030b 420 * @since CUPS 1.5/macOS 10.7@
2c85b752
MS
421 */
422
423int /* O - Status of call (0 = success) */
424httpCopyCredentials(
425 http_t *http, /* I - Connection to server */
426 cups_array_t **credentials) /* O - Array of credentials */
427{
428 OSStatus error; /* Error code */
429 SecTrustRef peerTrust; /* Peer trust reference */
430 CFIndex count; /* Number of credentials */
431 SecCertificateRef secCert; /* Certificate reference */
432 CFDataRef data; /* Certificate data */
433 int i; /* Looping var */
434
435
807315e6 436 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http, (void *)credentials));
376d7c69 437
2c85b752
MS
438 if (credentials)
439 *credentials = NULL;
440
441 if (!http || !http->tls || !credentials)
442 return (-1);
443
444 if (!(error = SSLCopyPeerTrust(http->tls, &peerTrust)) && peerTrust)
445 {
376d7c69
MS
446 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust)));
447
2c85b752
MS
448 if ((*credentials = cupsArrayNew(NULL, NULL)) != NULL)
449 {
450 count = SecTrustGetCertificateCount(peerTrust);
451
452 for (i = 0; i < count; i ++)
453 {
454 secCert = SecTrustGetCertificateAtIndex(peerTrust, i);
376d7c69
MS
455
456#ifdef DEBUG
457 CFStringRef cf_name = SecCertificateCopySubjectSummary(secCert);
458 char name[1024];
459 if (cf_name)
460 CFStringGetCString(cf_name, name, sizeof(name), kCFStringEncodingUTF8);
461 else
462 strlcpy(name, "unknown", sizeof(name));
463
464 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i, name));
465#endif /* DEBUG */
466
88f1e9c8 467 if ((data = SecCertificateCopyData(secCert)) != NULL)
2c85b752 468 {
376d7c69
MS
469 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
470
7e86f2f6 471 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
2c85b752
MS
472 CFRelease(data);
473 }
474 }
475 }
476
477 CFRelease(peerTrust);
478 }
479
480 return (error);
481}
482
483
484/*
485 * '_httpCreateCredentials()' - Create credentials in the internal format.
486 */
487
488http_tls_credentials_t /* O - Internal credentials */
489_httpCreateCredentials(
490 cups_array_t *credentials) /* I - Array of credentials */
491{
492 CFMutableArrayRef peerCerts; /* Peer credentials reference */
493 SecCertificateRef secCert; /* Certificate reference */
2c85b752
MS
494 http_credential_t *credential; /* Credential data */
495
496
497 if (!credentials)
498 return (NULL);
499
500 if ((peerCerts = CFArrayCreateMutable(kCFAllocatorDefault,
501 cupsArrayCount(credentials),
502 &kCFTypeArrayCallBacks)) == NULL)
503 return (NULL);
504
505 for (credential = (http_credential_t *)cupsArrayFirst(credentials);
506 credential;
507 credential = (http_credential_t *)cupsArrayNext(credentials))
508 {
9653cfdf 509 if ((secCert = http_cdsa_create_credential(credential)) != NULL)
2c85b752 510 {
9653cfdf
MS
511 CFArrayAppendValue(peerCerts, secCert);
512 CFRelease(secCert);
2c85b752
MS
513 }
514 }
515
516 return (peerCerts);
517}
518
519
3af9ac9e 520/*
524c65e6 521 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
3af9ac9e 522 *
8072030b 523 * @since CUPS 2.0/macOS 10.10@
3af9ac9e
MS
524 */
525
524c65e6
MS
526int /* O - 1 if valid, 0 otherwise */
527httpCredentialsAreValidForName(
528 cups_array_t *credentials, /* I - Credentials */
529 const char *common_name) /* I - Name to check */
530{
531 SecCertificateRef secCert; /* Certificate reference */
532 CFStringRef cfcert_name = NULL;
533 /* Certificate's common name (CF string) */
534 char cert_name[256]; /* Certificate's common name (C string) */
535 int valid = 1; /* Valid name? */
536
537
538 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
539 return (0);
540
541 /*
542 * Compare the common names...
543 */
544
545 if ((cfcert_name = SecCertificateCopySubjectSummary(secCert)) == NULL)
546 {
547 /*
548 * Can't get common name, cannot be valid...
549 */
550
551 valid = 0;
552 }
553 else if (CFStringGetCString(cfcert_name, cert_name, sizeof(cert_name), kCFStringEncodingUTF8) &&
554 _cups_strcasecmp(common_name, cert_name))
555 {
556 /*
557 * Not an exact match for the common name, check for wildcard certs...
558 */
559
560 const char *domain = strchr(common_name, '.');
561 /* Domain in common name */
562
563 if (strncmp(cert_name, "*.", 2) || !domain || _cups_strcasecmp(domain, cert_name + 1))
564 {
565 /*
566 * Not a wildcard match.
567 */
568
569 /* TODO: Check subject alternate names */
570 valid = 0;
571 }
572 }
573
574 if (cfcert_name)
575 CFRelease(cfcert_name);
576
577 CFRelease(secCert);
578
579 return (valid);
580}
581
582
583/*
584 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
585 *
8072030b 586 * @since CUPS 2.0/macOS 10.10@
524c65e6
MS
587 */
588
589http_trust_t /* O - Level of trust */
590httpCredentialsGetTrust(
376d7c69
MS
591 cups_array_t *credentials, /* I - Credentials */
592 const char *common_name) /* I - Common name for trust lookup */
3af9ac9e 593{
9653cfdf 594 SecCertificateRef secCert; /* Certificate reference */
524c65e6
MS
595 http_trust_t trust = HTTP_TRUST_OK;
596 /* Trusted? */
376d7c69 597 cups_array_t *tcreds = NULL; /* Trusted credentials */
9653cfdf
MS
598 _cups_globals_t *cg = _cupsGlobals();
599 /* Per-thread globals */
3af9ac9e 600
9653cfdf 601
376d7c69 602 if (!common_name)
524c65e6 603 return (HTTP_TRUST_UNKNOWN);
376d7c69 604
9653cfdf 605 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
524c65e6 606 return (HTTP_TRUST_UNKNOWN);
9653cfdf 607
3abb875b
MS
608 if (cg->any_root < 0)
609 _cupsSetDefaults();
610
376d7c69 611 /*
88f1e9c8 612 * Look this common name up in the default keychains...
376d7c69
MS
613 */
614
88f1e9c8 615 httpLoadCredentials(NULL, &tcreds, common_name);
376d7c69
MS
616
617 if (tcreds)
618 {
619 char credentials_str[1024], /* String for incoming credentials */
620 tcreds_str[1024]; /* String for saved credentials */
621
622 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
623 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
624
625 if (strcmp(credentials_str, tcreds_str))
626 {
627 /*
628 * Credentials don't match, let's look at the expiration date of the new
629 * credentials and allow if the new ones have a later expiration...
630 */
631
08d56b1f
MS
632 if (!cg->trust_first)
633 {
634 /*
635 * Do not trust certificates on first use...
636 */
637
638 trust = HTTP_TRUST_INVALID;
639 }
640 else if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds) || !httpCredentialsAreValidForName(credentials, common_name))
376d7c69
MS
641 {
642 /*
643 * Either the new credentials are not newly issued, or the common name
644 * does not match the issued certificate...
645 */
646
524c65e6 647 trust = HTTP_TRUST_INVALID;
376d7c69 648 }
524c65e6 649 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
376d7c69
MS
650 {
651 /*
524c65e6 652 * Save the renewed credentials...
376d7c69
MS
653 */
654
524c65e6
MS
655 trust = HTTP_TRUST_RENEWED;
656
657 httpSaveCredentials(NULL, credentials, common_name);
376d7c69
MS
658 }
659 }
660
661 httpFreeCredentials(tcreds);
662 }
f51f3773 663 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
524c65e6 664 trust = HTTP_TRUST_INVALID;
376d7c69 665
9653cfdf 666 if (!cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
524c65e6 667 trust = HTTP_TRUST_EXPIRED;
25731360 668 else if (!cg->any_root && cupsArrayCount(credentials) == 1)
524c65e6 669 trust = HTTP_TRUST_INVALID;
08d56b1f
MS
670 else if (!cg->trust_first)
671 trust = HTTP_TRUST_INVALID;
376d7c69 672
9653cfdf
MS
673 CFRelease(secCert);
674
524c65e6 675 return (trust);
3af9ac9e
MS
676}
677
678
679/*
680 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
681 *
8072030b 682 * @since CUPS 2.0/macOS 10.10@
3af9ac9e
MS
683 */
684
685time_t /* O - Expiration date of credentials */
686httpCredentialsGetExpiration(
687 cups_array_t *credentials) /* I - Credentials */
688{
9653cfdf
MS
689 SecCertificateRef secCert; /* Certificate reference */
690 time_t expiration; /* Expiration date */
3af9ac9e 691
9653cfdf
MS
692
693 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
694 return (0);
695
376d7c69 696 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
9653cfdf
MS
697
698 CFRelease(secCert);
699
700 return (expiration);
3af9ac9e
MS
701}
702
703
72d05bc9
MS
704/*
705 * 'httpCredentialsString()' - Return a string representing the credentials.
706 *
8072030b 707 * @since CUPS 2.0/macOS 10.10@
72d05bc9
MS
708 */
709
710size_t /* O - Total size of credentials string */
711httpCredentialsString(
712 cups_array_t *credentials, /* I - Credentials */
713 char *buffer, /* I - Buffer or @code NULL@ */
714 size_t bufsize) /* I - Size of buffer */
715{
376d7c69 716 http_credential_t *first; /* First certificate */
9653cfdf 717 SecCertificateRef secCert; /* Certificate reference */
9653cfdf
MS
718
719
807315e6 720 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", (void *)credentials, (void *)buffer, CUPS_LLCAST bufsize));
376d7c69 721
9653cfdf
MS
722 if (!buffer)
723 return (0);
72d05bc9
MS
724
725 if (buffer && bufsize > 0)
726 *buffer = '\0';
727
376d7c69
MS
728 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
729 (secCert = http_cdsa_create_credential(first)) != NULL)
9653cfdf 730 {
376d7c69
MS
731 CFStringRef cf_name; /* CF common name string */
732 char name[256]; /* Common name associated with cert */
733 time_t expiration; /* Expiration date of cert */
734 _cups_md5_state_t md5_state; /* MD5 state */
735 unsigned char md5_digest[16]; /* MD5 result */
736
737 if ((cf_name = SecCertificateCopySubjectSummary(secCert)) != NULL)
9653cfdf 738 {
376d7c69
MS
739 CFStringGetCString(cf_name, name, (CFIndex)sizeof(name), kCFStringEncodingUTF8);
740 CFRelease(cf_name);
9653cfdf 741 }
376d7c69
MS
742 else
743 strlcpy(name, "unknown", sizeof(name));
744
745 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
746
747 _cupsMD5Init(&md5_state);
748 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
749 _cupsMD5Finish(&md5_state, md5_digest);
750
751 snprintf(buffer, bufsize, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, httpGetDateString(expiration), md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
9653cfdf
MS
752
753 CFRelease(secCert);
754 }
755
376d7c69
MS
756 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
757
9653cfdf 758 return (strlen(buffer));
72d05bc9
MS
759}
760
761
2c85b752
MS
762/*
763 * '_httpFreeCredentials()' - Free internal credentials.
764 */
765
766void
767_httpFreeCredentials(
768 http_tls_credentials_t credentials) /* I - Internal credentials */
769{
770 if (!credentials)
771 return;
772
773 CFRelease(credentials);
774}
775
776
72d05bc9
MS
777/*
778 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
779 *
e1f19878 780 * @since CUPS 2.0/OS 10.10@
72d05bc9
MS
781 */
782
dafebafd 783int /* O - 0 on success, -1 on error */
72d05bc9 784httpLoadCredentials(
f93b32b6 785 const char *path, /* I - Keychain path or @code NULL@ for default */
72d05bc9
MS
786 cups_array_t **credentials, /* IO - Credentials */
787 const char *common_name) /* I - Common name for credentials */
788{
dafebafd 789 OSStatus err; /* Error info */
fc4bbb58 790#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 791 char filename[1024]; /* Filename for keychain */
dafebafd 792 SecKeychainRef keychain = NULL;/* Keychain reference */
fc4bbb58
MS
793 CFArrayRef list; /* Keychain list */
794#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8
MS
795 SecCertificateRef cert = NULL; /* Certificate */
796 CFDataRef data; /* Certificate data */
dafebafd
MS
797 SecPolicyRef policy = NULL; /* Policy ref */
798 CFStringRef cfcommon_name = NULL;
799 /* Server name */
800 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
dafebafd
MS
801
802
807315e6 803 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
88f1e9c8
MS
804
805 if (!credentials)
806 return (-1);
807
808 *credentials = NULL;
809
fc4bbb58 810#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 811 if (!path)
005f7f1f 812 path = http_cdsa_default_path(filename, sizeof(filename));
88f1e9c8 813
88f1e9c8 814 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
dafebafd
MS
815 goto cleanup;
816
fc4bbb58
MS
817#else
818 if (path)
819 return (-1);
820#endif /* HAVE_SECKEYCHAINOPEN */
821
dafebafd
MS
822 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
823
824 policy = SecPolicyCreateSSL(1, cfcommon_name);
825
826 if (cfcommon_name)
827 CFRelease(cfcommon_name);
828
829 if (!policy)
830 goto cleanup;
831
832 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
833 goto cleanup;
834
88f1e9c8 835 CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
dafebafd
MS
836 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
837 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
838 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
dafebafd 839
fc4bbb58
MS
840#ifdef HAVE_SECKEYCHAINOPEN
841 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
842 CFDictionaryAddValue(query, kSecMatchSearchList, list);
dafebafd 843 CFRelease(list);
fc4bbb58 844#endif /* HAVE_SECKEYCHAINOPEN */
dafebafd 845
88f1e9c8 846 err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
dafebafd
MS
847
848 if (err)
849 goto cleanup;
850
88f1e9c8 851 if (CFGetTypeID(cert) != SecCertificateGetTypeID())
dafebafd
MS
852 goto cleanup;
853
88f1e9c8
MS
854 if ((data = SecCertificateCopyData(cert)) != NULL)
855 {
856 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
857
858 *credentials = cupsArrayNew(NULL, NULL);
859 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
860 CFRelease(data);
861 }
dafebafd
MS
862
863 cleanup :
864
fc4bbb58 865#ifdef HAVE_SECKEYCHAINOPEN
dafebafd
MS
866 if (keychain)
867 CFRelease(keychain);
fc4bbb58 868#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8
MS
869 if (cert)
870 CFRelease(cert);
dafebafd
MS
871 if (policy)
872 CFRelease(policy);
873 if (query)
874 CFRelease(query);
875
88f1e9c8
MS
876 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
877
878 return (*credentials ? 0 : -1);
72d05bc9
MS
879}
880
881
72d05bc9
MS
882/*
883 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
884 *
e1f19878 885 * @since CUPS 2.0/OS 10.10@
72d05bc9
MS
886 */
887
888int /* O - -1 on error, 0 on success */
889httpSaveCredentials(
f93b32b6 890 const char *path, /* I - Keychain path or @code NULL@ for default */
72d05bc9
MS
891 cups_array_t *credentials, /* I - Credentials */
892 const char *common_name) /* I - Common name for credentials */
893{
88f1e9c8 894 int ret = -1; /* Return value */
41e0907c 895 OSStatus err; /* Error info */
fc4bbb58 896#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8
MS
897 char filename[1024]; /* Filename for keychain */
898 SecKeychainRef keychain = NULL;/* Keychain reference */
fc4bbb58
MS
899 CFArrayRef list; /* Keychain list */
900#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8 901 SecCertificateRef cert = NULL; /* Certificate */
88f1e9c8 902 CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
41e0907c
MS
903
904
807315e6 905 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
88f1e9c8 906 if (!credentials)
41e0907c
MS
907 goto cleanup;
908
524c65e6
MS
909 if (!httpCredentialsAreValidForName(credentials, common_name))
910 {
911 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
912 return (-1);
913 }
914
88f1e9c8
MS
915 if ((cert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
916 {
917 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
41e0907c 918 goto cleanup;
88f1e9c8 919 }
41e0907c 920
fc4bbb58 921#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 922 if (!path)
005f7f1f 923 path = http_cdsa_default_path(filename, sizeof(filename));
2c85b752 924
88f1e9c8 925 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
2c85b752 926 {
88f1e9c8
MS
927 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err));
928 goto cleanup;
2c85b752 929 }
2c85b752 930
fc4bbb58
MS
931#else
932 if (path)
933 return (-1);
934#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8 935
88f1e9c8
MS
936 if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
937 {
938 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
939 goto cleanup;
2c85b752
MS
940 }
941
88f1e9c8 942 CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
88f1e9c8 943 CFDictionaryAddValue(attrs, kSecValueRef, cert);
fc4bbb58
MS
944
945#ifdef HAVE_SECKEYCHAINOPEN
946 if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
947 {
948 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
949 goto cleanup;
950 }
88f1e9c8 951 CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
fc4bbb58
MS
952 CFRelease(list);
953#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752 954
88f1e9c8 955 /* Note: SecItemAdd consumes "attrs"... */
524c65e6 956 err = SecItemAdd(attrs, NULL);
88f1e9c8 957 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err));
2c85b752 958
88f1e9c8 959 cleanup :
2c85b752 960
fc4bbb58 961#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8
MS
962 if (keychain)
963 CFRelease(keychain);
fc4bbb58 964#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8
MS
965 if (cert)
966 CFRelease(cert);
2c85b752 967
88f1e9c8 968 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
2c85b752 969
88f1e9c8 970 return (ret);
2c85b752
MS
971}
972
973
974/*
25731360 975 * '_httpTLSInitialize()' - Initialize the TLS stack.
2c85b752
MS
976 */
977
25731360
MS
978void
979_httpTLSInitialize(void)
2c85b752
MS
980{
981 /*
982 * Nothing to do...
983 */
984}
985
986
987/*
25731360 988 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
2c85b752
MS
989 */
990
25731360
MS
991size_t
992_httpTLSPending(http_t *http) /* I - HTTP connection */
2c85b752
MS
993{
994 size_t bytes; /* Bytes that are available */
995
996
997 if (!SSLGetBufferedReadSize(http->tls, &bytes))
998 return (bytes);
999
1000 return (0);
1001}
1002
1003
1004/*
25731360 1005 * '_httpTLSRead()' - Read from a SSL/TLS connection.
2c85b752
MS
1006 */
1007
25731360
MS
1008int /* O - Bytes read */
1009_httpTLSRead(http_t *http, /* I - HTTP connection */
2c85b752
MS
1010 char *buf, /* I - Buffer to store data */
1011 int len) /* I - Length of buffer */
1012{
1013 int result; /* Return value */
1014 OSStatus error; /* Error info */
1015 size_t processed; /* Number of bytes processed */
1016
1017
7e86f2f6 1018 error = SSLRead(http->tls, buf, (size_t)len, &processed);
25731360 1019 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error,
2c85b752
MS
1020 (int)processed));
1021 switch (error)
1022 {
1023 case 0 :
1024 result = (int)processed;
1025 break;
1026
1027 case errSSLWouldBlock :
1028 if (processed)
1029 result = (int)processed;
1030 else
1031 {
1032 result = -1;
1033 errno = EINTR;
1034 }
1035 break;
1036
1037 case errSSLClosedGraceful :
1038 default :
1039 if (processed)
1040 result = (int)processed;
1041 else
1042 {
1043 result = -1;
1044 errno = EPIPE;
1045 }
1046 break;
1047 }
1048
1049 return (result);
1050}
1051
1052
63aefcd5
MS
1053/*
1054 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1055 */
1056
1057void
1058_httpTLSSetOptions(int options) /* I - Options */
1059{
1060 tls_options = options;
1061}
1062
1063
2c85b752 1064/*
25731360 1065 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
2c85b752
MS
1066 */
1067
25731360
MS
1068int /* O - 0 on success, -1 on failure */
1069_httpTLSStart(http_t *http) /* I - HTTP connection */
2c85b752
MS
1070{
1071 char hostname[256], /* Hostname */
1072 *hostptr; /* Pointer into hostname */
1073 _cups_globals_t *cg = _cupsGlobals();
1074 /* Pointer to library globals */
1075 OSStatus error; /* Error code */
1076 const char *message = NULL;/* Error message */
1077 cups_array_t *credentials; /* Credentials array */
1078 cups_array_t *names; /* CUPS distinguished names */
1079 CFArrayRef dn_array; /* CF distinguished names array */
1080 CFIndex count; /* Number of credentials */
1081 CFDataRef data; /* Certificate data */
1082 int i; /* Looping var */
1083 http_credential_t *credential; /* Credential data */
1084
1085
807315e6 1086 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http));
b37d45d9
MS
1087
1088 if (tls_options < 0)
1089 {
1090 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1091 _cupsSetDefaults();
1092 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options));
1093 }
2c85b752 1094
c913d726 1095#ifdef HAVE_SECKEYCHAINOPEN
41e0907c 1096 if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
2c85b752 1097 {
25731360 1098 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
41e0907c
MS
1099 http->error = errno = EINVAL;
1100 http->status = HTTP_STATUS_ERROR;
1101 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
2c85b752 1102
41e0907c 1103 return (-1);
2c85b752 1104 }
2274d26b 1105#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752 1106
72d05bc9 1107 if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
2c85b752 1108 {
25731360 1109 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
2c85b752
MS
1110 http->error = errno = ENOMEM;
1111 http->status = HTTP_STATUS_ERROR;
1112 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1113
1114 return (-1);
1115 }
1116
1117 error = SSLSetConnection(http->tls, http);
25731360 1118 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error));
2c85b752
MS
1119
1120 if (!error)
1121 {
1122 error = SSLSetIOFuncs(http->tls, http_cdsa_read, http_cdsa_write);
25731360 1123 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error));
2c85b752
MS
1124 }
1125
1126 if (!error)
1127 {
1128 error = SSLSetSessionOption(http->tls, kSSLSessionOptionBreakOnServerAuth,
1129 true);
63aefcd5
MS
1130 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error));
1131 }
1132
1133 if (!error)
1134 {
ee6226a5 1135 SSLProtocol minProtocol;
4492316e 1136
ee6226a5
MS
1137 if (tls_options & _HTTP_TLS_DENY_TLS10)
1138 minProtocol = kTLSProtocol11;
1139 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1140 minProtocol = kSSLProtocol3;
1141 else
1142 minProtocol = kTLSProtocol1;
1143
1144 error = SSLSetProtocolVersionMin(http->tls, minProtocol);
1145 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol, (int)error));
63aefcd5
MS
1146 }
1147
ee6226a5 1148# if HAVE_SSLSETENABLEDCIPHERS
63aefcd5
MS
1149 if (!error)
1150 {
1151 SSLCipherSuite supported[100]; /* Supported cipher suites */
1152 size_t num_supported; /* Number of supported cipher suites */
1153 SSLCipherSuite enabled[100]; /* Cipher suites to enable */
1154 size_t num_enabled; /* Number of cipher suites to enable */
1155
1156 num_supported = sizeof(supported) / sizeof(supported[0]);
1157 error = SSLGetSupportedCiphers(http->tls, supported, &num_supported);
1158
1159 if (!error)
1160 {
1161 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported));
1162
1163 for (i = 0, num_enabled = 0; i < (int)num_supported && num_enabled < (sizeof(enabled) / sizeof(enabled[0])); i ++)
1164 {
1165 switch (supported[i])
1166 {
1167 /* Obviously insecure cipher suites that we never want to use */
1168 case SSL_NULL_WITH_NULL_NULL :
1169 case SSL_RSA_WITH_NULL_MD5 :
1170 case SSL_RSA_WITH_NULL_SHA :
1171 case SSL_RSA_EXPORT_WITH_RC4_40_MD5 :
1172 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 :
1173 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA :
1174 case SSL_RSA_WITH_DES_CBC_SHA :
1175 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA :
1176 case SSL_DH_DSS_WITH_DES_CBC_SHA :
1177 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA :
1178 case SSL_DH_RSA_WITH_DES_CBC_SHA :
1179 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA :
1180 case SSL_DHE_DSS_WITH_DES_CBC_SHA :
1181 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA :
1182 case SSL_DHE_RSA_WITH_DES_CBC_SHA :
1183 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 :
1184 case SSL_DH_anon_WITH_RC4_128_MD5 :
1185 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA :
1186 case SSL_DH_anon_WITH_DES_CBC_SHA :
1187 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA :
1188 case SSL_FORTEZZA_DMS_WITH_NULL_SHA :
1189 case TLS_DH_anon_WITH_AES_128_CBC_SHA :
1190 case TLS_DH_anon_WITH_AES_256_CBC_SHA :
1191 case TLS_ECDH_ECDSA_WITH_NULL_SHA :
1192 case TLS_ECDHE_RSA_WITH_NULL_SHA :
1193 case TLS_ECDH_anon_WITH_NULL_SHA :
1194 case TLS_ECDH_anon_WITH_RC4_128_SHA :
1195 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA :
1196 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA :
1197 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA :
1198 case TLS_RSA_WITH_NULL_SHA256 :
1199 case TLS_DH_anon_WITH_AES_128_CBC_SHA256 :
1200 case TLS_DH_anon_WITH_AES_256_CBC_SHA256 :
1201 case TLS_PSK_WITH_NULL_SHA :
1202 case TLS_DHE_PSK_WITH_NULL_SHA :
1203 case TLS_RSA_PSK_WITH_NULL_SHA :
1204 case TLS_DH_anon_WITH_AES_128_GCM_SHA256 :
1205 case TLS_DH_anon_WITH_AES_256_GCM_SHA384 :
1206 case TLS_PSK_WITH_NULL_SHA256 :
1207 case TLS_PSK_WITH_NULL_SHA384 :
1208 case TLS_DHE_PSK_WITH_NULL_SHA256 :
1209 case TLS_DHE_PSK_WITH_NULL_SHA384 :
1210 case TLS_RSA_PSK_WITH_NULL_SHA256 :
1211 case TLS_RSA_PSK_WITH_NULL_SHA384 :
1212 case SSL_RSA_WITH_DES_CBC_MD5 :
b37d45d9 1213 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported[i]));
63aefcd5
MS
1214 break;
1215
1216 /* RC4 cipher suites that should only be used as a last resort */
1217 case SSL_RSA_WITH_RC4_128_MD5 :
1218 case SSL_RSA_WITH_RC4_128_SHA :
1219 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
1220 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
1221 case TLS_ECDH_RSA_WITH_RC4_128_SHA :
1222 case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
1223 case TLS_PSK_WITH_RC4_128_SHA :
1224 case TLS_DHE_PSK_WITH_RC4_128_SHA :
1225 case TLS_RSA_PSK_WITH_RC4_128_SHA :
1226 if (tls_options & _HTTP_TLS_ALLOW_RC4)
1227 enabled[num_enabled ++] = supported[i];
b37d45d9
MS
1228 else
1229 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported[i]));
63aefcd5
MS
1230 break;
1231
ee6226a5
MS
1232 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1233 case TLS_DH_DSS_WITH_AES_128_CBC_SHA :
1234 case TLS_DH_RSA_WITH_AES_128_CBC_SHA :
1235 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA :
1236 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
1237 case TLS_DH_DSS_WITH_AES_256_CBC_SHA :
1238 case TLS_DH_RSA_WITH_AES_256_CBC_SHA :
1239 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA :
1240 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
1241 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA :
1242 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA :
bdc4056c 1243// case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
ee6226a5
MS
1244 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA :
1245 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256 :
1246 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256 :
1247 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 :
1248 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
1249 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256 :
1250 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256 :
1251 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 :
1252 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
1253 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA :
1254 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA :
1255 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA :
bdc4056c
MS
1256// case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1257// case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
ee6226a5
MS
1258 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256 :
1259 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384 :
bdc4056c
MS
1260// case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1261// case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
ee6226a5
MS
1262 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256 :
1263 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384 :
1264 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
1265 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
1266 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
1267 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
1268 if (tls_options & _HTTP_TLS_ALLOW_DH)
1269 enabled[num_enabled ++] = supported[i];
b37d45d9
MS
1270 else
1271 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported[i]));
ee6226a5
MS
1272 break;
1273
63aefcd5
MS
1274 /* Anything else we'll assume is secure */
1275 default :
1276 enabled[num_enabled ++] = supported[i];
1277 break;
1278 }
1279 }
1280
1281 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled));
1282 error = SSLSetEnabledCiphers(http->tls, enabled, num_enabled);
1283 }
2c85b752 1284 }
ee6226a5 1285#endif /* HAVE_SSLSETENABLEDCIPHERS */
2c85b752 1286
41e0907c 1287 if (!error && http->mode == _HTTP_MODE_CLIENT)
2c85b752 1288 {
41e0907c
MS
1289 /*
1290 * Client: set client-side credentials, if any...
1291 */
1292
2c85b752
MS
1293 if (cg->client_cert_cb)
1294 {
1295 error = SSLSetSessionOption(http->tls,
1296 kSSLSessionOptionBreakOnCertRequested, true);
25731360 1297 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
2c85b752
MS
1298 "error=%d", (int)error));
1299 }
1300 else
1301 {
88f1e9c8
MS
1302 error = http_cdsa_set_credentials(http);
1303 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
2c85b752
MS
1304 (int)error));
1305 }
1306 }
41e0907c
MS
1307 else if (!error)
1308 {
1309 /*
1310 * Server: find/create a certificate for TLS...
1311 */
1312
1313 if (http->fields[HTTP_FIELD_HOST][0])
1314 {
1315 /*
1316 * Use hostname for TLS upgrade...
1317 */
1318
1319 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1320 }
1321 else
1322 {
1323 /*
1324 * Resolve hostname from connection address...
1325 */
1326
1327 http_addr_t addr; /* Connection address */
1328 socklen_t addrlen; /* Length of address */
1329
1330 addrlen = sizeof(addr);
1331 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1332 {
25731360 1333 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
41e0907c
MS
1334 hostname[0] = '\0';
1335 }
1336 else if (httpAddrLocalhost(&addr))
1337 hostname[0] = '\0';
1338 else
a27a134a
MS
1339 {
1340 httpAddrLookup(&addr, hostname, sizeof(hostname));
25731360 1341 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
a27a134a 1342 }
41e0907c
MS
1343 }
1344
a27a134a
MS
1345 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1346 hostname[0] = '\0'; /* Don't allow numeric addresses */
1347
41e0907c
MS
1348 if (hostname[0])
1349 http->tls_credentials = http_cdsa_copy_server(hostname);
1350 else if (tls_common_name)
1351 http->tls_credentials = http_cdsa_copy_server(tls_common_name);
1352
1353 if (!http->tls_credentials && tls_auto_create && (hostname[0] || tls_common_name))
1354 {
25731360 1355 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
41e0907c
MS
1356
1357 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1358 {
25731360 1359 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
41e0907c
MS
1360 http->error = errno = EINVAL;
1361 http->status = HTTP_STATUS_ERROR;
1362 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1363
1364 return (-1);
1365 }
1366
1367 http->tls_credentials = http_cdsa_copy_server(hostname[0] ? hostname : tls_common_name);
1368 }
1369
1370 if (!http->tls_credentials)
1371 {
25731360 1372 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
41e0907c
MS
1373 http->error = errno = EINVAL;
1374 http->status = HTTP_STATUS_ERROR;
1375 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to find server credentials."), 1);
1376
1377 return (-1);
1378 }
1379
1380 error = SSLSetCertificate(http->tls, http->tls_credentials);
1381
25731360 1382 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
41e0907c
MS
1383 }
1384
807315e6 1385 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http->tls_credentials));
2c85b752
MS
1386
1387 /*
1388 * Let the server know which hostname/domain we are trying to connect to
1389 * in case it wants to serve up a certificate with a matching common name.
1390 */
1391
41e0907c 1392 if (!error && http->mode == _HTTP_MODE_CLIENT)
2c85b752 1393 {
41e0907c
MS
1394 /*
1395 * Client: get the hostname to use for TLS...
1396 */
1397
1398 if (httpAddrLocalhost(http->hostaddr))
1399 {
1400 strlcpy(hostname, "localhost", sizeof(hostname));
1401 }
1402 else
1403 {
1404 /*
1405 * Otherwise make sure the hostname we have does not end in a trailing dot.
1406 */
1407
1408 strlcpy(hostname, http->hostname, sizeof(hostname));
1409 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1410 *hostptr == '.')
1411 *hostptr = '\0';
1412 }
1413
2c85b752
MS
1414 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
1415
25731360 1416 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error));
2c85b752
MS
1417 }
1418
1419 if (!error)
1420 {
1421 int done = 0; /* Are we done yet? */
1422
1423 while (!error && !done)
1424 {
1425 error = SSLHandshake(http->tls);
1426
25731360 1427 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error));
2c85b752
MS
1428
1429 switch (error)
1430 {
1431 case noErr :
1432 done = 1;
1433 break;
1434
1435 case errSSLWouldBlock :
1436 error = noErr; /* Force a retry */
1437 usleep(1000); /* in 1 millisecond */
1438 break;
1439
1440 case errSSLServerAuthCompleted :
1441 error = 0;
1442 if (cg->server_cert_cb)
1443 {
1444 error = httpCopyCredentials(http, &credentials);
1445 if (!error)
1446 {
1447 error = (cg->server_cert_cb)(http, http->tls, credentials,
1448 cg->server_cert_data);
1449 httpFreeCredentials(credentials);
1450 }
1451
25731360 1452 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
2c85b752
MS
1453 "returned %d.", (int)error));
1454 }
1455 break;
1456
1457 case errSSLClientCertRequested :
1458 error = 0;
1459
1460 if (cg->client_cert_cb)
1461 {
1462 names = NULL;
1463 if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
1464 dn_array)
1465 {
1466 if ((names = cupsArrayNew(NULL, NULL)) != NULL)
1467 {
1468 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
1469 {
1470 data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
1471
1472 if ((credential = malloc(sizeof(*credential))) != NULL)
1473 {
7e86f2f6 1474 credential->datalen = (size_t)CFDataGetLength(data);
2c85b752
MS
1475 if ((credential->data = malloc(credential->datalen)))
1476 {
1477 memcpy((void *)credential->data, CFDataGetBytePtr(data),
1478 credential->datalen);
1479 cupsArrayAdd(names, credential);
1480 }
1481 else
1482 free(credential);
1483 }
1484 }
1485 }
1486
1487 CFRelease(dn_array);
1488 }
1489
1490 if (!error)
1491 {
1492 error = (cg->client_cert_cb)(http, http->tls, names,
1493 cg->client_cert_data);
1494
25731360 1495 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
2c85b752
MS
1496 "returned %d.", (int)error));
1497 }
1498
1499 httpFreeCredentials(names);
1500 }
1501 break;
1502
1503 case errSSLUnknownRootCert :
1504 message = _("Unable to establish a secure connection to host "
1505 "(untrusted certificate).");
1506 break;
1507
1508 case errSSLNoRootCert :
1509 message = _("Unable to establish a secure connection to host "
1510 "(self-signed certificate).");
1511 break;
1512
1513 case errSSLCertExpired :
1514 message = _("Unable to establish a secure connection to host "
1515 "(expired certificate).");
1516 break;
1517
1518 case errSSLCertNotYetValid :
1519 message = _("Unable to establish a secure connection to host "
1520 "(certificate not yet valid).");
1521 break;
1522
1523 case errSSLHostNameMismatch :
1524 message = _("Unable to establish a secure connection to host "
1525 "(host name mismatch).");
1526 break;
1527
1528 case errSSLXCertChainInvalid :
1529 message = _("Unable to establish a secure connection to host "
1530 "(certificate chain invalid).");
1531 break;
1532
1533 case errSSLConnectionRefused :
1534 message = _("Unable to establish a secure connection to host "
1535 "(peer dropped connection before responding).");
1536 break;
1537
1538 default :
1539 break;
1540 }
1541 }
1542 }
1543
1544 if (error)
1545 {
1546 http->error = error;
1547 http->status = HTTP_STATUS_ERROR;
1548 errno = ECONNREFUSED;
1549
1550 CFRelease(http->tls);
1551 http->tls = NULL;
1552
1553 /*
1554 * If an error string wasn't set by the callbacks use a generic one...
1555 */
1556
1557 if (!message)
1558#ifdef HAVE_CSSMERRORSTRING
1559 message = cssmErrorString(error);
1560#else
1561 message = _("Unable to establish a secure connection to host.");
1562#endif /* HAVE_CSSMERRORSTRING */
1563
1564 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
1565
1566 return (-1);
1567 }
1568
1569 return (0);
1570}
1571
1572
1573/*
25731360 1574 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
2c85b752
MS
1575 */
1576
25731360
MS
1577void
1578_httpTLSStop(http_t *http) /* I - HTTP connection */
2c85b752
MS
1579{
1580 while (SSLClose(http->tls) == errSSLWouldBlock)
1581 usleep(1000);
1582
1583 CFRelease(http->tls);
1584
1585 if (http->tls_credentials)
1586 CFRelease(http->tls_credentials);
1587
1588 http->tls = NULL;
1589 http->tls_credentials = NULL;
1590}
1591
1592
1593/*
25731360 1594 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
2c85b752
MS
1595 */
1596
25731360
MS
1597int /* O - Bytes written */
1598_httpTLSWrite(http_t *http, /* I - HTTP connection */
2c85b752
MS
1599 const char *buf, /* I - Buffer holding data */
1600 int len) /* I - Length of buffer */
1601{
1602 ssize_t result; /* Return value */
1603 OSStatus error; /* Error info */
1604 size_t processed; /* Number of bytes processed */
1605
1606
807315e6 1607 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http, (void *)buf, len));
2c85b752 1608
7e86f2f6 1609 error = SSLWrite(http->tls, buf, (size_t)len, &processed);
2c85b752
MS
1610
1611 switch (error)
1612 {
1613 case 0 :
1614 result = (int)processed;
1615 break;
1616
1617 case errSSLWouldBlock :
1618 if (processed)
1619 {
1620 result = (int)processed;
1621 }
1622 else
1623 {
1624 result = -1;
1625 errno = EINTR;
1626 }
1627 break;
1628
1629 case errSSLClosedGraceful :
1630 default :
1631 if (processed)
1632 {
1633 result = (int)processed;
1634 }
1635 else
1636 {
1637 result = -1;
1638 errno = EPIPE;
1639 }
1640 break;
1641 }
1642
25731360 1643 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result));
2c85b752
MS
1644
1645 return ((int)result);
1646}
1647
1648
1649/*
88f1e9c8 1650 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
2c85b752
MS
1651 */
1652
88f1e9c8
MS
1653static CFArrayRef /* O - Array of certificates or NULL */
1654http_cdsa_copy_server(
1655 const char *common_name) /* I - Server's hostname */
2c85b752 1656{
2274d26b 1657#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 1658 OSStatus err; /* Error info */
88f1e9c8
MS
1659 SecIdentityRef identity = NULL;/* Identity */
1660 CFArrayRef certificates = NULL;
1661 /* Certificate array */
1662 SecPolicyRef policy = NULL; /* Policy ref */
1663 CFStringRef cfcommon_name = NULL;
1664 /* Server name */
1665 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
1666 CFArrayRef list = NULL; /* Keychain list */
2c85b752 1667
2c85b752 1668
2274d26b
MS
1669 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name));
1670
88f1e9c8 1671 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
2c85b752 1672
88f1e9c8
MS
1673 policy = SecPolicyCreateSSL(1, cfcommon_name);
1674
88f1e9c8 1675 if (!policy)
2274d26b
MS
1676 {
1677 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
88f1e9c8 1678 goto cleanup;
2274d26b 1679 }
88f1e9c8
MS
1680
1681 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
2274d26b
MS
1682 {
1683 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
88f1e9c8 1684 goto cleanup;
2274d26b 1685 }
88f1e9c8 1686
f93b32b6
MS
1687 _cupsMutexLock(&tls_mutex);
1688
88f1e9c8
MS
1689 CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
1690 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
1691 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
1692 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
88f1e9c8 1693
fc4bbb58
MS
1694 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
1695 CFDictionaryAddValue(query, kSecMatchSearchList, list);
88f1e9c8
MS
1696 CFRelease(list);
1697
1698 err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
1699
f93b32b6
MS
1700 _cupsMutexUnlock(&tls_mutex);
1701
2274d26b
MS
1702 if (err != noErr)
1703 {
1704 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err));
88f1e9c8 1705 goto cleanup;
2274d26b 1706 }
88f1e9c8
MS
1707
1708 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
2274d26b
MS
1709 {
1710 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
88f1e9c8 1711 goto cleanup;
2274d26b 1712 }
88f1e9c8
MS
1713
1714 if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
2274d26b
MS
1715 {
1716 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
88f1e9c8 1717 goto cleanup;
2274d26b 1718 }
88f1e9c8
MS
1719
1720 cleanup :
1721
88f1e9c8
MS
1722 if (identity)
1723 CFRelease(identity);
88f1e9c8
MS
1724 if (policy)
1725 CFRelease(policy);
2274d26b
MS
1726 if (cfcommon_name)
1727 CFRelease(cfcommon_name);
88f1e9c8
MS
1728 if (query)
1729 CFRelease(query);
1730
2274d26b
MS
1731 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates));
1732
88f1e9c8 1733 return (certificates);
2274d26b
MS
1734#else
1735
1736 if (!tls_selfsigned)
1737 return (NULL);
1738
1739 return (CFArrayCreate(NULL, (const void **)&tls_selfsigned, 1, &kCFTypeArrayCallBacks));
1740#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752
MS
1741}
1742
1743
2ece34a9
MS
1744/*
1745 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1746 */
1747
1748static SecCertificateRef /* O - Certificate */
1749http_cdsa_create_credential(
1750 http_credential_t *credential) /* I - Credential */
1751{
1752 if (!credential)
1753 return (NULL);
1754
1755 return (SecCertificateCreateWithBytes(kCFAllocatorDefault, credential->data, (CFIndex)credential->datalen));
1756}
1757
1758
fc4bbb58 1759#ifdef HAVE_SECKEYCHAINOPEN
005f7f1f
MS
1760/*
1761 * 'http_cdsa_default_path()' - Get the default keychain path.
1762 */
1763
1764static const char * /* O - Keychain path */
1765http_cdsa_default_path(char *buffer, /* I - Path buffer */
1766 size_t bufsize) /* I - Size of buffer */
1767{
1768 const char *home = getenv("HOME"); /* HOME environment variable */
1769
1770
1771 if (getuid() && home)
1772 snprintf(buffer, bufsize, "%s/Library/Keychains/login.keychain", home);
1773 else
1774 strlcpy(buffer, "/Library/Keychains/System.keychain", bufsize);
1775
1776 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer));
1777
1778 return (buffer);
1779}
fc4bbb58 1780#endif /* HAVE_SECKEYCHAINOPEN */
005f7f1f
MS
1781
1782
2c85b752 1783/*
88f1e9c8 1784 * 'http_cdsa_read()' - Read function for the CDSA library.
2c85b752
MS
1785 */
1786
88f1e9c8
MS
1787static OSStatus /* O - -1 on error, 0 on success */
1788http_cdsa_read(
1789 SSLConnectionRef connection, /* I - SSL/TLS connection */
1790 void *data, /* I - Data buffer */
1791 size_t *dataLength) /* IO - Number of bytes */
2c85b752 1792{
88f1e9c8
MS
1793 OSStatus result; /* Return value */
1794 ssize_t bytes; /* Number of bytes read */
1795 http_t *http; /* HTTP connection */
2c85b752 1796
2c85b752 1797
88f1e9c8 1798 http = (http_t *)connection;
2c85b752 1799
88f1e9c8 1800 if (!http->blocking)
2c85b752
MS
1801 {
1802 /*
88f1e9c8 1803 * Make sure we have data before we read...
2c85b752
MS
1804 */
1805
88f1e9c8
MS
1806 while (!_httpWait(http, http->wait_value, 0))
1807 {
1808 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1809 continue;
1810
1811 http->error = ETIMEDOUT;
1812 return (-1);
1813 }
2c85b752
MS
1814 }
1815
88f1e9c8 1816 do
2c85b752 1817 {
88f1e9c8 1818 bytes = recv(http->fd, data, *dataLength, 0);
2c85b752 1819 }
88f1e9c8 1820 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2c85b752 1821
88f1e9c8
MS
1822 if ((size_t)bytes == *dataLength)
1823 {
1824 result = 0;
1825 }
1826 else if (bytes > 0)
1827 {
1828 *dataLength = (size_t)bytes;
1829 result = errSSLWouldBlock;
1830 }
1831 else
1832 {
1833 *dataLength = 0;
2c85b752 1834
88f1e9c8
MS
1835 if (bytes == 0)
1836 result = errSSLClosedGraceful;
1837 else if (errno == EAGAIN)
1838 result = errSSLWouldBlock;
1839 else
1840 result = errSSLClosedAbort;
1841 }
2c85b752 1842
88f1e9c8
MS
1843 return (result);
1844}
2c85b752 1845
2c85b752 1846
88f1e9c8
MS
1847/*
1848 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1849 */
2c85b752 1850
88f1e9c8
MS
1851static int /* O - Status of connection */
1852http_cdsa_set_credentials(http_t *http) /* I - HTTP connection */
1853{
1854 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1855 OSStatus error = 0; /* Error code */
1856 http_tls_credentials_t credentials = NULL;
1857 /* TLS credentials */
2c85b752 1858
2c85b752 1859
807315e6 1860 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http));
2c85b752 1861
88f1e9c8
MS
1862 /*
1863 * Prefer connection specific credentials...
1864 */
2c85b752 1865
88f1e9c8
MS
1866 if ((credentials = http->tls_credentials) == NULL)
1867 credentials = cg->tls_credentials;
2c85b752 1868
88f1e9c8
MS
1869 if (credentials)
1870 {
1871 error = SSLSetCertificate(http->tls, credentials);
1872 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1873 (int)error));
2c85b752 1874 }
88f1e9c8
MS
1875 else
1876 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1877
1878 return (error);
1879}
1880
1881
1882/*
1883 * 'http_cdsa_write()' - Write function for the CDSA library.
1884 */
1885
1886static OSStatus /* O - -1 on error, 0 on success */
1887http_cdsa_write(
1888 SSLConnectionRef connection, /* I - SSL/TLS connection */
1889 const void *data, /* I - Data buffer */
1890 size_t *dataLength) /* IO - Number of bytes */
1891{
1892 OSStatus result; /* Return value */
1893 ssize_t bytes; /* Number of bytes read */
1894 http_t *http; /* HTTP connection */
2c85b752 1895
2c85b752 1896
88f1e9c8
MS
1897 http = (http_t *)connection;
1898
1899 do
2c85b752 1900 {
88f1e9c8
MS
1901 bytes = write(http->fd, data, *dataLength);
1902 }
1903 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
1904
1905 if ((size_t)bytes == *dataLength)
1906 {
1907 result = 0;
1908 }
1909 else if (bytes >= 0)
1910 {
1911 *dataLength = (size_t)bytes;
1912 result = errSSLWouldBlock;
2c85b752
MS
1913 }
1914 else
88f1e9c8
MS
1915 {
1916 *dataLength = 0;
2c85b752 1917
88f1e9c8
MS
1918 if (errno == EAGAIN)
1919 result = errSSLWouldBlock;
1920 else
1921 result = errSSLClosedAbort;
1922 }
1923
1924 return (result);
2c85b752 1925}