]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/tls-darwin.c
Import CUPS v2.0.2
[thirdparty/cups.git] / cups / tls-darwin.c
CommitLineData
1a18c85c 1/*
4ef75dec 2 * "$Id: tls-darwin.c 12481 2015-02-03 12:45:14Z msweet $"
1a18c85c
MS
3 *
4 * TLS support code for CUPS on OS X.
5 *
4ef75dec 6 * Copyright 2007-2015 by Apple Inc.
1a18c85c
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
b9367124 18/**** This file is included from tls.c ****/
1a18c85c
MS
19
20/*
21 * Include necessary headers...
22 */
23
24#include <spawn.h>
25
26extern char **environ;
27
28
86243a75
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
1a18c85c
MS
37/*
38 * Local globals...
39 */
40
41#ifdef HAVE_SECKEYCHAINOPEN
42static int tls_auto_create = 0;
43 /* Auto-create self-signed certs? */
44static char *tls_common_name = NULL;
45 /* Default common name */
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 */
86243a75 52static int tls_options = 0;/* Options for TLS connections */
1a18c85c
MS
53#endif /* HAVE_SECKEYCHAINOPEN */
54
55
56/*
57 * Local functions...
58 */
59
60#ifdef HAVE_SECKEYCHAINOPEN
61static CFArrayRef http_cdsa_copy_server(const char *common_name);
62#endif /* HAVE_SECKEYCHAINOPEN */
63static SecCertificateRef http_cdsa_create_credential(http_credential_t *credential);
64static const char *http_cdsa_default_path(char *buffer, size_t bufsize);
65static OSStatus http_cdsa_read(SSLConnectionRef connection, void *data, size_t *dataLength);
66static int http_cdsa_set_credentials(http_t *http);
67static OSStatus http_cdsa_write(SSLConnectionRef connection, const void *data, size_t *dataLength);
68
69
70/*
71 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
72 *
5d2cc5d3 73 * @since CUPS 2.0/OS 10.10@
1a18c85c
MS
74 */
75
76int /* O - 1 on success, 0 on failure */
77cupsMakeServerCredentials(
78 const char *path, /* I - Keychain path or @code NULL@ for default */
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{
84#if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE) && defined(HAVE_SECKEYCHAINOPEN)
85 char filename[1024]; /* Default keychain path */
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
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
101 (void)num_alt_names;
102 (void)alt_names;
103 (void)expiration_date;
104
105 if (!path)
106 path = http_cdsa_default_path(filename, sizeof(filename));
107
108 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
109 if (!cfcommon_name)
110 goto cleanup;
111
112 /*
113 * Create a public/private key pair...
114 */
115
116 keyParams = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
117 if (!keyParams)
118 goto cleanup;
119
120 CFDictionaryAddValue(keyParams, kSecAttrKeyType, kSecAttrKeyTypeRSA);
121 CFDictionaryAddValue(keyParams, kSecAttrKeySizeInBits, CFSTR("2048"));
122 CFDictionaryAddValue(keyParams, kSecAttrLabel, CFSTR("CUPS Self-Signed Certificate"));
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
186#else /* !(HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN) */
187 int pid, /* Process ID of command */
188 status, /* Status of command */
189 i; /* Looping var */
190 char command[1024], /* Command */
191 *argv[4], /* Command-line arguments */
192 *envp[1000], /* Environment variables */
193 days[32], /* CERTTOOL_EXPIRATION_DAYS env var */
194 keychain[1024], /* Keychain argument */
195 infofile[1024], /* Type-in information for cert */
196 filename[1024]; /* Default keychain path */
197 cups_file_t *fp; /* Seed/info file */
198
199
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
202 (void)num_alt_names;
203 (void)alt_names;
204
205 if (!path)
206 path = http_cdsa_default_path(filename, sizeof(filename));
207
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
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
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);
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);
266
267 if (posix_spawn(&pid, command, &actions, NULL, argv, envp))
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);
285#endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
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 *
5d2cc5d3 295 * @since CUPS 2.0/OS X 10.10@
1a18c85c
MS
296 */
297
298int /* O - 1 on success, 0 on failure */
299cupsSetServerCredentials(
300 const char *path, /* I - Keychain path or @code NULL@ for default */
301 const char *common_name, /* I - Default common name for server */
302 int auto_create) /* I - 1 = automatically create self-signed certificates */
303{
304 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
305
306#ifdef HAVE_SECKEYCHAINOPEN
307 char filename[1024]; /* Filename for keychain */
308 SecKeychainRef keychain = NULL;/* Temporary keychain */
309
310
311 if (!path)
312 path = http_cdsa_default_path(filename, sizeof(filename));
313
314 if (SecKeychainOpen(path, &keychain) != noErr)
315 {
316 /* TODO: Set cups last error string */
317 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain, returning 0.");
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
330 if (tls_keypath)
331 _cupsStrFree(tls_keypath);
332
333 if (tls_common_name)
334 _cupsStrFree(tls_common_name);
335
336 /*
337 * Save the new keychain...
338 */
339
340 tls_keychain = keychain;
341 tls_keypath = _cupsStrAlloc(path);
342 tls_auto_create = auto_create;
343 tls_common_name = _cupsStrAlloc(common_name);
344
345 _cupsMutexUnlock(&tls_mutex);
346
347 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
348 return (1);
349
350#else
351 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
352 return (0);
353#endif /* HAVE_SECKEYCHAINOPEN */
354}
355
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
377 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
378
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 {
387 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust)));
388
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);
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
408 if ((data = SecCertificateCopyData(secCert)) != NULL)
409 {
410 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
411
412 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
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 */
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 {
450 if ((secCert = http_cdsa_create_credential(credential)) != NULL)
451 {
452 CFArrayAppendValue(peerCerts, secCert);
453 CFRelease(secCert);
454 }
455 }
456
457 return (peerCerts);
458}
459
460
461/*
462 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
463 *
5d2cc5d3 464 * @since CUPS 2.0/OS X 10.10@
1a18c85c
MS
465 */
466
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 *
5d2cc5d3 527 * @since CUPS 2.0/OS X 10.10@
1a18c85c
MS
528 */
529
530http_trust_t /* O - Level of trust */
531httpCredentialsGetTrust(
532 cups_array_t *credentials, /* I - Credentials */
533 const char *common_name) /* I - Common name for trust lookup */
534{
535 SecCertificateRef secCert; /* Certificate reference */
536 http_trust_t trust = HTTP_TRUST_OK;
537 /* Trusted? */
538 cups_array_t *tcreds = NULL; /* Trusted credentials */
539 _cups_globals_t *cg = _cupsGlobals();
540 /* Per-thread globals */
541
542
543 if (!common_name)
544 return (HTTP_TRUST_UNKNOWN);
545
546 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
547 return (HTTP_TRUST_UNKNOWN);
548
4ef75dec
MS
549 if (cg->any_root < 0)
550 _cupsSetDefaults();
551
1a18c85c
MS
552 /*
553 * Look this common name up in the default keychains...
554 */
555
556 httpLoadCredentials(NULL, &tcreds, common_name);
557
558 if (tcreds)
559 {
560 char credentials_str[1024], /* String for incoming credentials */
561 tcreds_str[1024]; /* String for saved credentials */
562
563 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
564 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
565
566 if (strcmp(credentials_str, tcreds_str))
567 {
568 /*
569 * Credentials don't match, let's look at the expiration date of the new
570 * credentials and allow if the new ones have a later expiration...
571 */
572
573 if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds) ||
574 !httpCredentialsAreValidForName(credentials, common_name))
575 {
576 /*
577 * Either the new credentials are not newly issued, or the common name
578 * does not match the issued certificate...
579 */
580
581 trust = HTTP_TRUST_INVALID;
582 }
583 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
584 {
585 /*
586 * Save the renewed credentials...
587 */
588
589 trust = HTTP_TRUST_RENEWED;
590
591 httpSaveCredentials(NULL, credentials, common_name);
592 }
593 }
594
595 httpFreeCredentials(tcreds);
596 }
597 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
598 trust = HTTP_TRUST_INVALID;
599
600 if (!cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
601 trust = HTTP_TRUST_EXPIRED;
602 else if (!cg->any_root && cupsArrayCount(credentials) == 1)
603 trust = HTTP_TRUST_INVALID;
604
605 CFRelease(secCert);
606
607 return (trust);
608}
609
610
611/*
612 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
613 *
5d2cc5d3 614 * @since CUPS 2.0/OS X 10.10@
1a18c85c
MS
615 */
616
617time_t /* O - Expiration date of credentials */
618httpCredentialsGetExpiration(
619 cups_array_t *credentials) /* I - Credentials */
620{
621 SecCertificateRef secCert; /* Certificate reference */
622 time_t expiration; /* Expiration date */
623
624
625 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
626 return (0);
627
628 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
629
630 CFRelease(secCert);
631
632 return (expiration);
633}
634
635
636/*
637 * 'httpCredentialsString()' - Return a string representing the credentials.
638 *
5d2cc5d3 639 * @since CUPS 2.0/OS X 10.10@
1a18c85c
MS
640 */
641
642size_t /* O - Total size of credentials string */
643httpCredentialsString(
644 cups_array_t *credentials, /* I - Credentials */
645 char *buffer, /* I - Buffer or @code NULL@ */
646 size_t bufsize) /* I - Size of buffer */
647{
648 http_credential_t *first; /* First certificate */
649 SecCertificateRef secCert; /* Certificate reference */
650
651
652 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
653
654 if (!buffer)
655 return (0);
656
657 if (buffer && bufsize > 0)
658 *buffer = '\0';
659
660 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
661 (secCert = http_cdsa_create_credential(first)) != NULL)
662 {
663 CFStringRef cf_name; /* CF common name string */
664 char name[256]; /* Common name associated with cert */
665 time_t expiration; /* Expiration date of cert */
666 _cups_md5_state_t md5_state; /* MD5 state */
667 unsigned char md5_digest[16]; /* MD5 result */
668
669 if ((cf_name = SecCertificateCopySubjectSummary(secCert)) != NULL)
670 {
671 CFStringGetCString(cf_name, name, (CFIndex)sizeof(name), kCFStringEncodingUTF8);
672 CFRelease(cf_name);
673 }
674 else
675 strlcpy(name, "unknown", sizeof(name));
676
677 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
678
679 _cupsMD5Init(&md5_state);
680 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
681 _cupsMD5Finish(&md5_state, md5_digest);
682
683 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]);
684
685 CFRelease(secCert);
686 }
687
688 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
689
690 return (strlen(buffer));
691}
692
693
694/*
695 * '_httpFreeCredentials()' - Free internal credentials.
696 */
697
698void
699_httpFreeCredentials(
700 http_tls_credentials_t credentials) /* I - Internal credentials */
701{
702 if (!credentials)
703 return;
704
705 CFRelease(credentials);
706}
707
708
709/*
710 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
711 *
5d2cc5d3 712 * @since CUPS 2.0/OS 10.10@
1a18c85c
MS
713 */
714
715int /* O - 0 on success, -1 on error */
716httpLoadCredentials(
717 const char *path, /* I - Keychain path or @code NULL@ for default */
718 cups_array_t **credentials, /* IO - Credentials */
719 const char *common_name) /* I - Common name for credentials */
720{
721#ifdef HAVE_SECKEYCHAINOPEN
722 OSStatus err; /* Error info */
723 char filename[1024]; /* Filename for keychain */
724 SecKeychainRef keychain = NULL;/* Keychain reference */
725 SecIdentitySearchRef search = NULL; /* Search reference */
726 SecCertificateRef cert = NULL; /* Certificate */
727 CFDataRef data; /* Certificate data */
728 SecPolicyRef policy = NULL; /* Policy ref */
729 CFStringRef cfcommon_name = NULL;
730 /* Server name */
731 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
732 CFArrayRef list = NULL; /* Keychain list */
733
734
735 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
736
737 if (!credentials)
738 return (-1);
739
740 *credentials = NULL;
741
742 if (!path)
743 path = http_cdsa_default_path(filename, sizeof(filename));
744
745 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
746 goto cleanup;
747
748 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
749
750 policy = SecPolicyCreateSSL(1, cfcommon_name);
751
752 if (cfcommon_name)
753 CFRelease(cfcommon_name);
754
755 if (!policy)
756 goto cleanup;
757
758 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
759 goto cleanup;
760
761 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
762
763 CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
764 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
765 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
766 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
767 CFDictionaryAddValue(query, kSecMatchSearchList, list);
768
769 CFRelease(list);
770
771 err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
772
773 if (err)
774 goto cleanup;
775
776 if (CFGetTypeID(cert) != SecCertificateGetTypeID())
777 goto cleanup;
778
779 if ((data = SecCertificateCopyData(cert)) != NULL)
780 {
781 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
782
783 *credentials = cupsArrayNew(NULL, NULL);
784 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
785 CFRelease(data);
786 }
787
788 cleanup :
789
790 if (keychain)
791 CFRelease(keychain);
792 if (search)
793 CFRelease(search);
794 if (cert)
795 CFRelease(cert);
796 if (policy)
797 CFRelease(policy);
798 if (query)
799 CFRelease(query);
800
801 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
802
803 return (*credentials ? 0 : -1);
804
805#else
806 (void)path;
807 (void)credentials;
808 (void)common_name;
809
810 return (-1);
811#endif /* HAVE_SECKEYCHAINOPEN */
812}
813
814
815/*
816 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
817 *
5d2cc5d3 818 * @since CUPS 2.0/OS 10.10@
1a18c85c
MS
819 */
820
821int /* O - -1 on error, 0 on success */
822httpSaveCredentials(
823 const char *path, /* I - Keychain path or @code NULL@ for default */
824 cups_array_t *credentials, /* I - Credentials */
825 const char *common_name) /* I - Common name for credentials */
826{
827#ifdef HAVE_SECKEYCHAINOPEN
828 int ret = -1; /* Return value */
829 OSStatus err; /* Error info */
830 char filename[1024]; /* Filename for keychain */
831 SecKeychainRef keychain = NULL;/* Keychain reference */
832 SecIdentitySearchRef search = NULL; /* Search reference */
833 SecCertificateRef cert = NULL; /* Certificate */
834 CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
835 CFArrayRef list = NULL; /* Keychain list */
836
837
838 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
839 if (!credentials)
840 goto cleanup;
841
842 if (!httpCredentialsAreValidForName(credentials, common_name))
843 {
844 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
845 return (-1);
846 }
847
848 if ((cert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
849 {
850 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
851 goto cleanup;
852 }
853
854 if (!path)
855 path = http_cdsa_default_path(filename, sizeof(filename));
856
857 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
858 {
859 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err));
860 goto cleanup;
861 }
862
863 if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
864 {
865 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
866 goto cleanup;
867 }
868
869 if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
870 {
871 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
872 goto cleanup;
873 }
874
875 CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
876 CFDictionaryAddValue(attrs, kSecValueRef, cert);
877 CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
878
879 /* Note: SecItemAdd consumes "attrs"... */
880 err = SecItemAdd(attrs, NULL);
881 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err));
882
883 cleanup :
884
885 if (list)
886 CFRelease(list);
887 if (keychain)
888 CFRelease(keychain);
889 if (search)
890 CFRelease(search);
891 if (cert)
892 CFRelease(cert);
893
894 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
895
896 return (ret);
897
898#else
899 (void)path;
900 (void)credentials;
901 (void)common_name;
902
903 return (-1);
904#endif /* HAVE_SECKEYCHAINOPEN */
905}
906
907
908/*
909 * '_httpTLSInitialize()' - Initialize the TLS stack.
910 */
911
912void
913_httpTLSInitialize(void)
914{
915 /*
916 * Nothing to do...
917 */
918}
919
920
921/*
922 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
923 */
924
925size_t
926_httpTLSPending(http_t *http) /* I - HTTP connection */
927{
928 size_t bytes; /* Bytes that are available */
929
930
931 if (!SSLGetBufferedReadSize(http->tls, &bytes))
932 return (bytes);
933
934 return (0);
935}
936
937
938/*
939 * '_httpTLSRead()' - Read from a SSL/TLS connection.
940 */
941
942int /* O - Bytes read */
943_httpTLSRead(http_t *http, /* I - HTTP connection */
944 char *buf, /* I - Buffer to store data */
945 int len) /* I - Length of buffer */
946{
947 int result; /* Return value */
948 OSStatus error; /* Error info */
949 size_t processed; /* Number of bytes processed */
950
951
952 error = SSLRead(http->tls, buf, (size_t)len, &processed);
953 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error,
954 (int)processed));
955 switch (error)
956 {
957 case 0 :
958 result = (int)processed;
959 break;
960
961 case errSSLWouldBlock :
962 if (processed)
963 result = (int)processed;
964 else
965 {
966 result = -1;
967 errno = EINTR;
968 }
969 break;
970
971 case errSSLClosedGraceful :
972 default :
973 if (processed)
974 result = (int)processed;
975 else
976 {
977 result = -1;
978 errno = EPIPE;
979 }
980 break;
981 }
982
983 return (result);
984}
985
986
86243a75
MS
987/*
988 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
989 */
990
991void
992_httpTLSSetOptions(int options) /* I - Options */
993{
994 tls_options = options;
995}
996
997
1a18c85c
MS
998/*
999 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1000 */
1001
1002int /* O - 0 on success, -1 on failure */
1003_httpTLSStart(http_t *http) /* I - HTTP connection */
1004{
1005 char hostname[256], /* Hostname */
1006 *hostptr; /* Pointer into hostname */
1007 _cups_globals_t *cg = _cupsGlobals();
1008 /* Pointer to library globals */
1009 OSStatus error; /* Error code */
1010 const char *message = NULL;/* Error message */
1011 cups_array_t *credentials; /* Credentials array */
1012 cups_array_t *names; /* CUPS distinguished names */
1013 CFArrayRef dn_array; /* CF distinguished names array */
1014 CFIndex count; /* Number of credentials */
1015 CFDataRef data; /* Certificate data */
1016 int i; /* Looping var */
1017 http_credential_t *credential; /* Credential data */
1018
1019
1020 DEBUG_printf(("7_httpTLSStart(http=%p)", http));
1021
1022#ifdef HAVE_SECKEYCHAINOPEN
1023 if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
1024#else
1025 if (http->mode == _HTTP_MODE_SERVER)
1026#endif /* HAVE_SECKEYCHAINOPEN */
1027 {
1028 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1029 http->error = errno = EINVAL;
1030 http->status = HTTP_STATUS_ERROR;
1031 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
1032
1033 return (-1);
1034 }
1035
1036 if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
1037 {
1038 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
1039 http->error = errno = ENOMEM;
1040 http->status = HTTP_STATUS_ERROR;
1041 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1042
1043 return (-1);
1044 }
1045
1046 error = SSLSetConnection(http->tls, http);
1047 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error));
1048
1049 if (!error)
1050 {
1051 error = SSLSetIOFuncs(http->tls, http_cdsa_read, http_cdsa_write);
1052 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error));
1053 }
1054
1055 if (!error)
1056 {
1057 error = SSLSetSessionOption(http->tls, kSSLSessionOptionBreakOnServerAuth,
1058 true);
86243a75
MS
1059 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error));
1060 }
1061
1062 if (!error)
1063 {
1064 error = SSLSetProtocolVersionMin(http->tls, (tls_options & _HTTP_TLS_ALLOW_SSL3) ? kSSLProtocol3 : kTLSProtocol1);
1065 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin, error=%d", (int)error));
1066 }
1067
1068# if USE_SET_ENABLED_CIPHERS
1069 if (!error)
1070 {
1071 SSLCipherSuite supported[100]; /* Supported cipher suites */
1072 size_t num_supported; /* Number of supported cipher suites */
1073 SSLCipherSuite enabled[100]; /* Cipher suites to enable */
1074 size_t num_enabled; /* Number of cipher suites to enable */
1075
1076 num_supported = sizeof(supported) / sizeof(supported[0]);
1077 error = SSLGetSupportedCiphers(http->tls, supported, &num_supported);
1078
1079 if (!error)
1080 {
1081 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported));
1082
1083 for (i = 0, num_enabled = 0; i < (int)num_supported && num_enabled < (sizeof(enabled) / sizeof(enabled[0])); i ++)
1084 {
1085 switch (supported[i])
1086 {
1087 /* Obviously insecure cipher suites that we never want to use */
1088 case SSL_NULL_WITH_NULL_NULL :
1089 case SSL_RSA_WITH_NULL_MD5 :
1090 case SSL_RSA_WITH_NULL_SHA :
1091 case SSL_RSA_EXPORT_WITH_RC4_40_MD5 :
1092 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 :
1093 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA :
1094 case SSL_RSA_WITH_DES_CBC_SHA :
1095 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA :
1096 case SSL_DH_DSS_WITH_DES_CBC_SHA :
1097 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA :
1098 case SSL_DH_RSA_WITH_DES_CBC_SHA :
1099 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA :
1100 case SSL_DHE_DSS_WITH_DES_CBC_SHA :
1101 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA :
1102 case SSL_DHE_RSA_WITH_DES_CBC_SHA :
1103 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 :
1104 case SSL_DH_anon_WITH_RC4_128_MD5 :
1105 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA :
1106 case SSL_DH_anon_WITH_DES_CBC_SHA :
1107 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA :
1108 case SSL_FORTEZZA_DMS_WITH_NULL_SHA :
1109 case TLS_DH_anon_WITH_AES_128_CBC_SHA :
1110 case TLS_DH_anon_WITH_AES_256_CBC_SHA :
1111 case TLS_ECDH_ECDSA_WITH_NULL_SHA :
1112 case TLS_ECDHE_RSA_WITH_NULL_SHA :
1113 case TLS_ECDH_anon_WITH_NULL_SHA :
1114 case TLS_ECDH_anon_WITH_RC4_128_SHA :
1115 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA :
1116 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA :
1117 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA :
1118 case TLS_RSA_WITH_NULL_SHA256 :
1119 case TLS_DH_anon_WITH_AES_128_CBC_SHA256 :
1120 case TLS_DH_anon_WITH_AES_256_CBC_SHA256 :
1121 case TLS_PSK_WITH_NULL_SHA :
1122 case TLS_DHE_PSK_WITH_NULL_SHA :
1123 case TLS_RSA_PSK_WITH_NULL_SHA :
1124 case TLS_DH_anon_WITH_AES_128_GCM_SHA256 :
1125 case TLS_DH_anon_WITH_AES_256_GCM_SHA384 :
1126 case TLS_PSK_WITH_NULL_SHA256 :
1127 case TLS_PSK_WITH_NULL_SHA384 :
1128 case TLS_DHE_PSK_WITH_NULL_SHA256 :
1129 case TLS_DHE_PSK_WITH_NULL_SHA384 :
1130 case TLS_RSA_PSK_WITH_NULL_SHA256 :
1131 case TLS_RSA_PSK_WITH_NULL_SHA384 :
1132 case SSL_RSA_WITH_DES_CBC_MD5 :
1133 break;
1134
1135 /* RC4 cipher suites that should only be used as a last resort */
1136 case SSL_RSA_WITH_RC4_128_MD5 :
1137 case SSL_RSA_WITH_RC4_128_SHA :
1138 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
1139 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
1140 case TLS_ECDH_RSA_WITH_RC4_128_SHA :
1141 case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
1142 case TLS_PSK_WITH_RC4_128_SHA :
1143 case TLS_DHE_PSK_WITH_RC4_128_SHA :
1144 case TLS_RSA_PSK_WITH_RC4_128_SHA :
1145 if (tls_options & _HTTP_TLS_ALLOW_RC4)
1146 enabled[num_enabled ++] = supported[i];
1147 break;
1148
1149 /* Anything else we'll assume is secure */
1150 default :
1151 enabled[num_enabled ++] = supported[i];
1152 break;
1153 }
1154 }
1155
1156 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled));
1157 error = SSLSetEnabledCiphers(http->tls, enabled, num_enabled);
1158 }
1a18c85c 1159 }
86243a75 1160#endif /* USE_SET_ENABLED_CIPHERS */
1a18c85c
MS
1161
1162 if (!error && http->mode == _HTTP_MODE_CLIENT)
1163 {
1164 /*
1165 * Client: set client-side credentials, if any...
1166 */
1167
1168 if (cg->client_cert_cb)
1169 {
1170 error = SSLSetSessionOption(http->tls,
1171 kSSLSessionOptionBreakOnCertRequested, true);
1172 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
1173 "error=%d", (int)error));
1174 }
1175 else
1176 {
1177 error = http_cdsa_set_credentials(http);
1178 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
1179 (int)error));
1180 }
1181 }
1182 else if (!error)
1183 {
1184 /*
1185 * Server: find/create a certificate for TLS...
1186 */
1187
1188 if (http->fields[HTTP_FIELD_HOST][0])
1189 {
1190 /*
1191 * Use hostname for TLS upgrade...
1192 */
1193
1194 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1195 }
1196 else
1197 {
1198 /*
1199 * Resolve hostname from connection address...
1200 */
1201
1202 http_addr_t addr; /* Connection address */
1203 socklen_t addrlen; /* Length of address */
1204
1205 addrlen = sizeof(addr);
1206 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1207 {
1208 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
1209 hostname[0] = '\0';
1210 }
1211 else if (httpAddrLocalhost(&addr))
1212 hostname[0] = '\0';
1213 else
1214 {
1215 httpAddrLookup(&addr, hostname, sizeof(hostname));
1216 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
1217 }
1218 }
1219
1220#ifdef HAVE_SECKEYCHAINOPEN
1221 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1222 hostname[0] = '\0'; /* Don't allow numeric addresses */
1223
1224 if (hostname[0])
1225 http->tls_credentials = http_cdsa_copy_server(hostname);
1226 else if (tls_common_name)
1227 http->tls_credentials = http_cdsa_copy_server(tls_common_name);
1228
1229 if (!http->tls_credentials && tls_auto_create && (hostname[0] || tls_common_name))
1230 {
1231 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
1232
1233 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1234 {
1235 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1236 http->error = errno = EINVAL;
1237 http->status = HTTP_STATUS_ERROR;
1238 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1239
1240 return (-1);
1241 }
1242
1243 http->tls_credentials = http_cdsa_copy_server(hostname[0] ? hostname : tls_common_name);
1244 }
1245#endif /* HAVE_SECKEYCHAINOPEN */
1246
1247 if (!http->tls_credentials)
1248 {
1249 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
1250 http->error = errno = EINVAL;
1251 http->status = HTTP_STATUS_ERROR;
1252 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to find server credentials."), 1);
1253
1254 return (-1);
1255 }
1256
1257 error = SSLSetCertificate(http->tls, http->tls_credentials);
1258
1259 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
1260 }
1261
1262 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http->tls_credentials));
1263
1264 /*
1265 * Let the server know which hostname/domain we are trying to connect to
1266 * in case it wants to serve up a certificate with a matching common name.
1267 */
1268
1269 if (!error && http->mode == _HTTP_MODE_CLIENT)
1270 {
1271 /*
1272 * Client: get the hostname to use for TLS...
1273 */
1274
1275 if (httpAddrLocalhost(http->hostaddr))
1276 {
1277 strlcpy(hostname, "localhost", sizeof(hostname));
1278 }
1279 else
1280 {
1281 /*
1282 * Otherwise make sure the hostname we have does not end in a trailing dot.
1283 */
1284
1285 strlcpy(hostname, http->hostname, sizeof(hostname));
1286 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1287 *hostptr == '.')
1288 *hostptr = '\0';
1289 }
1290
1291 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
1292
1293 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error));
1294 }
1295
1296 if (!error)
1297 {
1298 int done = 0; /* Are we done yet? */
1299
1300 while (!error && !done)
1301 {
1302 error = SSLHandshake(http->tls);
1303
1304 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error));
1305
1306 switch (error)
1307 {
1308 case noErr :
1309 done = 1;
1310 break;
1311
1312 case errSSLWouldBlock :
1313 error = noErr; /* Force a retry */
1314 usleep(1000); /* in 1 millisecond */
1315 break;
1316
1317 case errSSLServerAuthCompleted :
1318 error = 0;
1319 if (cg->server_cert_cb)
1320 {
1321 error = httpCopyCredentials(http, &credentials);
1322 if (!error)
1323 {
1324 error = (cg->server_cert_cb)(http, http->tls, credentials,
1325 cg->server_cert_data);
1326 httpFreeCredentials(credentials);
1327 }
1328
1329 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
1330 "returned %d.", (int)error));
1331 }
1332 break;
1333
1334 case errSSLClientCertRequested :
1335 error = 0;
1336
1337 if (cg->client_cert_cb)
1338 {
1339 names = NULL;
1340 if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
1341 dn_array)
1342 {
1343 if ((names = cupsArrayNew(NULL, NULL)) != NULL)
1344 {
1345 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
1346 {
1347 data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
1348
1349 if ((credential = malloc(sizeof(*credential))) != NULL)
1350 {
1351 credential->datalen = (size_t)CFDataGetLength(data);
1352 if ((credential->data = malloc(credential->datalen)))
1353 {
1354 memcpy((void *)credential->data, CFDataGetBytePtr(data),
1355 credential->datalen);
1356 cupsArrayAdd(names, credential);
1357 }
1358 else
1359 free(credential);
1360 }
1361 }
1362 }
1363
1364 CFRelease(dn_array);
1365 }
1366
1367 if (!error)
1368 {
1369 error = (cg->client_cert_cb)(http, http->tls, names,
1370 cg->client_cert_data);
1371
1372 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
1373 "returned %d.", (int)error));
1374 }
1375
1376 httpFreeCredentials(names);
1377 }
1378 break;
1379
1380 case errSSLUnknownRootCert :
1381 message = _("Unable to establish a secure connection to host "
1382 "(untrusted certificate).");
1383 break;
1384
1385 case errSSLNoRootCert :
1386 message = _("Unable to establish a secure connection to host "
1387 "(self-signed certificate).");
1388 break;
1389
1390 case errSSLCertExpired :
1391 message = _("Unable to establish a secure connection to host "
1392 "(expired certificate).");
1393 break;
1394
1395 case errSSLCertNotYetValid :
1396 message = _("Unable to establish a secure connection to host "
1397 "(certificate not yet valid).");
1398 break;
1399
1400 case errSSLHostNameMismatch :
1401 message = _("Unable to establish a secure connection to host "
1402 "(host name mismatch).");
1403 break;
1404
1405 case errSSLXCertChainInvalid :
1406 message = _("Unable to establish a secure connection to host "
1407 "(certificate chain invalid).");
1408 break;
1409
1410 case errSSLConnectionRefused :
1411 message = _("Unable to establish a secure connection to host "
1412 "(peer dropped connection before responding).");
1413 break;
1414
1415 default :
1416 break;
1417 }
1418 }
1419 }
1420
1421 if (error)
1422 {
1423 http->error = error;
1424 http->status = HTTP_STATUS_ERROR;
1425 errno = ECONNREFUSED;
1426
1427 CFRelease(http->tls);
1428 http->tls = NULL;
1429
1430 /*
1431 * If an error string wasn't set by the callbacks use a generic one...
1432 */
1433
1434 if (!message)
1435#ifdef HAVE_CSSMERRORSTRING
1436 message = cssmErrorString(error);
1437#else
1438 message = _("Unable to establish a secure connection to host.");
1439#endif /* HAVE_CSSMERRORSTRING */
1440
1441 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
1442
1443 return (-1);
1444 }
1445
1446 return (0);
1447}
1448
1449
1450/*
1451 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1452 */
1453
1454void
1455_httpTLSStop(http_t *http) /* I - HTTP connection */
1456{
1457 while (SSLClose(http->tls) == errSSLWouldBlock)
1458 usleep(1000);
1459
1460 CFRelease(http->tls);
1461
1462 if (http->tls_credentials)
1463 CFRelease(http->tls_credentials);
1464
1465 http->tls = NULL;
1466 http->tls_credentials = NULL;
1467}
1468
1469
1470/*
1471 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1472 */
1473
1474int /* O - Bytes written */
1475_httpTLSWrite(http_t *http, /* I - HTTP connection */
1476 const char *buf, /* I - Buffer holding data */
1477 int len) /* I - Length of buffer */
1478{
1479 ssize_t result; /* Return value */
1480 OSStatus error; /* Error info */
1481 size_t processed; /* Number of bytes processed */
1482
1483
1484 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http, buf, len));
1485
1486 error = SSLWrite(http->tls, buf, (size_t)len, &processed);
1487
1488 switch (error)
1489 {
1490 case 0 :
1491 result = (int)processed;
1492 break;
1493
1494 case errSSLWouldBlock :
1495 if (processed)
1496 {
1497 result = (int)processed;
1498 }
1499 else
1500 {
1501 result = -1;
1502 errno = EINTR;
1503 }
1504 break;
1505
1506 case errSSLClosedGraceful :
1507 default :
1508 if (processed)
1509 {
1510 result = (int)processed;
1511 }
1512 else
1513 {
1514 result = -1;
1515 errno = EPIPE;
1516 }
1517 break;
1518 }
1519
1520 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result));
1521
1522 return ((int)result);
1523}
1524
1525
1526#ifdef HAVE_SECKEYCHAINOPEN
1527/*
1528 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
1529 */
1530
1531static CFArrayRef /* O - Array of certificates or NULL */
1532http_cdsa_copy_server(
1533 const char *common_name) /* I - Server's hostname */
1534{
1535 OSStatus err; /* Error info */
1536 SecIdentitySearchRef search = NULL; /* Search reference */
1537 SecIdentityRef identity = NULL;/* Identity */
1538 CFArrayRef certificates = NULL;
1539 /* Certificate array */
1540 SecPolicyRef policy = NULL; /* Policy ref */
1541 CFStringRef cfcommon_name = NULL;
1542 /* Server name */
1543 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
1544 CFArrayRef list = NULL; /* Keychain list */
1545
1546
1547 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
1548
1549 policy = SecPolicyCreateSSL(1, cfcommon_name);
1550
1551 if (cfcommon_name)
1552 CFRelease(cfcommon_name);
1553
1554 if (!policy)
1555 goto cleanup;
1556
1557 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
1558 goto cleanup;
1559
1560 _cupsMutexLock(&tls_mutex);
1561
1562 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
1563
1564 CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
1565 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
1566 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
1567 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
1568 CFDictionaryAddValue(query, kSecMatchSearchList, list);
1569
1570 CFRelease(list);
1571
1572 err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
1573
1574 _cupsMutexUnlock(&tls_mutex);
1575
1576 if (err)
1577 goto cleanup;
1578
1579 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
1580 goto cleanup;
1581
1582 if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
1583 goto cleanup;
1584
1585 cleanup :
1586
1587 if (search)
1588 CFRelease(search);
1589 if (identity)
1590 CFRelease(identity);
1591
1592 if (policy)
1593 CFRelease(policy);
1594 if (query)
1595 CFRelease(query);
1596
1597 return (certificates);
1598}
1599#endif /* HAVE_SECKEYCHAINOPEN */
1600
1601
1602/*
1603 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1604 */
1605
1606static SecCertificateRef /* O - Certificate */
1607http_cdsa_create_credential(
1608 http_credential_t *credential) /* I - Credential */
1609{
1610 if (!credential)
1611 return (NULL);
1612
1613 return (SecCertificateCreateWithBytes(kCFAllocatorDefault, credential->data, (CFIndex)credential->datalen));
1614}
1615
1616
1617/*
1618 * 'http_cdsa_default_path()' - Get the default keychain path.
1619 */
1620
1621static const char * /* O - Keychain path */
1622http_cdsa_default_path(char *buffer, /* I - Path buffer */
1623 size_t bufsize) /* I - Size of buffer */
1624{
1625 const char *home = getenv("HOME"); /* HOME environment variable */
1626
1627
1628 if (getuid() && home)
1629 snprintf(buffer, bufsize, "%s/Library/Keychains/login.keychain", home);
1630 else
1631 strlcpy(buffer, "/Library/Keychains/System.keychain", bufsize);
1632
1633 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer));
1634
1635 return (buffer);
1636}
1637
1638
1639/*
1640 * 'http_cdsa_read()' - Read function for the CDSA library.
1641 */
1642
1643static OSStatus /* O - -1 on error, 0 on success */
1644http_cdsa_read(
1645 SSLConnectionRef connection, /* I - SSL/TLS connection */
1646 void *data, /* I - Data buffer */
1647 size_t *dataLength) /* IO - Number of bytes */
1648{
1649 OSStatus result; /* Return value */
1650 ssize_t bytes; /* Number of bytes read */
1651 http_t *http; /* HTTP connection */
1652
1653
1654 http = (http_t *)connection;
1655
1656 if (!http->blocking)
1657 {
1658 /*
1659 * Make sure we have data before we read...
1660 */
1661
1662 while (!_httpWait(http, http->wait_value, 0))
1663 {
1664 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1665 continue;
1666
1667 http->error = ETIMEDOUT;
1668 return (-1);
1669 }
1670 }
1671
1672 do
1673 {
1674 bytes = recv(http->fd, data, *dataLength, 0);
1675 }
1676 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
1677
1678 if ((size_t)bytes == *dataLength)
1679 {
1680 result = 0;
1681 }
1682 else if (bytes > 0)
1683 {
1684 *dataLength = (size_t)bytes;
1685 result = errSSLWouldBlock;
1686 }
1687 else
1688 {
1689 *dataLength = 0;
1690
1691 if (bytes == 0)
1692 result = errSSLClosedGraceful;
1693 else if (errno == EAGAIN)
1694 result = errSSLWouldBlock;
1695 else
1696 result = errSSLClosedAbort;
1697 }
1698
1699 return (result);
1700}
1701
1702
1703/*
1704 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1705 */
1706
1707static int /* O - Status of connection */
1708http_cdsa_set_credentials(http_t *http) /* I - HTTP connection */
1709{
1710 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1711 OSStatus error = 0; /* Error code */
1712 http_tls_credentials_t credentials = NULL;
1713 /* TLS credentials */
1714
1715
1716 DEBUG_printf(("7http_tls_set_credentials(%p)", http));
1717
1718 /*
1719 * Prefer connection specific credentials...
1720 */
1721
1722 if ((credentials = http->tls_credentials) == NULL)
1723 credentials = cg->tls_credentials;
1724
1725 if (credentials)
1726 {
1727 error = SSLSetCertificate(http->tls, credentials);
1728 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1729 (int)error));
1730 }
1731 else
1732 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1733
1734 return (error);
1735}
1736
1737
1738/*
1739 * 'http_cdsa_write()' - Write function for the CDSA library.
1740 */
1741
1742static OSStatus /* O - -1 on error, 0 on success */
1743http_cdsa_write(
1744 SSLConnectionRef connection, /* I - SSL/TLS connection */
1745 const void *data, /* I - Data buffer */
1746 size_t *dataLength) /* IO - Number of bytes */
1747{
1748 OSStatus result; /* Return value */
1749 ssize_t bytes; /* Number of bytes read */
1750 http_t *http; /* HTTP connection */
1751
1752
1753 http = (http_t *)connection;
1754
1755 do
1756 {
1757 bytes = write(http->fd, data, *dataLength);
1758 }
1759 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
1760
1761 if ((size_t)bytes == *dataLength)
1762 {
1763 result = 0;
1764 }
1765 else if (bytes >= 0)
1766 {
1767 *dataLength = (size_t)bytes;
1768 result = errSSLWouldBlock;
1769 }
1770 else
1771 {
1772 *dataLength = 0;
1773
1774 if (errno == EAGAIN)
1775 result = errSSLWouldBlock;
1776 else
1777 result = errSSLClosedAbort;
1778 }
1779
1780 return (result);
1781}
1782
1783
1784/*
4ef75dec 1785 * End of "$Id: tls-darwin.c 12481 2015-02-03 12:45:14Z msweet $".
1a18c85c 1786 */