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