]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/tls-darwin.c
Update Xcode settings (yet again...)
[thirdparty/cups.git] / cups / tls-darwin.c
CommitLineData
2c85b752 1/*
8072030b 2 * TLS support code for CUPS on macOS.
2c85b752 3 *
60716f94 4 * Copyright 2007-2017 by Apple Inc.
2c85b752
MS
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
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 {
376d7c69
MS
803 CFStringRef cf_name; /* CF common name string */
804 char name[256]; /* Common name associated with cert */
805 time_t expiration; /* Expiration date of cert */
376d7c69
MS
806 unsigned char md5_digest[16]; /* MD5 result */
807
808 if ((cf_name = SecCertificateCopySubjectSummary(secCert)) != NULL)
9653cfdf 809 {
376d7c69
MS
810 CFStringGetCString(cf_name, name, (CFIndex)sizeof(name), kCFStringEncodingUTF8);
811 CFRelease(cf_name);
9653cfdf 812 }
376d7c69
MS
813 else
814 strlcpy(name, "unknown", sizeof(name));
815
816 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
817
7ec11630 818 cupsHashData("md5", first->data, first->datalen, md5_digest, sizeof(md5_digest));
376d7c69
MS
819
820 snprintf(buffer, bufsize, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, httpGetDateString(expiration), md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
9653cfdf
MS
821
822 CFRelease(secCert);
823 }
824
376d7c69
MS
825 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
826
9653cfdf 827 return (strlen(buffer));
72d05bc9
MS
828}
829
830
2c85b752
MS
831/*
832 * '_httpFreeCredentials()' - Free internal credentials.
833 */
834
835void
836_httpFreeCredentials(
837 http_tls_credentials_t credentials) /* I - Internal credentials */
838{
839 if (!credentials)
840 return;
841
842 CFRelease(credentials);
843}
844
845
72d05bc9
MS
846/*
847 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
848 *
e1f19878 849 * @since CUPS 2.0/OS 10.10@
72d05bc9
MS
850 */
851
dafebafd 852int /* O - 0 on success, -1 on error */
72d05bc9 853httpLoadCredentials(
f93b32b6 854 const char *path, /* I - Keychain path or @code NULL@ for default */
72d05bc9
MS
855 cups_array_t **credentials, /* IO - Credentials */
856 const char *common_name) /* I - Common name for credentials */
857{
dafebafd 858 OSStatus err; /* Error info */
fc4bbb58 859#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 860 char filename[1024]; /* Filename for keychain */
4daf7e97
MS
861 SecKeychainRef keychain = NULL,/* Keychain reference */
862 syschain = NULL;/* System keychain */
fc4bbb58
MS
863 CFArrayRef list; /* Keychain list */
864#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8
MS
865 SecCertificateRef cert = NULL; /* Certificate */
866 CFDataRef data; /* Certificate data */
dafebafd
MS
867 SecPolicyRef policy = NULL; /* Policy ref */
868 CFStringRef cfcommon_name = NULL;
869 /* Server name */
870 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
dafebafd
MS
871
872
807315e6 873 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
88f1e9c8
MS
874
875 if (!credentials)
876 return (-1);
877
878 *credentials = NULL;
879
fc4bbb58 880#ifdef HAVE_SECKEYCHAINOPEN
4daf7e97 881 keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
88f1e9c8 882
4daf7e97 883 if (!keychain)
dafebafd
MS
884 goto cleanup;
885
4daf7e97
MS
886 syschain = http_cdsa_open_system_keychain();
887
fc4bbb58
MS
888#else
889 if (path)
890 return (-1);
891#endif /* HAVE_SECKEYCHAINOPEN */
892
dafebafd
MS
893 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
894
895 policy = SecPolicyCreateSSL(1, cfcommon_name);
896
897 if (cfcommon_name)
898 CFRelease(cfcommon_name);
899
900 if (!policy)
901 goto cleanup;
902
903 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
904 goto cleanup;
905
88f1e9c8 906 CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
dafebafd
MS
907 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
908 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
909 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
dafebafd 910
fc4bbb58 911#ifdef HAVE_SECKEYCHAINOPEN
4daf7e97
MS
912 if (syschain)
913 {
914 const void *values[2] = { syschain, keychain };
915
916 list = CFArrayCreate(kCFAllocatorDefault, (const void **)values, 2, &kCFTypeArrayCallBacks);
917 }
918 else
919 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
fc4bbb58 920 CFDictionaryAddValue(query, kSecMatchSearchList, list);
dafebafd 921 CFRelease(list);
fc4bbb58 922#endif /* HAVE_SECKEYCHAINOPEN */
dafebafd 923
88f1e9c8 924 err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
dafebafd
MS
925
926 if (err)
927 goto cleanup;
928
88f1e9c8 929 if (CFGetTypeID(cert) != SecCertificateGetTypeID())
dafebafd
MS
930 goto cleanup;
931
88f1e9c8
MS
932 if ((data = SecCertificateCopyData(cert)) != NULL)
933 {
934 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
935
936 *credentials = cupsArrayNew(NULL, NULL);
937 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
938 CFRelease(data);
939 }
dafebafd
MS
940
941 cleanup :
942
fc4bbb58 943#ifdef HAVE_SECKEYCHAINOPEN
dafebafd
MS
944 if (keychain)
945 CFRelease(keychain);
4daf7e97
MS
946
947 if (syschain)
948 CFRelease(syschain);
fc4bbb58 949#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8
MS
950 if (cert)
951 CFRelease(cert);
dafebafd
MS
952 if (policy)
953 CFRelease(policy);
954 if (query)
955 CFRelease(query);
956
88f1e9c8
MS
957 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
958
959 return (*credentials ? 0 : -1);
72d05bc9
MS
960}
961
962
72d05bc9
MS
963/*
964 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
965 *
e1f19878 966 * @since CUPS 2.0/OS 10.10@
72d05bc9
MS
967 */
968
969int /* O - -1 on error, 0 on success */
970httpSaveCredentials(
f93b32b6 971 const char *path, /* I - Keychain path or @code NULL@ for default */
72d05bc9
MS
972 cups_array_t *credentials, /* I - Credentials */
973 const char *common_name) /* I - Common name for credentials */
974{
88f1e9c8 975 int ret = -1; /* Return value */
41e0907c 976 OSStatus err; /* Error info */
fc4bbb58 977#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8
MS
978 char filename[1024]; /* Filename for keychain */
979 SecKeychainRef keychain = NULL;/* Keychain reference */
fc4bbb58
MS
980 CFArrayRef list; /* Keychain list */
981#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8 982 SecCertificateRef cert = NULL; /* Certificate */
88f1e9c8 983 CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
41e0907c
MS
984
985
807315e6 986 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, (void *)credentials, common_name));
88f1e9c8 987 if (!credentials)
41e0907c
MS
988 goto cleanup;
989
524c65e6
MS
990 if (!httpCredentialsAreValidForName(credentials, common_name))
991 {
992 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
993 return (-1);
994 }
995
88f1e9c8
MS
996 if ((cert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
997 {
998 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
41e0907c 999 goto cleanup;
88f1e9c8 1000 }
41e0907c 1001
fc4bbb58 1002#ifdef HAVE_SECKEYCHAINOPEN
4daf7e97 1003 keychain = http_cdsa_open_keychain(path, filename, sizeof(filename));
2c85b752 1004
4daf7e97 1005 if (!keychain)
88f1e9c8 1006 goto cleanup;
2c85b752 1007
fc4bbb58
MS
1008#else
1009 if (path)
1010 return (-1);
1011#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8 1012
88f1e9c8
MS
1013 if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
1014 {
1015 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
1016 goto cleanup;
2c85b752
MS
1017 }
1018
88f1e9c8 1019 CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
88f1e9c8 1020 CFDictionaryAddValue(attrs, kSecValueRef, cert);
fc4bbb58
MS
1021
1022#ifdef HAVE_SECKEYCHAINOPEN
1023 if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
1024 {
1025 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
1026 goto cleanup;
1027 }
88f1e9c8 1028 CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
fc4bbb58
MS
1029 CFRelease(list);
1030#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752 1031
88f1e9c8 1032 /* Note: SecItemAdd consumes "attrs"... */
524c65e6 1033 err = SecItemAdd(attrs, NULL);
88f1e9c8 1034 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err));
2c85b752 1035
88f1e9c8 1036 cleanup :
2c85b752 1037
fc4bbb58 1038#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8
MS
1039 if (keychain)
1040 CFRelease(keychain);
fc4bbb58 1041#endif /* HAVE_SECKEYCHAINOPEN */
88f1e9c8
MS
1042 if (cert)
1043 CFRelease(cert);
2c85b752 1044
88f1e9c8 1045 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
2c85b752 1046
88f1e9c8 1047 return (ret);
2c85b752
MS
1048}
1049
1050
1051/*
25731360 1052 * '_httpTLSInitialize()' - Initialize the TLS stack.
2c85b752
MS
1053 */
1054
25731360
MS
1055void
1056_httpTLSInitialize(void)
2c85b752
MS
1057{
1058 /*
1059 * Nothing to do...
1060 */
1061}
1062
1063
1064/*
25731360 1065 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
2c85b752
MS
1066 */
1067
25731360
MS
1068size_t
1069_httpTLSPending(http_t *http) /* I - HTTP connection */
2c85b752
MS
1070{
1071 size_t bytes; /* Bytes that are available */
1072
1073
1074 if (!SSLGetBufferedReadSize(http->tls, &bytes))
1075 return (bytes);
1076
1077 return (0);
1078}
1079
1080
1081/*
25731360 1082 * '_httpTLSRead()' - Read from a SSL/TLS connection.
2c85b752
MS
1083 */
1084
25731360
MS
1085int /* O - Bytes read */
1086_httpTLSRead(http_t *http, /* I - HTTP connection */
2c85b752
MS
1087 char *buf, /* I - Buffer to store data */
1088 int len) /* I - Length of buffer */
1089{
1090 int result; /* Return value */
1091 OSStatus error; /* Error info */
1092 size_t processed; /* Number of bytes processed */
1093
1094
7e86f2f6 1095 error = SSLRead(http->tls, buf, (size_t)len, &processed);
25731360 1096 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error,
2c85b752
MS
1097 (int)processed));
1098 switch (error)
1099 {
1100 case 0 :
1101 result = (int)processed;
1102 break;
1103
1104 case errSSLWouldBlock :
1105 if (processed)
1106 result = (int)processed;
1107 else
1108 {
1109 result = -1;
1110 errno = EINTR;
1111 }
1112 break;
1113
1114 case errSSLClosedGraceful :
1115 default :
1116 if (processed)
1117 result = (int)processed;
1118 else
1119 {
1120 result = -1;
1121 errno = EPIPE;
1122 }
1123 break;
1124 }
1125
1126 return (result);
1127}
1128
1129
63aefcd5
MS
1130/*
1131 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1132 */
1133
1134void
8f1fbdec
MS
1135_httpTLSSetOptions(int options, /* I - Options */
1136 int min_version, /* I - Minimum TLS version */
1137 int max_version) /* I - Maximum TLS version */
63aefcd5 1138{
02c88e67 1139 if (!(options & _HTTP_TLS_SET_DEFAULT) || tls_options < 0)
8f1fbdec
MS
1140 {
1141 tls_options = options;
1142 tls_min_version = min_version;
1143 tls_max_version = max_version;
1144 }
63aefcd5
MS
1145}
1146
1147
2c85b752 1148/*
25731360 1149 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
2c85b752
MS
1150 */
1151
25731360
MS
1152int /* O - 0 on success, -1 on failure */
1153_httpTLSStart(http_t *http) /* I - HTTP connection */
2c85b752
MS
1154{
1155 char hostname[256], /* Hostname */
1156 *hostptr; /* Pointer into hostname */
1157 _cups_globals_t *cg = _cupsGlobals();
1158 /* Pointer to library globals */
1159 OSStatus error; /* Error code */
1160 const char *message = NULL;/* Error message */
1161 cups_array_t *credentials; /* Credentials array */
1162 cups_array_t *names; /* CUPS distinguished names */
1163 CFArrayRef dn_array; /* CF distinguished names array */
1164 CFIndex count; /* Number of credentials */
1165 CFDataRef data; /* Certificate data */
1166 int i; /* Looping var */
1167 http_credential_t *credential; /* Credential data */
1168
1169
807315e6 1170 DEBUG_printf(("3_httpTLSStart(http=%p)", (void *)http));
b37d45d9
MS
1171
1172 if (tls_options < 0)
1173 {
1174 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1175 _cupsSetDefaults();
8f1fbdec 1176 DEBUG_printf(("4_httpTLSStart: tls_options=%x, tls_min_version=%d, tls_max_version=%d", tls_options, tls_min_version, tls_max_version));
b37d45d9 1177 }
2c85b752 1178
c913d726 1179#ifdef HAVE_SECKEYCHAINOPEN
41e0907c 1180 if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
2c85b752 1181 {
25731360 1182 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
41e0907c
MS
1183 http->error = errno = EINVAL;
1184 http->status = HTTP_STATUS_ERROR;
1185 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
2c85b752 1186
41e0907c 1187 return (-1);
2c85b752 1188 }
2274d26b 1189#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752 1190
72d05bc9 1191 if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
2c85b752 1192 {
25731360 1193 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
2c85b752
MS
1194 http->error = errno = ENOMEM;
1195 http->status = HTTP_STATUS_ERROR;
1196 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1197
1198 return (-1);
1199 }
1200
1201 error = SSLSetConnection(http->tls, http);
25731360 1202 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error));
2c85b752
MS
1203
1204 if (!error)
1205 {
1206 error = SSLSetIOFuncs(http->tls, http_cdsa_read, http_cdsa_write);
25731360 1207 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error));
2c85b752
MS
1208 }
1209
1210 if (!error)
1211 {
1212 error = SSLSetSessionOption(http->tls, kSSLSessionOptionBreakOnServerAuth,
1213 true);
63aefcd5
MS
1214 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error));
1215 }
1216
1217 if (!error)
1218 {
8f1fbdec
MS
1219 static const SSLProtocol protocols[] = /* Min/max protocol versions */
1220 {
1221 kSSLProtocol3,
1222 kTLSProtocol1,
1223 kTLSProtocol11,
1224 kTLSProtocol12,
9661b112
MS
1225 kTLSProtocol12, /* TODO: update to 1.3 when 1.3 is supported */
1226 kTLSProtocol12 /* TODO: update to 1.3 when 1.3 is supported */
8f1fbdec
MS
1227 };
1228
1229 error = SSLSetProtocolVersionMin(http->tls, protocols[tls_min_version]);
1230 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", protocols[tls_min_version], (int)error));
1231
1232 if (!error)
4f272af7 1233 {
8f1fbdec
MS
1234 error = SSLSetProtocolVersionMax(http->tls, protocols[tls_max_version]);
1235 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMax(%d), error=%d", protocols[tls_max_version], (int)error));
4f272af7 1236 }
63aefcd5
MS
1237 }
1238
ee6226a5 1239# if HAVE_SSLSETENABLEDCIPHERS
63aefcd5
MS
1240 if (!error)
1241 {
1242 SSLCipherSuite supported[100]; /* Supported cipher suites */
1243 size_t num_supported; /* Number of supported cipher suites */
1244 SSLCipherSuite enabled[100]; /* Cipher suites to enable */
1245 size_t num_enabled; /* Number of cipher suites to enable */
1246
1247 num_supported = sizeof(supported) / sizeof(supported[0]);
1248 error = SSLGetSupportedCiphers(http->tls, supported, &num_supported);
1249
1250 if (!error)
1251 {
1252 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported));
1253
1254 for (i = 0, num_enabled = 0; i < (int)num_supported && num_enabled < (sizeof(enabled) / sizeof(enabled[0])); i ++)
1255 {
1256 switch (supported[i])
1257 {
1258 /* Obviously insecure cipher suites that we never want to use */
1259 case SSL_NULL_WITH_NULL_NULL :
1260 case SSL_RSA_WITH_NULL_MD5 :
1261 case SSL_RSA_WITH_NULL_SHA :
1262 case SSL_RSA_EXPORT_WITH_RC4_40_MD5 :
1263 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 :
1264 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA :
1265 case SSL_RSA_WITH_DES_CBC_SHA :
1266 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA :
1267 case SSL_DH_DSS_WITH_DES_CBC_SHA :
1268 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA :
1269 case SSL_DH_RSA_WITH_DES_CBC_SHA :
1270 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA :
1271 case SSL_DHE_DSS_WITH_DES_CBC_SHA :
1272 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA :
1273 case SSL_DHE_RSA_WITH_DES_CBC_SHA :
1274 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 :
1275 case SSL_DH_anon_WITH_RC4_128_MD5 :
1276 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA :
1277 case SSL_DH_anon_WITH_DES_CBC_SHA :
1278 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA :
1279 case SSL_FORTEZZA_DMS_WITH_NULL_SHA :
1280 case TLS_DH_anon_WITH_AES_128_CBC_SHA :
1281 case TLS_DH_anon_WITH_AES_256_CBC_SHA :
1282 case TLS_ECDH_ECDSA_WITH_NULL_SHA :
1283 case TLS_ECDHE_RSA_WITH_NULL_SHA :
1284 case TLS_ECDH_anon_WITH_NULL_SHA :
1285 case TLS_ECDH_anon_WITH_RC4_128_SHA :
1286 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA :
1287 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA :
1288 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA :
1289 case TLS_RSA_WITH_NULL_SHA256 :
1290 case TLS_DH_anon_WITH_AES_128_CBC_SHA256 :
1291 case TLS_DH_anon_WITH_AES_256_CBC_SHA256 :
1292 case TLS_PSK_WITH_NULL_SHA :
1293 case TLS_DHE_PSK_WITH_NULL_SHA :
1294 case TLS_RSA_PSK_WITH_NULL_SHA :
1295 case TLS_DH_anon_WITH_AES_128_GCM_SHA256 :
1296 case TLS_DH_anon_WITH_AES_256_GCM_SHA384 :
1297 case TLS_PSK_WITH_NULL_SHA256 :
1298 case TLS_PSK_WITH_NULL_SHA384 :
1299 case TLS_DHE_PSK_WITH_NULL_SHA256 :
1300 case TLS_DHE_PSK_WITH_NULL_SHA384 :
1301 case TLS_RSA_PSK_WITH_NULL_SHA256 :
1302 case TLS_RSA_PSK_WITH_NULL_SHA384 :
1303 case SSL_RSA_WITH_DES_CBC_MD5 :
b37d45d9 1304 DEBUG_printf(("4_httpTLSStart: Excluding insecure cipher suite %d", supported[i]));
63aefcd5
MS
1305 break;
1306
1307 /* RC4 cipher suites that should only be used as a last resort */
1308 case SSL_RSA_WITH_RC4_128_MD5 :
1309 case SSL_RSA_WITH_RC4_128_SHA :
1310 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
1311 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
1312 case TLS_ECDH_RSA_WITH_RC4_128_SHA :
1313 case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
1314 case TLS_PSK_WITH_RC4_128_SHA :
1315 case TLS_DHE_PSK_WITH_RC4_128_SHA :
1316 case TLS_RSA_PSK_WITH_RC4_128_SHA :
1317 if (tls_options & _HTTP_TLS_ALLOW_RC4)
1318 enabled[num_enabled ++] = supported[i];
b37d45d9
MS
1319 else
1320 DEBUG_printf(("4_httpTLSStart: Excluding RC4 cipher suite %d", supported[i]));
63aefcd5
MS
1321 break;
1322
ee6226a5
MS
1323 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1324 case TLS_DH_DSS_WITH_AES_128_CBC_SHA :
1325 case TLS_DH_RSA_WITH_AES_128_CBC_SHA :
1326 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA :
1327 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
1328 case TLS_DH_DSS_WITH_AES_256_CBC_SHA :
1329 case TLS_DH_RSA_WITH_AES_256_CBC_SHA :
1330 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA :
1331 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
1332 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA :
1333 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA :
ee6226a5
MS
1334 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA :
1335 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256 :
1336 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256 :
1337 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 :
1338 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
1339 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256 :
1340 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256 :
1341 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 :
1342 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
1343 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA :
1344 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA :
1345 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA :
f2e87147
MS
1346 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
1347 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
1348 if (tls_options & _HTTP_TLS_DENY_CBC)
1349 {
1350 DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported[i]));
1351 break;
1352 }
1353
bdc4056c
MS
1354// case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1355// case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
ee6226a5
MS
1356 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256 :
1357 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384 :
bdc4056c
MS
1358// case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1359// case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
ee6226a5
MS
1360 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256 :
1361 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384 :
1362 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
1363 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
ee6226a5
MS
1364 if (tls_options & _HTTP_TLS_ALLOW_DH)
1365 enabled[num_enabled ++] = supported[i];
b37d45d9
MS
1366 else
1367 DEBUG_printf(("4_httpTLSStart: Excluding DH/DHE cipher suite %d", supported[i]));
ee6226a5
MS
1368 break;
1369
f2e87147
MS
1370 case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
1371 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 :
1372 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 :
1373 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 :
1374 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 :
1375 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 :
1376 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 :
1377 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 :
1378 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 :
4f272af7
MS
1379 case TLS_RSA_WITH_3DES_EDE_CBC_SHA :
1380 case TLS_RSA_WITH_AES_128_CBC_SHA :
1381 case TLS_RSA_WITH_AES_256_CBC_SHA :
f2e87147
MS
1382 if (tls_options & _HTTP_TLS_DENY_CBC)
1383 {
1384 DEBUG_printf(("4_httpTLSStart: Excluding CBC cipher suite %d", supported[i]));
1385 break;
1386 }
1387
1388 /* Anything else we'll assume is "secure" */
63aefcd5
MS
1389 default :
1390 enabled[num_enabled ++] = supported[i];
1391 break;
1392 }
1393 }
1394
1395 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled));
1396 error = SSLSetEnabledCiphers(http->tls, enabled, num_enabled);
1397 }
2c85b752 1398 }
ee6226a5 1399#endif /* HAVE_SSLSETENABLEDCIPHERS */
2c85b752 1400
41e0907c 1401 if (!error && http->mode == _HTTP_MODE_CLIENT)
2c85b752 1402 {
41e0907c
MS
1403 /*
1404 * Client: set client-side credentials, if any...
1405 */
1406
2c85b752
MS
1407 if (cg->client_cert_cb)
1408 {
1409 error = SSLSetSessionOption(http->tls,
1410 kSSLSessionOptionBreakOnCertRequested, true);
25731360 1411 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
2c85b752
MS
1412 "error=%d", (int)error));
1413 }
1414 else
1415 {
88f1e9c8
MS
1416 error = http_cdsa_set_credentials(http);
1417 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
2c85b752
MS
1418 (int)error));
1419 }
1420 }
41e0907c
MS
1421 else if (!error)
1422 {
1423 /*
1424 * Server: find/create a certificate for TLS...
1425 */
1426
1427 if (http->fields[HTTP_FIELD_HOST][0])
1428 {
1429 /*
1430 * Use hostname for TLS upgrade...
1431 */
1432
1433 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1434 }
1435 else
1436 {
1437 /*
1438 * Resolve hostname from connection address...
1439 */
1440
1441 http_addr_t addr; /* Connection address */
1442 socklen_t addrlen; /* Length of address */
1443
1444 addrlen = sizeof(addr);
1445 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1446 {
25731360 1447 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
41e0907c
MS
1448 hostname[0] = '\0';
1449 }
1450 else if (httpAddrLocalhost(&addr))
1451 hostname[0] = '\0';
1452 else
a27a134a
MS
1453 {
1454 httpAddrLookup(&addr, hostname, sizeof(hostname));
25731360 1455 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
a27a134a 1456 }
41e0907c
MS
1457 }
1458
a27a134a
MS
1459 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1460 hostname[0] = '\0'; /* Don't allow numeric addresses */
1461
41e0907c
MS
1462 if (hostname[0])
1463 http->tls_credentials = http_cdsa_copy_server(hostname);
1464 else if (tls_common_name)
1465 http->tls_credentials = http_cdsa_copy_server(tls_common_name);
1466
1467 if (!http->tls_credentials && tls_auto_create && (hostname[0] || tls_common_name))
1468 {
25731360 1469 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
41e0907c
MS
1470
1471 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1472 {
25731360 1473 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
41e0907c
MS
1474 http->error = errno = EINVAL;
1475 http->status = HTTP_STATUS_ERROR;
1476 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1477
1478 return (-1);
1479 }
1480
1481 http->tls_credentials = http_cdsa_copy_server(hostname[0] ? hostname : tls_common_name);
1482 }
1483
1484 if (!http->tls_credentials)
1485 {
25731360 1486 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
41e0907c
MS
1487 http->error = errno = EINVAL;
1488 http->status = HTTP_STATUS_ERROR;
1489 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to find server credentials."), 1);
1490
1491 return (-1);
1492 }
1493
1494 error = SSLSetCertificate(http->tls, http->tls_credentials);
1495
25731360 1496 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
41e0907c
MS
1497 }
1498
807315e6 1499 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", (void *)http->tls_credentials));
2c85b752
MS
1500
1501 /*
1502 * Let the server know which hostname/domain we are trying to connect to
1503 * in case it wants to serve up a certificate with a matching common name.
1504 */
1505
41e0907c 1506 if (!error && http->mode == _HTTP_MODE_CLIENT)
2c85b752 1507 {
41e0907c
MS
1508 /*
1509 * Client: get the hostname to use for TLS...
1510 */
1511
1512 if (httpAddrLocalhost(http->hostaddr))
1513 {
1514 strlcpy(hostname, "localhost", sizeof(hostname));
1515 }
1516 else
1517 {
1518 /*
1519 * Otherwise make sure the hostname we have does not end in a trailing dot.
1520 */
1521
1522 strlcpy(hostname, http->hostname, sizeof(hostname));
1523 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1524 *hostptr == '.')
1525 *hostptr = '\0';
1526 }
1527
2c85b752
MS
1528 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
1529
25731360 1530 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error));
2c85b752
MS
1531 }
1532
1533 if (!error)
1534 {
1535 int done = 0; /* Are we done yet? */
1536
1537 while (!error && !done)
1538 {
1539 error = SSLHandshake(http->tls);
1540
25731360 1541 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error));
2c85b752
MS
1542
1543 switch (error)
1544 {
1545 case noErr :
1546 done = 1;
1547 break;
1548
1549 case errSSLWouldBlock :
1550 error = noErr; /* Force a retry */
1551 usleep(1000); /* in 1 millisecond */
1552 break;
1553
1554 case errSSLServerAuthCompleted :
1555 error = 0;
1556 if (cg->server_cert_cb)
1557 {
1558 error = httpCopyCredentials(http, &credentials);
1559 if (!error)
1560 {
1561 error = (cg->server_cert_cb)(http, http->tls, credentials,
1562 cg->server_cert_data);
1563 httpFreeCredentials(credentials);
1564 }
1565
25731360 1566 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
2c85b752
MS
1567 "returned %d.", (int)error));
1568 }
1569 break;
1570
1571 case errSSLClientCertRequested :
1572 error = 0;
1573
1574 if (cg->client_cert_cb)
1575 {
1576 names = NULL;
1577 if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
1578 dn_array)
1579 {
1580 if ((names = cupsArrayNew(NULL, NULL)) != NULL)
1581 {
1582 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
1583 {
1584 data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
1585
1586 if ((credential = malloc(sizeof(*credential))) != NULL)
1587 {
7e86f2f6 1588 credential->datalen = (size_t)CFDataGetLength(data);
2c85b752
MS
1589 if ((credential->data = malloc(credential->datalen)))
1590 {
1591 memcpy((void *)credential->data, CFDataGetBytePtr(data),
1592 credential->datalen);
1593 cupsArrayAdd(names, credential);
1594 }
1595 else
1596 free(credential);
1597 }
1598 }
1599 }
1600
1601 CFRelease(dn_array);
1602 }
1603
1604 if (!error)
1605 {
1606 error = (cg->client_cert_cb)(http, http->tls, names,
1607 cg->client_cert_data);
1608
25731360 1609 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
2c85b752
MS
1610 "returned %d.", (int)error));
1611 }
1612
1613 httpFreeCredentials(names);
1614 }
1615 break;
1616
1617 case errSSLUnknownRootCert :
1618 message = _("Unable to establish a secure connection to host "
1619 "(untrusted certificate).");
1620 break;
1621
1622 case errSSLNoRootCert :
1623 message = _("Unable to establish a secure connection to host "
1624 "(self-signed certificate).");
1625 break;
1626
1627 case errSSLCertExpired :
1628 message = _("Unable to establish a secure connection to host "
1629 "(expired certificate).");
1630 break;
1631
1632 case errSSLCertNotYetValid :
1633 message = _("Unable to establish a secure connection to host "
1634 "(certificate not yet valid).");
1635 break;
1636
1637 case errSSLHostNameMismatch :
1638 message = _("Unable to establish a secure connection to host "
1639 "(host name mismatch).");
1640 break;
1641
1642 case errSSLXCertChainInvalid :
1643 message = _("Unable to establish a secure connection to host "
1644 "(certificate chain invalid).");
1645 break;
1646
1647 case errSSLConnectionRefused :
1648 message = _("Unable to establish a secure connection to host "
1649 "(peer dropped connection before responding).");
1650 break;
1651
1652 default :
1653 break;
1654 }
1655 }
1656 }
1657
1658 if (error)
1659 {
1660 http->error = error;
1661 http->status = HTTP_STATUS_ERROR;
1662 errno = ECONNREFUSED;
1663
1664 CFRelease(http->tls);
1665 http->tls = NULL;
1666
1667 /*
1668 * If an error string wasn't set by the callbacks use a generic one...
1669 */
1670
1671 if (!message)
1672#ifdef HAVE_CSSMERRORSTRING
1673 message = cssmErrorString(error);
1674#else
1675 message = _("Unable to establish a secure connection to host.");
1676#endif /* HAVE_CSSMERRORSTRING */
1677
1678 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
1679
1680 return (-1);
1681 }
1682
1683 return (0);
1684}
1685
1686
1687/*
25731360 1688 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
2c85b752
MS
1689 */
1690
25731360
MS
1691void
1692_httpTLSStop(http_t *http) /* I - HTTP connection */
2c85b752
MS
1693{
1694 while (SSLClose(http->tls) == errSSLWouldBlock)
1695 usleep(1000);
1696
1697 CFRelease(http->tls);
1698
1699 if (http->tls_credentials)
1700 CFRelease(http->tls_credentials);
1701
1702 http->tls = NULL;
1703 http->tls_credentials = NULL;
1704}
1705
1706
1707/*
25731360 1708 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
2c85b752
MS
1709 */
1710
25731360
MS
1711int /* O - Bytes written */
1712_httpTLSWrite(http_t *http, /* I - HTTP connection */
2c85b752
MS
1713 const char *buf, /* I - Buffer holding data */
1714 int len) /* I - Length of buffer */
1715{
1716 ssize_t result; /* Return value */
1717 OSStatus error; /* Error info */
1718 size_t processed; /* Number of bytes processed */
1719
1720
807315e6 1721 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", (void *)http, (void *)buf, len));
2c85b752 1722
7e86f2f6 1723 error = SSLWrite(http->tls, buf, (size_t)len, &processed);
2c85b752
MS
1724
1725 switch (error)
1726 {
1727 case 0 :
1728 result = (int)processed;
1729 break;
1730
1731 case errSSLWouldBlock :
1732 if (processed)
1733 {
1734 result = (int)processed;
1735 }
1736 else
1737 {
1738 result = -1;
1739 errno = EINTR;
1740 }
1741 break;
1742
1743 case errSSLClosedGraceful :
1744 default :
1745 if (processed)
1746 {
1747 result = (int)processed;
1748 }
1749 else
1750 {
1751 result = -1;
1752 errno = EPIPE;
1753 }
1754 break;
1755 }
1756
25731360 1757 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result));
2c85b752
MS
1758
1759 return ((int)result);
1760}
1761
1762
1763/*
88f1e9c8 1764 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
2c85b752
MS
1765 */
1766
88f1e9c8
MS
1767static CFArrayRef /* O - Array of certificates or NULL */
1768http_cdsa_copy_server(
1769 const char *common_name) /* I - Server's hostname */
2c85b752 1770{
2274d26b 1771#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 1772 OSStatus err; /* Error info */
88f1e9c8
MS
1773 SecIdentityRef identity = NULL;/* Identity */
1774 CFArrayRef certificates = NULL;
1775 /* Certificate array */
1776 SecPolicyRef policy = NULL; /* Policy ref */
1777 CFStringRef cfcommon_name = NULL;
1778 /* Server name */
1779 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
1780 CFArrayRef list = NULL; /* Keychain list */
4daf7e97 1781 SecKeychainRef syschain = NULL;/* System keychain */
afd25c34 1782 SecKeychainStatus status = 0; /* Keychain status */
2c85b752 1783
2c85b752 1784
2274d26b
MS
1785 DEBUG_printf(("3http_cdsa_copy_server(common_name=\"%s\")", common_name));
1786
88f1e9c8 1787 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
2c85b752 1788
88f1e9c8
MS
1789 policy = SecPolicyCreateSSL(1, cfcommon_name);
1790
88f1e9c8 1791 if (!policy)
2274d26b
MS
1792 {
1793 DEBUG_puts("4http_cdsa_copy_server: Unable to create SSL policy.");
88f1e9c8 1794 goto cleanup;
2274d26b 1795 }
88f1e9c8
MS
1796
1797 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
2274d26b
MS
1798 {
1799 DEBUG_puts("4http_cdsa_copy_server: Unable to create query dictionary.");
88f1e9c8 1800 goto cleanup;
2274d26b 1801 }
88f1e9c8 1802
f93b32b6
MS
1803 _cupsMutexLock(&tls_mutex);
1804
afd25c34
MS
1805 err = SecKeychainGetStatus(tls_keychain, &status);
1806
1807 if (err == noErr && !(status & kSecUnlockStateStatus) && tls_cups_keychain)
1808 SecKeychainUnlock(tls_keychain, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, TRUE);
1809
88f1e9c8
MS
1810 CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
1811 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
1812 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
1813 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
88f1e9c8 1814
4daf7e97
MS
1815 syschain = http_cdsa_open_system_keychain();
1816
1817 if (syschain)
1818 {
1819 const void *values[2] = { syschain, tls_keychain };
1820
1821 list = CFArrayCreate(kCFAllocatorDefault, (const void **)values, 2, &kCFTypeArrayCallBacks);
1822 }
1823 else
1824 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
1825
fc4bbb58 1826 CFDictionaryAddValue(query, kSecMatchSearchList, list);
88f1e9c8
MS
1827 CFRelease(list);
1828
1829 err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
1830
f93b32b6
MS
1831 _cupsMutexUnlock(&tls_mutex);
1832
2274d26b
MS
1833 if (err != noErr)
1834 {
1835 DEBUG_printf(("4http_cdsa_copy_server: SecItemCopyMatching failed with status %d.", (int)err));
88f1e9c8 1836 goto cleanup;
2274d26b 1837 }
88f1e9c8
MS
1838
1839 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
2274d26b
MS
1840 {
1841 DEBUG_puts("4http_cdsa_copy_server: Search returned something that is not an identity.");
88f1e9c8 1842 goto cleanup;
2274d26b 1843 }
88f1e9c8
MS
1844
1845 if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
2274d26b
MS
1846 {
1847 DEBUG_puts("4http_cdsa_copy_server: Unable to create array of certificates.");
88f1e9c8 1848 goto cleanup;
2274d26b 1849 }
88f1e9c8
MS
1850
1851 cleanup :
1852
4daf7e97
MS
1853 if (syschain)
1854 CFRelease(syschain);
88f1e9c8
MS
1855 if (identity)
1856 CFRelease(identity);
88f1e9c8
MS
1857 if (policy)
1858 CFRelease(policy);
2274d26b
MS
1859 if (cfcommon_name)
1860 CFRelease(cfcommon_name);
88f1e9c8
MS
1861 if (query)
1862 CFRelease(query);
1863
2274d26b
MS
1864 DEBUG_printf(("4http_cdsa_copy_server: Returning %p.", (void *)certificates));
1865
88f1e9c8 1866 return (certificates);
2274d26b
MS
1867#else
1868
1869 if (!tls_selfsigned)
1870 return (NULL);
1871
1872 return (CFArrayCreate(NULL, (const void **)&tls_selfsigned, 1, &kCFTypeArrayCallBacks));
1873#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752
MS
1874}
1875
1876
2ece34a9
MS
1877/*
1878 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1879 */
1880
1881static SecCertificateRef /* O - Certificate */
1882http_cdsa_create_credential(
1883 http_credential_t *credential) /* I - Credential */
1884{
1885 if (!credential)
1886 return (NULL);
1887
1888 return (SecCertificateCreateWithBytes(kCFAllocatorDefault, credential->data, (CFIndex)credential->datalen));
1889}
1890
1891
fc4bbb58 1892#ifdef HAVE_SECKEYCHAINOPEN
005f7f1f
MS
1893/*
1894 * 'http_cdsa_default_path()' - Get the default keychain path.
1895 */
1896
1897static const char * /* O - Keychain path */
1898http_cdsa_default_path(char *buffer, /* I - Path buffer */
1899 size_t bufsize) /* I - Size of buffer */
1900{
1901 const char *home = getenv("HOME"); /* HOME environment variable */
1902
1903
4daf7e97
MS
1904 /*
1905 * Determine the default keychain path. Note that the login and system
1906 * keychains are no longer accessible to user applications starting in macOS
1907 * 10.11.4 (!), so we need to create our own keychain just for CUPS.
1908 */
1909
005f7f1f 1910 if (getuid() && home)
4daf7e97 1911 snprintf(buffer, bufsize, "%s/.cups/ssl.keychain", home);
005f7f1f 1912 else
4daf7e97 1913 strlcpy(buffer, "/etc/cups/ssl.keychain", bufsize);
005f7f1f
MS
1914
1915 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer));
1916
1917 return (buffer);
1918}
4daf7e97
MS
1919
1920
1921/*
1922 * 'http_cdsa_open_keychain()' - Open (or create) a keychain.
1923 */
1924
1925static SecKeychainRef /* O - Keychain or NULL */
1926http_cdsa_open_keychain(
1927 const char *path, /* I - Path to keychain */
1928 char *filename, /* I - Keychain filename */
1929 size_t filesize) /* I - Size of filename buffer */
1930{
1931 SecKeychainRef keychain = NULL;/* Temporary keychain */
1932 OSStatus err; /* Error code */
1933 Boolean interaction; /* Interaction allowed? */
1934 SecKeychainStatus status = 0; /* Keychain status */
1935
1936
1937 /*
1938 * Get the keychain filename...
1939 */
1940
1941 if (!path)
afd25c34 1942 {
4daf7e97 1943 path = http_cdsa_default_path(filename, filesize);
afd25c34
MS
1944 tls_cups_keychain = 1;
1945 }
4daf7e97 1946 else
afd25c34 1947 {
4daf7e97 1948 strlcpy(filename, path, filesize);
afd25c34
MS
1949 tls_cups_keychain = 0;
1950 }
4daf7e97
MS
1951
1952 /*
1953 * Save the interaction setting and disable while we open the keychain...
1954 */
1955
1956 SecKeychainGetUserInteractionAllowed(&interaction);
1957 SecKeychainSetUserInteractionAllowed(FALSE);
1958
afd25c34 1959 if (access(path, R_OK) && tls_cups_keychain)
4daf7e97
MS
1960 {
1961 /*
1962 * Create a new keychain at the given path...
1963 */
1964
1965 err = SecKeychainCreate(path, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, FALSE, NULL, &keychain);
1966 }
1967 else
1968 {
1969 /*
1970 * Open the existing keychain and unlock as needed...
1971 */
1972
1973 err = SecKeychainOpen(path, &keychain);
1974
1975 if (err == noErr)
1976 err = SecKeychainGetStatus(keychain, &status);
1977
afd25c34 1978 if (err == noErr && !(status & kSecUnlockStateStatus) && tls_cups_keychain)
4daf7e97
MS
1979 err = SecKeychainUnlock(keychain, _CUPS_CDSA_PASSLEN, _CUPS_CDSA_PASSWORD, TRUE);
1980 }
1981
1982 /*
1983 * Restore interaction setting...
1984 */
1985
1986 SecKeychainSetUserInteractionAllowed(interaction);
1987
1988 /*
1989 * Release the keychain if we had any errors...
1990 */
1991
1992 if (err != noErr)
1993 {
1994 /* TODO: Set cups last error string */
1995 DEBUG_printf(("4http_cdsa_open_keychain: Unable to open keychain (%d), returning NULL.", (int)err));
1996
1997 if (keychain)
1998 {
1999 CFRelease(keychain);
2000 keychain = NULL;
2001 }
2002 }
2003
2004 /*
2005 * Return the keychain or NULL...
2006 */
2007
2008 return (keychain);
2009}
2010
2011
2012/*
2013 * 'http_cdsa_open_system_keychain()' - Open the System keychain.
2014 */
2015
2016static SecKeychainRef
2017http_cdsa_open_system_keychain(void)
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 * Save the interaction setting and disable while we open the keychain...
2027 */
2028
2029 SecKeychainGetUserInteractionAllowed(&interaction);
2030 SecKeychainSetUserInteractionAllowed(TRUE);
2031
2032 err = SecKeychainOpen("/Library/Keychains/System.keychain", &keychain);
2033
2034 if (err == noErr)
2035 err = SecKeychainGetStatus(keychain, &status);
2036
2037 if (err == noErr && !(status & kSecUnlockStateStatus))
2038 err = errSecInteractionNotAllowed;
2039
2040 /*
2041 * Restore interaction setting...
2042 */
2043
2044 SecKeychainSetUserInteractionAllowed(interaction);
2045
2046 /*
2047 * Release the keychain if we had any errors...
2048 */
2049
2050 if (err != noErr)
2051 {
2052 /* TODO: Set cups last error string */
2053 DEBUG_printf(("4http_cdsa_open_system_keychain: Unable to open keychain (%d), returning NULL.", (int)err));
2054
2055 if (keychain)
2056 {
2057 CFRelease(keychain);
2058 keychain = NULL;
2059 }
2060 }
2061
2062 /*
2063 * Return the keychain or NULL...
2064 */
2065
2066 return (keychain);
2067}
fc4bbb58 2068#endif /* HAVE_SECKEYCHAINOPEN */
005f7f1f
MS
2069
2070
2c85b752 2071/*
88f1e9c8 2072 * 'http_cdsa_read()' - Read function for the CDSA library.
2c85b752
MS
2073 */
2074
88f1e9c8
MS
2075static OSStatus /* O - -1 on error, 0 on success */
2076http_cdsa_read(
2077 SSLConnectionRef connection, /* I - SSL/TLS connection */
2078 void *data, /* I - Data buffer */
2079 size_t *dataLength) /* IO - Number of bytes */
2c85b752 2080{
88f1e9c8
MS
2081 OSStatus result; /* Return value */
2082 ssize_t bytes; /* Number of bytes read */
2083 http_t *http; /* HTTP connection */
2c85b752 2084
2c85b752 2085
88f1e9c8 2086 http = (http_t *)connection;
2c85b752 2087
88f1e9c8 2088 if (!http->blocking)
2c85b752
MS
2089 {
2090 /*
88f1e9c8 2091 * Make sure we have data before we read...
2c85b752
MS
2092 */
2093
88f1e9c8
MS
2094 while (!_httpWait(http, http->wait_value, 0))
2095 {
2096 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2097 continue;
2098
2099 http->error = ETIMEDOUT;
2100 return (-1);
2101 }
2c85b752
MS
2102 }
2103
88f1e9c8 2104 do
2c85b752 2105 {
88f1e9c8 2106 bytes = recv(http->fd, data, *dataLength, 0);
2c85b752 2107 }
88f1e9c8 2108 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2c85b752 2109
88f1e9c8
MS
2110 if ((size_t)bytes == *dataLength)
2111 {
2112 result = 0;
2113 }
2114 else if (bytes > 0)
2115 {
2116 *dataLength = (size_t)bytes;
2117 result = errSSLWouldBlock;
2118 }
2119 else
2120 {
2121 *dataLength = 0;
2c85b752 2122
88f1e9c8
MS
2123 if (bytes == 0)
2124 result = errSSLClosedGraceful;
2125 else if (errno == EAGAIN)
2126 result = errSSLWouldBlock;
2127 else
2128 result = errSSLClosedAbort;
2129 }
2c85b752 2130
88f1e9c8
MS
2131 return (result);
2132}
2c85b752 2133
2c85b752 2134
88f1e9c8
MS
2135/*
2136 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
2137 */
2c85b752 2138
88f1e9c8
MS
2139static int /* O - Status of connection */
2140http_cdsa_set_credentials(http_t *http) /* I - HTTP connection */
2141{
2142 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2143 OSStatus error = 0; /* Error code */
2144 http_tls_credentials_t credentials = NULL;
2145 /* TLS credentials */
2c85b752 2146
2c85b752 2147
807315e6 2148 DEBUG_printf(("7http_tls_set_credentials(%p)", (void *)http));
2c85b752 2149
88f1e9c8
MS
2150 /*
2151 * Prefer connection specific credentials...
2152 */
2c85b752 2153
88f1e9c8
MS
2154 if ((credentials = http->tls_credentials) == NULL)
2155 credentials = cg->tls_credentials;
2c85b752 2156
88f1e9c8
MS
2157 if (credentials)
2158 {
2159 error = SSLSetCertificate(http->tls, credentials);
2160 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
2161 (int)error));
2c85b752 2162 }
88f1e9c8
MS
2163 else
2164 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
2165
2166 return (error);
2167}
2168
2169
2170/*
2171 * 'http_cdsa_write()' - Write function for the CDSA library.
2172 */
2173
2174static OSStatus /* O - -1 on error, 0 on success */
2175http_cdsa_write(
2176 SSLConnectionRef connection, /* I - SSL/TLS connection */
2177 const void *data, /* I - Data buffer */
2178 size_t *dataLength) /* IO - Number of bytes */
2179{
2180 OSStatus result; /* Return value */
2181 ssize_t bytes; /* Number of bytes read */
2182 http_t *http; /* HTTP connection */
2c85b752 2183
2c85b752 2184
88f1e9c8
MS
2185 http = (http_t *)connection;
2186
2187 do
2c85b752 2188 {
88f1e9c8
MS
2189 bytes = write(http->fd, data, *dataLength);
2190 }
2191 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2192
2193 if ((size_t)bytes == *dataLength)
2194 {
2195 result = 0;
2196 }
2197 else if (bytes >= 0)
2198 {
2199 *dataLength = (size_t)bytes;
2200 result = errSSLWouldBlock;
2c85b752
MS
2201 }
2202 else
88f1e9c8
MS
2203 {
2204 *dataLength = 0;
2c85b752 2205
88f1e9c8
MS
2206 if (errno == EAGAIN)
2207 result = errSSLWouldBlock;
2208 else
2209 result = errSSLClosedAbort;
2210 }
2211
2212 return (result);
2c85b752 2213}