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