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