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