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