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