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