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