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