]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/tls-darwin.c
ab9fedc6a88f51df81e99a7b2c3e6e8d3b5e3961
[thirdparty/cups.git] / cups / tls-darwin.c
1 /*
2 * TLS support code for CUPS on OS X.
3 *
4 * Copyright 2007-2016 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 * 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
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;
25
26
27 /*
28 * Local globals...
29 */
30
31 static int tls_auto_create = 0;
32 /* Auto-create self-signed certs? */
33 static char *tls_common_name = NULL;
34 /* Default common name */
35 #ifdef HAVE_SECKEYCHAINOPEN
36 static SecKeychainRef tls_keychain = NULL;
37 /* Server cert keychain */
38 #else
39 static SecIdentityRef tls_selfsigned = NULL;
40 /* Temporary self-signed cert */
41 #endif /* HAVE_SECKEYCHAINOPEN */
42 static char *tls_keypath = NULL;
43 /* Server cert keychain path */
44 static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER;
45 /* Mutex for keychain/certs */
46 static int tls_options = -1;/* Options for TLS connections */
47
48
49 /*
50 * Local functions...
51 */
52
53 static CFArrayRef http_cdsa_copy_server(const char *common_name);
54 static SecCertificateRef http_cdsa_create_credential(http_credential_t *credential);
55 #ifdef HAVE_SECKEYCHAINOPEN
56 static const char *http_cdsa_default_path(char *buffer, size_t bufsize);
57 #endif /* HAVE_SECKEYCHAINOPEN */
58 static OSStatus http_cdsa_read(SSLConnectionRef connection, void *data, size_t *dataLength);
59 static int http_cdsa_set_credentials(http_t *http);
60 static OSStatus http_cdsa_write(SSLConnectionRef connection, const void *data, size_t *dataLength);
61
62
63 /*
64 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
65 *
66 * @since CUPS 2.0/OS 10.10@
67 */
68
69 int /* O - 1 on success, 0 on failure */
70 cupsMakeServerCredentials(
71 const char *path, /* I - Keychain path or @code NULL@ for default */
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 {
77 #if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE)
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 */
87 SecCertificateRef cert = NULL; /* Self-signed certificate */
88 CFMutableDictionaryRef keyParams = NULL;
89 /* Key generation parameters */
90
91
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
94 (void)path;
95 (void)num_alt_names;
96 (void)alt_names;
97 (void)expiration_date;
98
99 if (path)
100 {
101 DEBUG_puts("1cupsMakeServerCredentials: No keychain support compiled in, returning 0.");
102 return (0);
103 }
104
105 if (tls_selfsigned)
106 {
107 DEBUG_puts("1cupsMakeServerCredentials: Using existing self-signed cert.");
108 return (1);
109 }
110
111 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
112 if (!cfcommon_name)
113 {
114 DEBUG_puts("1cupsMakeServerCredentials: Unable to create CF string of common name.");
115 goto cleanup;
116 }
117
118 /*
119 * Create a public/private key pair...
120 */
121
122 keyParams = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
123 if (!keyParams)
124 {
125 DEBUG_puts("1cupsMakeServerCredentials: Unable to create key parameters dictionary.");
126 goto cleanup;
127 }
128
129 CFDictionaryAddValue(keyParams, kSecAttrKeyType, kSecAttrKeyTypeRSA);
130 CFDictionaryAddValue(keyParams, kSecAttrKeySizeInBits, CFSTR("2048"));
131 CFDictionaryAddValue(keyParams, kSecAttrLabel, cfcommon_name);
132
133 err = SecKeyGeneratePair(keyParams, &publicKey, &privateKey);
134 if (err != noErr)
135 {
136 DEBUG_printf(("1cupsMakeServerCredentials: Unable to generate key pair: %d.", (int)err));
137 goto cleanup;
138 }
139
140 /*
141 * Create a self-signed certificate using the public/private key pair...
142 */
143
144 CFIndex usageInt = kSecKeyUsageAll;
145 CFNumberRef usage = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &usageInt);
146 CFIndex lenInt = 0;
147 CFNumberRef len = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &lenInt);
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);
151 CFRelease(usage);
152 CFRelease(len);
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);
164
165 cert = SecGenerateSelfSignedCertificate(subject, certParams, publicKey, privateKey);
166
167 CFRelease(subject);
168 CFRelease(certParams);
169
170 if (!cert)
171 {
172 DEBUG_puts("1cupsMakeServerCredentials: Unable to create self-signed certificate.");
173 goto cleanup;
174 }
175
176 ident = SecIdentityCreate(kCFAllocatorDefault, cert, privateKey);
177
178 if (ident)
179 {
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 */
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);
195 /* SecItemAdd consumes itemAttrs... */
196
197 CFRelease(ident);
198
199 if (err != noErr)
200 {
201 DEBUG_printf(("1cupsMakeServerCredentials: Unable to add identity to keychain: %d.", (int)err));
202 goto cleanup;
203 }
204 # endif /* 0 */
205
206 status = 1;
207 }
208 else
209 DEBUG_puts("1cupsMakeServerCredentials: Unable to create identity from cert and keys.");
210
211 /*
212 * Cleanup and return...
213 */
214
215 cleanup:
216
217 if (cfcommon_name)
218 CFRelease(cfcommon_name);
219
220 if (keyParams)
221 CFRelease(keyParams);
222
223 if (cert)
224 CFRelease(cert);
225
226 if (publicKey)
227 CFRelease(publicKey);
228
229 if (privateKey)
230 CFRelease(privateKey);
231
232 DEBUG_printf(("1cupsMakeServerCredentials: Returning %d.", status));
233
234 return (status);
235
236 #else /* !HAVE_SECGENERATESELFSIGNEDCERTIFICATE */
237 int pid, /* Process ID of command */
238 status, /* Status of command */
239 i; /* Looping var */
240 char command[1024], /* Command */
241 *argv[5], /* Command-line arguments */
242 *envp[1000], /* Environment variables */
243 days[32], /* CERTTOOL_EXPIRATION_DAYS env var */
244 keychain[1024], /* Keychain argument */
245 infofile[1024], /* Type-in information for cert */
246 filename[1024]; /* Default keychain path */
247 cups_file_t *fp; /* Seed/info file */
248
249
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));
251
252 (void)num_alt_names;
253 (void)alt_names;
254
255 if (!path)
256 path = http_cdsa_default_path(filename, sizeof(filename));
257
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 */
278 "r\n" /* Generate RSA key pair */
279 "2048\n" /* 2048 bit encryption key */
280 "y\n" /* OK (y = yes) */
281 "b\n" /* Usage (b=signing/encryption) */
282 "2\n" /* Sign with SHA256 */
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
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
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);
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);
316
317 if (posix_spawn(&pid, command, &actions, NULL, argv, envp))
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);
335 #endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
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 *
345 * @since CUPS 2.0/OS X 10.10@
346 */
347
348 int /* O - 1 on success, 0 on failure */
349 cupsSetServerCredentials(
350 const char *path, /* I - Keychain path or @code NULL@ for default */
351 const char *common_name, /* I - Default common name for server */
352 int auto_create) /* I - 1 = automatically create self-signed certificates */
353 {
354 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
355
356 #ifdef HAVE_SECKEYCHAINOPEN
357 char filename[1024]; /* Filename for keychain */
358 SecKeychainRef keychain = NULL;/* Temporary keychain */
359 OSStatus status; /* Status code */
360
361
362 if (!path)
363 path = http_cdsa_default_path(filename, sizeof(filename));
364
365 if ((status = SecKeychainOpen(path, &keychain)) != noErr)
366 {
367 /* TODO: Set cups last error string */
368 DEBUG_printf(("1cupsSetServerCredentials: Unable to open keychain (%d), returning 0.", (int)status));
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
381 if (tls_keypath)
382 _cupsStrFree(tls_keypath);
383
384 if (tls_common_name)
385 _cupsStrFree(tls_common_name);
386
387 /*
388 * Save the new keychain...
389 */
390
391 tls_keychain = keychain;
392 tls_keypath = _cupsStrAlloc(path);
393 tls_auto_create = auto_create;
394 tls_common_name = _cupsStrAlloc(common_name);
395
396 _cupsMutexUnlock(&tls_mutex);
397
398 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
399 return (1);
400
401 #else
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);
412 #endif /* HAVE_SECKEYCHAINOPEN */
413 }
414
415
416 /*
417 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
418 * an encrypted connection.
419 *
420 * @since CUPS 1.5/OS X 10.7@
421 */
422
423 int /* O - Status of call (0 = success) */
424 httpCopyCredentials(
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
436 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", (void *)http, (void *)credentials));
437
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 {
446 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust)));
447
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);
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
467 if ((data = SecCertificateCopyData(secCert)) != NULL)
468 {
469 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
470
471 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
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
488 http_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 */
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 {
509 if ((secCert = http_cdsa_create_credential(credential)) != NULL)
510 {
511 CFArrayAppendValue(peerCerts, secCert);
512 CFRelease(secCert);
513 }
514 }
515
516 return (peerCerts);
517 }
518
519
520 /*
521 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
522 *
523 * @since CUPS 2.0/OS X 10.10@
524 */
525
526 int /* O - 1 if valid, 0 otherwise */
527 httpCredentialsAreValidForName(
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 *
586 * @since CUPS 2.0/OS X 10.10@
587 */
588
589 http_trust_t /* O - Level of trust */
590 httpCredentialsGetTrust(
591 cups_array_t *credentials, /* I - Credentials */
592 const char *common_name) /* I - Common name for trust lookup */
593 {
594 SecCertificateRef secCert; /* Certificate reference */
595 http_trust_t trust = HTTP_TRUST_OK;
596 /* Trusted? */
597 cups_array_t *tcreds = NULL; /* Trusted credentials */
598 _cups_globals_t *cg = _cupsGlobals();
599 /* Per-thread globals */
600
601
602 if (!common_name)
603 return (HTTP_TRUST_UNKNOWN);
604
605 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
606 return (HTTP_TRUST_UNKNOWN);
607
608 if (cg->any_root < 0)
609 _cupsSetDefaults();
610
611 /*
612 * Look this common name up in the default keychains...
613 */
614
615 httpLoadCredentials(NULL, &tcreds, common_name);
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
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))
641 {
642 /*
643 * Either the new credentials are not newly issued, or the common name
644 * does not match the issued certificate...
645 */
646
647 trust = HTTP_TRUST_INVALID;
648 }
649 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
650 {
651 /*
652 * Save the renewed credentials...
653 */
654
655 trust = HTTP_TRUST_RENEWED;
656
657 httpSaveCredentials(NULL, credentials, common_name);
658 }
659 }
660
661 httpFreeCredentials(tcreds);
662 }
663 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
664 trust = HTTP_TRUST_INVALID;
665
666 if (!cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
667 trust = HTTP_TRUST_EXPIRED;
668 else if (!cg->any_root && cupsArrayCount(credentials) == 1)
669 trust = HTTP_TRUST_INVALID;
670 else if (!cg->trust_first)
671 trust = HTTP_TRUST_INVALID;
672
673 CFRelease(secCert);
674
675 return (trust);
676 }
677
678
679 /*
680 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
681 *
682 * @since CUPS 2.0/OS X 10.10@
683 */
684
685 time_t /* O - Expiration date of credentials */
686 httpCredentialsGetExpiration(
687 cups_array_t *credentials) /* I - Credentials */
688 {
689 SecCertificateRef secCert; /* Certificate reference */
690 time_t expiration; /* Expiration date */
691
692
693 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
694 return (0);
695
696 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
697
698 CFRelease(secCert);
699
700 return (expiration);
701 }
702
703
704 /*
705 * 'httpCredentialsString()' - Return a string representing the credentials.
706 *
707 * @since CUPS 2.0/OS X 10.10@
708 */
709
710 size_t /* O - Total size of credentials string */
711 httpCredentialsString(
712 cups_array_t *credentials, /* I - Credentials */
713 char *buffer, /* I - Buffer or @code NULL@ */
714 size_t bufsize) /* I - Size of buffer */
715 {
716 http_credential_t *first; /* First certificate */
717 SecCertificateRef secCert; /* Certificate reference */
718
719
720 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", (void *)credentials, (void *)buffer, CUPS_LLCAST bufsize));
721
722 if (!buffer)
723 return (0);
724
725 if (buffer && bufsize > 0)
726 *buffer = '\0';
727
728 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
729 (secCert = http_cdsa_create_credential(first)) != NULL)
730 {
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)
738 {
739 CFStringGetCString(cf_name, name, (CFIndex)sizeof(name), kCFStringEncodingUTF8);
740 CFRelease(cf_name);
741 }
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]);
752
753 CFRelease(secCert);
754 }
755
756 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
757
758 return (strlen(buffer));
759 }
760
761
762 /*
763 * '_httpFreeCredentials()' - Free internal credentials.
764 */
765
766 void
767 _httpFreeCredentials(
768 http_tls_credentials_t credentials) /* I - Internal credentials */
769 {
770 if (!credentials)
771 return;
772
773 CFRelease(credentials);
774 }
775
776
777 /*
778 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
779 *
780 * @since CUPS 2.0/OS 10.10@
781 */
782
783 int /* O - 0 on success, -1 on error */
784 httpLoadCredentials(
785 const char *path, /* I - Keychain path or @code NULL@ for default */
786 cups_array_t **credentials, /* IO - Credentials */
787 const char *common_name) /* I - Common name for credentials */
788 {
789 OSStatus err; /* Error info */
790 #ifdef HAVE_SECKEYCHAINOPEN
791 char filename[1024]; /* Filename for keychain */
792 SecKeychainRef keychain = NULL;/* Keychain reference */
793 CFArrayRef list; /* Keychain list */
794 #endif /* HAVE_SECKEYCHAINOPEN */
795 SecCertificateRef cert = NULL; /* Certificate */
796 CFDataRef data; /* Certificate data */
797 SecPolicyRef policy = NULL; /* Policy ref */
798 CFStringRef cfcommon_name = NULL;
799 /* Server name */
800 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
801
802
803 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
804
805 if (!credentials)
806 return (-1);
807
808 *credentials = NULL;
809
810 #ifdef HAVE_SECKEYCHAINOPEN
811 if (!path)
812 path = http_cdsa_default_path(filename, sizeof(filename));
813
814 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
815 goto cleanup;
816
817 #else
818 if (path)
819 return (-1);
820 #endif /* HAVE_SECKEYCHAINOPEN */
821
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
835 CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
836 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
837 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
838 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
839
840 #ifdef HAVE_SECKEYCHAINOPEN
841 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
842 CFDictionaryAddValue(query, kSecMatchSearchList, list);
843 CFRelease(list);
844 #endif /* HAVE_SECKEYCHAINOPEN */
845
846 err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
847
848 if (err)
849 goto cleanup;
850
851 if (CFGetTypeID(cert) != SecCertificateGetTypeID())
852 goto cleanup;
853
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 }
862
863 cleanup :
864
865 #ifdef HAVE_SECKEYCHAINOPEN
866 if (keychain)
867 CFRelease(keychain);
868 #endif /* HAVE_SECKEYCHAINOPEN */
869 if (cert)
870 CFRelease(cert);
871 if (policy)
872 CFRelease(policy);
873 if (query)
874 CFRelease(query);
875
876 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
877
878 return (*credentials ? 0 : -1);
879 }
880
881
882 /*
883 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
884 *
885 * @since CUPS 2.0/OS 10.10@
886 */
887
888 int /* O - -1 on error, 0 on success */
889 httpSaveCredentials(
890 const char *path, /* I - Keychain path or @code NULL@ for default */
891 cups_array_t *credentials, /* I - Credentials */
892 const char *common_name) /* I - Common name for credentials */
893 {
894 int ret = -1; /* Return value */
895 OSStatus err; /* Error info */
896 #ifdef HAVE_SECKEYCHAINOPEN
897 char filename[1024]; /* Filename for keychain */
898 SecKeychainRef keychain = NULL;/* Keychain reference */
899 CFArrayRef list; /* Keychain list */
900 #endif /* HAVE_SECKEYCHAINOPEN */
901 SecCertificateRef cert = NULL; /* Certificate */
902 CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
903
904
905 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
906 if (!credentials)
907 goto cleanup;
908
909 if (!httpCredentialsAreValidForName(credentials, common_name))
910 {
911 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
912 return (-1);
913 }
914
915 if ((cert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
916 {
917 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
918 goto cleanup;
919 }
920
921 #ifdef HAVE_SECKEYCHAINOPEN
922 if (!path)
923 path = http_cdsa_default_path(filename, sizeof(filename));
924
925 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
926 {
927 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err));
928 goto cleanup;
929 }
930
931 #else
932 if (path)
933 return (-1);
934 #endif /* HAVE_SECKEYCHAINOPEN */
935
936 if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
937 {
938 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
939 goto cleanup;
940 }
941
942 CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
943 CFDictionaryAddValue(attrs, kSecValueRef, cert);
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 }
951 CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
952 CFRelease(list);
953 #endif /* HAVE_SECKEYCHAINOPEN */
954
955 /* Note: SecItemAdd consumes "attrs"... */
956 err = SecItemAdd(attrs, NULL);
957 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err));
958
959 cleanup :
960
961 #ifdef HAVE_SECKEYCHAINOPEN
962 if (keychain)
963 CFRelease(keychain);
964 #endif /* HAVE_SECKEYCHAINOPEN */
965 if (cert)
966 CFRelease(cert);
967
968 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
969
970 return (ret);
971 }
972
973
974 /*
975 * '_httpTLSInitialize()' - Initialize the TLS stack.
976 */
977
978 void
979 _httpTLSInitialize(void)
980 {
981 /*
982 * Nothing to do...
983 */
984 }
985
986
987 /*
988 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
989 */
990
991 size_t
992 _httpTLSPending(http_t *http) /* I - HTTP connection */
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 /*
1005 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1006 */
1007
1008 int /* O - Bytes read */
1009 _httpTLSRead(http_t *http, /* I - HTTP connection */
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
1018 error = SSLRead(http->tls, buf, (size_t)len, &processed);
1019 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error,
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
1053 /*
1054 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1055 */
1056
1057 void
1058 _httpTLSSetOptions(int options) /* I - Options */
1059 {
1060 tls_options = options;
1061 }
1062
1063
1064 /*
1065 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1066 */
1067
1068 int /* O - 0 on success, -1 on failure */
1069 _httpTLSStart(http_t *http) /* I - HTTP connection */
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
1086 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http));
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 }
1094
1095 #ifdef HAVE_SECKEYCHAINOPEN
1096 if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
1097 {
1098 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1099 http->error = errno = EINVAL;
1100 http->status = HTTP_STATUS_ERROR;
1101 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
1102
1103 return (-1);
1104 }
1105 #endif /* HAVE_SECKEYCHAINOPEN */
1106
1107 if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
1108 {
1109 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
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);
1118 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error));
1119
1120 if (!error)
1121 {
1122 error = SSLSetIOFuncs(http->tls, http_cdsa_read, http_cdsa_write);
1123 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error));
1124 }
1125
1126 if (!error)
1127 {
1128 error = SSLSetSessionOption(http->tls, kSSLSessionOptionBreakOnServerAuth,
1129 true);
1130 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error));
1131 }
1132
1133 if (!error)
1134 {
1135 SSLProtocol minProtocol;
1136
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));
1146 }
1147
1148 # if HAVE_SSLSETENABLEDCIPHERS
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 :
1213 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported[i]));
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];
1228 else
1229 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported[i]));
1230 break;
1231
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 :
1243 // case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
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 :
1256 // case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1257 // case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1258 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256 :
1259 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384 :
1260 // case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1261 // case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
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];
1270 else
1271 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported[i]));
1272 break;
1273
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 }
1284 }
1285 #endif /* HAVE_SSLSETENABLEDCIPHERS */
1286
1287 if (!error && http->mode == _HTTP_MODE_CLIENT)
1288 {
1289 /*
1290 * Client: set client-side credentials, if any...
1291 */
1292
1293 if (cg->client_cert_cb)
1294 {
1295 error = SSLSetSessionOption(http->tls,
1296 kSSLSessionOptionBreakOnCertRequested, true);
1297 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1298 "error=%d", (int)error));
1299 }
1300 else
1301 {
1302 error = http_cdsa_set_credentials(http);
1303 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1304 (int)error));
1305 }
1306 }
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 {
1333 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
1334 hostname[0] = '\0';
1335 }
1336 else if (httpAddrLocalhost(&addr))
1337 hostname[0] = '\0';
1338 else
1339 {
1340 httpAddrLookup(&addr, hostname, sizeof(hostname));
1341 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
1342 }
1343 }
1344
1345 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1346 hostname[0] = '\0'; /* Don't allow numeric addresses */
1347
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 {
1355 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
1356
1357 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1358 {
1359 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
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 {
1372 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
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
1382 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
1383 }
1384
1385 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http->tls_credentials));
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
1392 if (!error && http->mode == _HTTP_MODE_CLIENT)
1393 {
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
1414 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
1415
1416 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error));
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
1427 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error));
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
1452 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
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 {
1474 credential->datalen = (size_t)CFDataGetLength(data);
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
1495 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
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 /*
1574 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1575 */
1576
1577 void
1578 _httpTLSStop(http_t *http) /* I - HTTP connection */
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 /*
1594 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1595 */
1596
1597 int /* O - Bytes written */
1598 _httpTLSWrite(http_t *http, /* I - HTTP connection */
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
1607 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http, (void *)buf, len));
1608
1609 error = SSLWrite(http->tls, buf, (size_t)len, &processed);
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
1643 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result));
1644
1645 return ((int)result);
1646 }
1647
1648
1649 /*
1650 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1651 */
1652
1653 static CFArrayRef /* O - Array of certificates or NULL */
1654 http_cdsa_copy_server(
1655 const char *common_name) /* I - Server's hostname */
1656 {
1657 #ifdef HAVE_SECKEYCHAINOPEN
1658 OSStatus err; /* Error info */
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 */
1667
1668
1669 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name));
1670
1671 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
1672
1673 policy = SecPolicyCreateSSL(1, cfcommon_name);
1674
1675 if (!policy)
1676 {
1677 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
1678 goto cleanup;
1679 }
1680
1681 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
1682 {
1683 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
1684 goto cleanup;
1685 }
1686
1687 _cupsMutexLock(&tls_mutex);
1688
1689 CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
1690 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
1691 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
1692 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
1693
1694 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
1695 CFDictionaryAddValue(query, kSecMatchSearchList, list);
1696 CFRelease(list);
1697
1698 err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
1699
1700 _cupsMutexUnlock(&tls_mutex);
1701
1702 if (err != noErr)
1703 {
1704 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err));
1705 goto cleanup;
1706 }
1707
1708 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
1709 {
1710 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
1711 goto cleanup;
1712 }
1713
1714 if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
1715 {
1716 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
1717 goto cleanup;
1718 }
1719
1720 cleanup :
1721
1722 if (identity)
1723 CFRelease(identity);
1724 if (policy)
1725 CFRelease(policy);
1726 if (cfcommon_name)
1727 CFRelease(cfcommon_name);
1728 if (query)
1729 CFRelease(query);
1730
1731 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates));
1732
1733 return (certificates);
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 */
1741 }
1742
1743
1744 /*
1745 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1746 */
1747
1748 static SecCertificateRef /* O - Certificate */
1749 http_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
1759 #ifdef HAVE_SECKEYCHAINOPEN
1760 /*
1761 * 'http_cdsa_default_path()' - Get the default keychain path.
1762 */
1763
1764 static const char * /* O - Keychain path */
1765 http_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 }
1780 #endif /* HAVE_SECKEYCHAINOPEN */
1781
1782
1783 /*
1784 * 'http_cdsa_read()' - Read function for the CDSA library.
1785 */
1786
1787 static OSStatus /* O - -1 on error, 0 on success */
1788 http_cdsa_read(
1789 SSLConnectionRef connection, /* I - SSL/TLS connection */
1790 void *data, /* I - Data buffer */
1791 size_t *dataLength) /* IO - Number of bytes */
1792 {
1793 OSStatus result; /* Return value */
1794 ssize_t bytes; /* Number of bytes read */
1795 http_t *http; /* HTTP connection */
1796
1797
1798 http = (http_t *)connection;
1799
1800 if (!http->blocking)
1801 {
1802 /*
1803 * Make sure we have data before we read...
1804 */
1805
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 }
1814 }
1815
1816 do
1817 {
1818 bytes = recv(http->fd, data, *dataLength, 0);
1819 }
1820 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
1821
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;
1834
1835 if (bytes == 0)
1836 result = errSSLClosedGraceful;
1837 else if (errno == EAGAIN)
1838 result = errSSLWouldBlock;
1839 else
1840 result = errSSLClosedAbort;
1841 }
1842
1843 return (result);
1844 }
1845
1846
1847 /*
1848 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1849 */
1850
1851 static int /* O - Status of connection */
1852 http_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 */
1858
1859
1860 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http));
1861
1862 /*
1863 * Prefer connection specific credentials...
1864 */
1865
1866 if ((credentials = http->tls_credentials) == NULL)
1867 credentials = cg->tls_credentials;
1868
1869 if (credentials)
1870 {
1871 error = SSLSetCertificate(http->tls, credentials);
1872 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1873 (int)error));
1874 }
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
1886 static OSStatus /* O - -1 on error, 0 on success */
1887 http_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 */
1895
1896
1897 http = (http_t *)connection;
1898
1899 do
1900 {
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;
1913 }
1914 else
1915 {
1916 *dataLength = 0;
1917
1918 if (errno == EAGAIN)
1919 result = errSSLWouldBlock;
1920 else
1921 result = errSSLClosedAbort;
1922 }
1923
1924 return (result);
1925 }