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