1 /*
2 * Authentication functions for CUPS.
3 *
4 * Copyright © 2020-2024 by OpenPrinting.
5 * Copyright © 2007-2019 by Apple Inc.
6 * Copyright © 1997-2007 by Easy Software Products.
7 *
8 * This file contains Kerberos support code, copyright 2006 by
9 * Jelmer Vernooij.
10 *
11 * Licensed under Apache License v2.0. See the file "LICENSE" for more
12 * information.
13 */
14
15 /*
16 * Include necessary headers...
17 */
18
19 #include "cups-private.h"
20 #include "debug-internal.h"
21 #include <fcntl.h>
22 #include <sys/stat.h>
23 #if defined(_WIN32) || defined(__EMX__)
24 # include <io.h>
25 #else
26 # include <unistd.h>
27 #endif /* _WIN32 || __EMX__ */
28
29 #if HAVE_AUTHORIZATION_H
30 # include <Security/Authorization.h>
31 #endif /* HAVE_AUTHORIZATION_H */
32
33 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
34 # include <pwd.h>
35 #endif /* SO_PEERCRED && AF_LOCAL */
36
37
38 /*
39 * Local functions...
40 */
41
42 static const char *cups_auth_find(const char *www_authenticate, const char *scheme);
43 static const char *cups_auth_param(const char *scheme, const char *name, char *value, size_t valsize);
44 static const char *cups_auth_scheme(const char *www_authenticate, char *scheme, size_t schemesize);
45
46 #ifdef HAVE_GSSAPI
47 # define CUPS_GSS_OK 0 /* Successfully set credentials */
48 # define CUPS_GSS_NONE -1 /* No credentials */
49 # define CUPS_GSS_FAIL -2 /* Failed credentials/authentication */
50 # ifdef HAVE_GSS_ACQUIRE_CRED_EX_F
51 # ifdef HAVE_GSS_GSSAPI_SPI_H
52 # include <GSS/gssapi_spi.h>
53 # else
54 # define GSS_AUTH_IDENTITY_TYPE_1 1
55 # define gss_acquire_cred_ex_f __ApplePrivate_gss_acquire_cred_ex_f
56 typedef struct gss_auth_identity /* @private@ */
57 {
58 uint32_t type;
59 uint32_t flags;
60 char *username;
61 char *realm;
62 char *password;
63 gss_buffer_t *credentialsRef;
64 } gss_auth_identity_desc;
65 extern OM_uint32 gss_acquire_cred_ex_f(gss_status_id_t, const gss_name_t,
66 OM_uint32, OM_uint32, const gss_OID,
67 gss_cred_usage_t, gss_auth_identity_t,
68 void *, void (*)(void *, OM_uint32,
69 gss_status_id_t,
70 gss_cred_id_t,
71 gss_OID_set,
72 OM_uint32));
73 # endif /* HAVE_GSS_GSSAPI_SPI_H */
74 # include <dispatch/dispatch.h>
75 typedef struct _cups_gss_acquire_s /* Acquire callback data */
76 {
77 dispatch_semaphore_t sem; /* Synchronization semaphore */
78 OM_uint32 major; /* Returned status code */
79 gss_cred_id_t creds; /* Returned credentials */
80 } _cups_gss_acquire_t;
81
82 static void cups_gss_acquire(void *ctx, OM_uint32 major,
83 gss_status_id_t status,
84 gss_cred_id_t creds, gss_OID_set oids,
85 OM_uint32 time_rec);
86 # endif /* HAVE_GSS_ACQUIRE_CRED_EX_F */
87 static gss_name_t cups_gss_getname(http_t *http, const char *service_name);
88 # ifdef DEBUG
89 static void cups_gss_printf(OM_uint32 major_status, OM_uint32 minor_status,
90 const char *message);
91 # else
92 # define cups_gss_printf(major, minor, message)
93 # endif /* DEBUG */
94 #endif /* HAVE_GSSAPI */
95 static int cups_is_local_connection(http_t *http);
96 static int cups_local_auth(http_t *http);
97
98
99 /*
100 * 'cupsDoAuthentication()' - Authenticate a request.
101 *
102 * This function should be called in response to a @code HTTP_STATUS_UNAUTHORIZED@
103 * status, prior to resubmitting your request.
104 *
105 * @since CUPS 1.1.20/macOS 10.4@
106 */
107
108 int /* O - 0 on success, -1 on error */
cupsDoAuthentication(http_t * http,const char * method,const char * resource)109 cupsDoAuthentication(
110 http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
111 const char *method, /* I - Request method ("GET", "POST", "PUT") */
112 const char *resource) /* I - Resource path */
113 {
114 const char *password, /* Password string */
115 *www_auth, /* WWW-Authenticate header */
116 *schemedata; /* Scheme-specific data */
117 char scheme[256], /* Scheme name */
118 prompt[1024]; /* Prompt for user */
119 int localauth; /* Local authentication result */
120 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
121
122
123 DEBUG_printf(("cupsDoAuthentication(http=%p, method=\"%s\", resource=\"%s\")", (void *)http, method, resource));
124
125 if (!http)
126 http = _cupsConnect();
127
128 if (!http || !method || !resource)
129 return (-1);
130
131 DEBUG_printf(("2cupsDoAuthentication: digest_tries=%d, userpass=\"%s\"",
132 http->digest_tries, http->userpass));
133 DEBUG_printf(("2cupsDoAuthentication: WWW-Authenticate=\"%s\"",
134 httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE)));
135
136 /*
137 * Clear the current authentication string...
138 */
139
140 httpSetAuthString(http, NULL, NULL);
141
142 /*
143 * See if we can do local authentication...
144 */
145
146 if (http->digest_tries < 3)
147 {
148 if ((localauth = cups_local_auth(http)) == 0)
149 {
150 DEBUG_printf(("2cupsDoAuthentication: authstring=\"%s\"",
151 http->authstring));
152
153 if (http->status == HTTP_STATUS_UNAUTHORIZED)
154 http->digest_tries ++;
155
156 return (0);
157 }
158 else if (localauth == -1)
159 {
160 http->status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
161 return (-1); /* Error or canceled */
162 }
163 }
164
165 /*
166 * Nope, loop through the authentication schemes to find the first we support.
167 */
168
169 www_auth = httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE);
170
171 for (schemedata = cups_auth_scheme(www_auth, scheme, sizeof(scheme)); schemedata; schemedata = cups_auth_scheme(schemedata + strlen(scheme), scheme, sizeof(scheme)))
172 {
173 /*
174 * Check the scheme name...
175 */
176
177 DEBUG_printf(("2cupsDoAuthentication: Trying scheme \"%s\"...", scheme));
178
179 #ifdef HAVE_GSSAPI
180 if (!_cups_strcasecmp(scheme, "Negotiate") && !cups_is_local_connection(http))
181 {
182 /*
183 * Kerberos authentication to remote server...
184 */
185
186 int gss_status; /* Auth status */
187
188 if ((gss_status = _cupsSetNegotiateAuthString(http, method, resource)) == CUPS_GSS_FAIL)
189 {
190 DEBUG_puts("1cupsDoAuthentication: Negotiate failed.");
191 http->status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
192 return (-1);
193 }
194 else if (gss_status == CUPS_GSS_NONE)
195 {
196 DEBUG_puts("2cupsDoAuthentication: No credentials for Negotiate.");
197 continue;
198 }
199 else
200 {
201 DEBUG_puts("2cupsDoAuthentication: Using Negotiate.");
202 break;
203 }
204 }
205 else
206 #endif /* HAVE_GSSAPI */
207 if (!_cups_strcasecmp(scheme, "Bearer"))
208 {
209 // OAuth 2.0 (Bearer) authentication...
210 const char *bearer = NULL; /* Bearer token string, if any */
211
212 if (cg->oauth_cb)
213 {
214 // Try callback...
215 char scope[HTTP_MAX_VALUE]; /* scope="xyz" string */
216
217 cups_auth_param(schemedata, "realm", http->realm, sizeof(http->realm));
218
219 if (cups_auth_param(schemedata, "scope", scope, sizeof(scope)))
220 bearer = (cg->oauth_cb)(http, http->realm, scope, resource, cg->oauth_data);
221 else
222 bearer = (cg->oauth_cb)(http, http->realm, NULL, resource, cg->oauth_data);
223 }
224
225 if (bearer)
226 {
227 // Use this access token...
228 httpSetAuthString(http, "Bearer", bearer);
229 break;
230 }
231 else
232 {
233 // No access token, try the next scheme...
234 DEBUG_puts("2cupsDoAuthentication: No OAuth access token to provide.");
235 continue;
236 }
237 }
238 else if (_cups_strcasecmp(scheme, "Basic") && _cups_strcasecmp(scheme, "Digest") && _cups_strcasecmp(scheme, "Negotiate"))
239 {
240 /*
241 * Other schemes not yet supported...
242 */
243
244 DEBUG_printf(("2cupsDoAuthentication: Scheme \"%s\" not yet supported.", scheme));
245 continue;
246 }
247
248 /*
249 * See if we should retry the current username:password...
250 */
251
252 if (http->digest_tries > 1 || !http->userpass[0])
253 {
254 /*
255 * Nope - get a new password from the user...
256 */
257
258 char default_username[HTTP_MAX_VALUE];
259 /* Default username */
260
261 if (!cg->lang_default)
262 cg->lang_default = cupsLangDefault();
263
264 if (cups_auth_param(schemedata, "username", default_username, sizeof(default_username)))
265 cupsSetUser(default_username);
266
267 snprintf(prompt, sizeof(prompt), _cupsLangString(cg->lang_default, _("Password for %s on %s? ")), cupsUser(), http->hostname[0] == '/' ? "localhost" : http->hostname);
268
269 http->digest_tries = _cups_strncasecmp(scheme, "Digest", 6) != 0;
270 http->userpass[0] = '\0';
271
272 if ((password = cupsGetPassword2(prompt, http, method, resource)) == NULL)
273 {
274 DEBUG_puts("1cupsDoAuthentication: User canceled password request.");
275 http->status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
276 return (-1);
277 }
278
279 snprintf(http->userpass, sizeof(http->userpass), "%s:%s", cupsUser(), password);
280 }
281 else if (http->status == HTTP_STATUS_UNAUTHORIZED)
282 http->digest_tries ++;
283
284 if (http->status == HTTP_STATUS_UNAUTHORIZED && http->digest_tries >= 3)
285 {
286 DEBUG_printf(("1cupsDoAuthentication: Too many authentication tries (%d)", http->digest_tries));
287
288 http->status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
289 return (-1);
290 }
291
292 /*
293 * Got a password; encode it for the server...
294 */
295
296 if (!_cups_strcasecmp(scheme, "Basic"))
297 {
298 /*
299 * Basic authentication...
300 */
301
302 char encode[256]; /* Base64 buffer */
303
304 DEBUG_puts("2cupsDoAuthentication: Using Basic.");
305 httpEncode64_2(encode, sizeof(encode), http->userpass, (int)strlen(http->userpass));
306 httpSetAuthString(http, "Basic", encode);
307 break;
308 }
309 else if (!_cups_strcasecmp(scheme, "Digest"))
310 {
311 /*
312 * Digest authentication...
313 */
314
315 char nonce[HTTP_MAX_VALUE]; /* nonce="xyz" string */
316
317 cups_auth_param(schemedata, "algorithm", http->algorithm, sizeof(http->algorithm));
318 cups_auth_param(schemedata, "opaque", http->opaque, sizeof(http->opaque));
319 cups_auth_param(schemedata, "nonce", nonce, sizeof(nonce));
320 cups_auth_param(schemedata, "realm", http->realm, sizeof(http->realm));
321
322 if (_httpSetDigestAuthString(http, nonce, method, resource))
323 {
324 DEBUG_puts("2cupsDoAuthentication: Using Digest.");
325 break;
326 }
327 }
328 }
329
330 if (http->authstring && http->authstring[0])
331 {
332 DEBUG_printf(("1cupsDoAuthentication: authstring=\"%s\".", http->authstring));
333
334 return (0);
335 }
336 else
337 {
338 DEBUG_puts("1cupsDoAuthentication: No supported schemes.");
339 http->status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
340
341 return (-1);
342 }
343 }
344
345
346 #ifdef HAVE_GSSAPI
347 /*
348 * '_cupsSetNegotiateAuthString()' - Set the Kerberos authentication string.
349 */
350
351 int /* O - 0 on success, negative on error */
_cupsSetNegotiateAuthString(http_t * http,const char * method,const char * resource)352 _cupsSetNegotiateAuthString(
353 http_t *http, /* I - Connection to server */
354 const char *method, /* I - Request method ("GET", "POST", "PUT") */
355 const char *resource) /* I - Resource path */
356 {
357 OM_uint32 minor_status, /* Minor status code */
358 major_status; /* Major status code */
359 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
360 /* Output token */
361
362 # ifdef __APPLE__
363 /*
364 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
365 * to use it...
366 */
367
368 if (&gss_init_sec_context == NULL)
369 {
370 DEBUG_puts("1_cupsSetNegotiateAuthString: Weak-linked GSSAPI/Kerberos "
371 "framework is not present");
372 return (CUPS_GSS_NONE);
373 }
374 # endif /* __APPLE__ */
375
376 if (!strcmp(http->hostname, "localhost") || http->hostname[0] == '/' || isdigit(http->hostname[0] & 255) || !strchr(http->hostname, '.'))
377 {
378 DEBUG_printf(("1_cupsSetNegotiateAuthString: Kerberos not available for host \"%s\".", http->hostname));
379 return (CUPS_GSS_NONE);
380 }
381
382 if (http->gssname == GSS_C_NO_NAME)
383 {
384 http->gssname = cups_gss_getname(http, _cupsGSSServiceName());
385 }
386
387 if (http->gssctx != GSS_C_NO_CONTEXT)
388 {
389 gss_delete_sec_context(&minor_status, &http->gssctx, GSS_C_NO_BUFFER);
390 http->gssctx = GSS_C_NO_CONTEXT;
391 }
392
393 major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
394 &http->gssctx,
395 http->gssname, http->gssmech,
396 GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG,
397 GSS_C_INDEFINITE,
398 GSS_C_NO_CHANNEL_BINDINGS,
399 GSS_C_NO_BUFFER, &http->gssmech,
400 &output_token, NULL, NULL);
401
402 # ifdef HAVE_GSS_ACQUIRE_CRED_EX_F
403 if (major_status == GSS_S_NO_CRED)
404 {
405 /*
406 * Ask the user for credentials...
407 */
408
409 char prompt[1024], /* Prompt for user */
410 userbuf[256]; /* Kerberos username */
411 const char *username, /* Username string */
412 *password; /* Password string */
413 _cups_gss_acquire_t data; /* Callback data */
414 gss_auth_identity_desc identity; /* Kerberos user identity */
415 _cups_globals_t *cg = _cupsGlobals();
416 /* Per-thread global data */
417
418 if (!cg->lang_default)
419 cg->lang_default = cupsLangDefault();
420
421 snprintf(prompt, sizeof(prompt),
422 _cupsLangString(cg->lang_default, _("Password for %s on %s? ")),
423 cupsUser(), http->gsshost);
424
425 if ((password = cupsGetPassword2(prompt, http, method, resource)) == NULL)
426 return (CUPS_GSS_FAIL);
427
428 /*
429 * Try to acquire credentials...
430 */
431
432 username = cupsUser();
433 if (!strchr(username, '@'))
434 {
435 snprintf(userbuf, sizeof(userbuf), "%s@%s", username, http->gsshost);
436 username = userbuf;
437 }
438
439 identity.type = GSS_AUTH_IDENTITY_TYPE_1;
440 identity.flags = 0;
441 identity.username = (char *)username;
442 identity.realm = (char *)"";
443 identity.password = (char *)password;
444 identity.credentialsRef = NULL;
445
446 data.sem = dispatch_semaphore_create(0);
447 data.major = 0;
448 data.creds = NULL;
449
450 if (data.sem)
451 {
452 major_status = gss_acquire_cred_ex_f(NULL, GSS_C_NO_NAME, 0, GSS_C_INDEFINITE, GSS_KRB5_MECHANISM, GSS_C_INITIATE, (gss_auth_identity_t)&identity, &data, cups_gss_acquire);
453
454 if (major_status == GSS_S_COMPLETE)
455 {
456 dispatch_semaphore_wait(data.sem, DISPATCH_TIME_FOREVER);
457 major_status = data.major;
458 }
459
460 dispatch_release(data.sem);
461
462 if (major_status == GSS_S_COMPLETE)
463 {
464 OM_uint32 release_minor; /* Minor status from releasing creds */
465
466 major_status = gss_init_sec_context(&minor_status, data.creds,
467 &http->gssctx,
468 http->gssname, http->gssmech,
469 GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG,
470 GSS_C_INDEFINITE,
471 GSS_C_NO_CHANNEL_BINDINGS,
472 GSS_C_NO_BUFFER, &http->gssmech,
473 &output_token, NULL, NULL);
474 gss_release_cred(&release_minor, &data.creds);
475 }
476 }
477 }
478 # else
479 (void)method;
480 (void)resource;
481 # endif /* HAVE_GSS_ACQUIRED_CRED_EX_F */
482
483 if (major_status == GSS_S_NO_CRED)
484 {
485 cups_gss_printf(major_status, minor_status, "_cupsSetNegotiateAuthString: No credentials");
486 return (CUPS_GSS_NONE);
487 }
488 else if (GSS_ERROR(major_status))
489 {
490 cups_gss_printf(major_status, minor_status, "_cupsSetNegotiateAuthString: Unable to initialize security context");
491 return (CUPS_GSS_FAIL);
492 }
493
494 # ifdef DEBUG
495 else if (major_status == GSS_S_CONTINUE_NEEDED)
496 cups_gss_printf(major_status, minor_status, "_cupsSetNegotiateAuthString: Continuation needed");
497 # endif /* DEBUG */
498
499 if (output_token.length > 0 && output_token.length <= 65536)
500 {
501 /*
502 * Allocate the authorization string since Windows KDCs can have
503 * arbitrarily large credentials...
504 */
505
506 int authsize = 10 + /* "Negotiate " */
507 (((int)output_token.length * 4 / 3 + 3) & ~3) + 1;
508 /* Base64 + nul */
509
510 httpSetAuthString(http, NULL, NULL);
511
512 if ((http->authstring = malloc((size_t)authsize)) == NULL)
513 {
514 http->authstring = http->_authstring;
515 authsize = sizeof(http->_authstring);
516 }
517
518 strlcpy(http->authstring, "Negotiate ", (size_t)authsize);
519 httpEncode64_2(http->authstring + 10, authsize - 10, output_token.value,
520 (int)output_token.length);
521
522 gss_release_buffer(&minor_status, &output_token);
523 }
524 else
525 {
526 DEBUG_printf(("1_cupsSetNegotiateAuthString: Kerberos credentials too "
527 "large - %d bytes!", (int)output_token.length));
528 gss_release_buffer(&minor_status, &output_token);
529
530 return (CUPS_GSS_FAIL);
531 }
532
533 return (CUPS_GSS_OK);
534 }
535 #endif /* HAVE_GSSAPI */
536
537
538 /*
539 * 'cups_auth_find()' - Find the named WWW-Authenticate scheme.
540 *
541 * The "www_authenticate" parameter points to the current position in the header.
542 *
543 * Returns @code NULL@ if the auth scheme is not present.
544 */
545
546 static const char * /* O - Start of matching scheme or @code NULL@ if not found */
cups_auth_find(const char * www_authenticate,const char * scheme)547 cups_auth_find(const char *www_authenticate, /* I - Pointer into WWW-Authenticate header */
548 const char *scheme) /* I - Authentication scheme */
549 {
550 size_t schemelen = strlen(scheme); /* Length of scheme */
551
552
553 DEBUG_printf(("8cups_auth_find(www_authenticate=\"%s\", scheme=\"%s\"(%d))", www_authenticate, scheme, (int)schemelen));
554
555 while (*www_authenticate)
556 {
557 /*
558 * Skip leading whitespace and commas...
559 */
560
561 DEBUG_printf(("9cups_auth_find: Before whitespace: \"%s\"", www_authenticate));
562 while (isspace(*www_authenticate & 255) || *www_authenticate == ',')
563 www_authenticate ++;
564 DEBUG_printf(("9cups_auth_find: After whitespace: \"%s\"", www_authenticate));
565
566 /*
567 * See if this is "Scheme" followed by whitespace or the end of the string.
568 */
569
570 if (!strncmp(www_authenticate, scheme, schemelen) && (isspace(www_authenticate[schemelen] & 255) || www_authenticate[schemelen] == ',' || !www_authenticate[schemelen]))
571 {
572 /*
573 * Yes, this is the start of the scheme-specific information...
574 */
575
576 DEBUG_printf(("9cups_auth_find: Returning \"%s\".", www_authenticate));
577
578 return (www_authenticate);
579 }
580
581 /*
582 * Skip the scheme name or param="value" string...
583 */
584
585 while (!isspace(*www_authenticate & 255) && *www_authenticate)
586 {
587 if (*www_authenticate == '\"')
588 {
589 /*
590 * Skip quoted value...
591 */
592
593 www_authenticate ++;
594 while (*www_authenticate && *www_authenticate != '\"')
595 www_authenticate ++;
596
597 DEBUG_printf(("9cups_auth_find: After quoted: \"%s\"", www_authenticate));
598 }
599
600 www_authenticate ++;
601 }
602
603 DEBUG_printf(("9cups_auth_find: After skip: \"%s\"", www_authenticate));
604 }
605
606 DEBUG_puts("9cups_auth_find: Returning NULL.");
607
608 return (NULL);
609 }
610
611
612 /*
613 * 'cups_auth_param()' - Copy the value for the named authentication parameter,
614 * if present.
615 */
616
617 static const char * /* O - Parameter value or @code NULL@ if not present */
cups_auth_param(const char * scheme,const char * name,char * value,size_t valsize)618 cups_auth_param(const char *scheme, /* I - Pointer to auth data */
619 const char *name, /* I - Name of parameter */
620 char *value, /* I - Value buffer */
621 size_t valsize) /* I - Size of value buffer */
622 {
623 char *valptr = value, /* Pointer into value buffer */
624 *valend = value + valsize - 1; /* Pointer to end of buffer */
625 size_t namelen = strlen(name); /* Name length */
626 int param; /* Is this a parameter? */
627
628
629 DEBUG_printf(("8cups_auth_param(scheme=\"%s\", name=\"%s\", value=%p, valsize=%d)", scheme, name, (void *)value, (int)valsize));
630
631 while (!isspace(*scheme & 255) && *scheme)
632 scheme ++;
633
634 while (*scheme)
635 {
636 while (isspace(*scheme & 255) || *scheme == ',')
637 scheme ++;
638
639 if (!strncmp(scheme, name, namelen) && scheme[namelen] == '=')
640 {
641 /*
642 * Found the parameter, copy the value...
643 */
644
645 scheme += namelen + 1;
646 if (*scheme == '\"')
647 {
648 scheme ++;
649
650 while (*scheme && *scheme != '\"')
651 {
652 if (valptr < valend)
653 *valptr++ = *scheme;
654
655 scheme ++;
656 }
657 }
658 else
659 {
660 while (*scheme && strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~+/=", *scheme))
661 {
662 if (valptr < valend)
663 *valptr++ = *scheme;
664
665 scheme ++;
666 }
667 }
668
669 *valptr = '\0';
670
671 DEBUG_printf(("9cups_auth_param: Returning \"%s\".", value));
672
673 return (value);
674 }
675
676 /*
677 * Skip the param=value string...
678 */
679
680 param = 0;
681
682 while (!isspace(*scheme & 255) && *scheme)
683 {
684 if (*scheme == '=')
685 param = 1;
686 else if (*scheme == '\"')
687 {
688 /*
689 * Skip quoted value...
690 */
691
692 scheme ++;
693 while (*scheme && *scheme != '\"')
694 scheme ++;
695 }
696
697 scheme ++;
698 }
699
700 /*
701 * If this wasn't a parameter, we are at the end of this scheme's
702 * parameters...
703 */
704
705 if (!param)
706 break;
707 }
708
709 *value = '\0';
710
711 DEBUG_puts("9cups_auth_param: Returning NULL.");
712
713 return (NULL);
714 }
715
716
717 /*
718 * 'cups_auth_scheme()' - Get the (next) WWW-Authenticate scheme.
719 *
720 * The "www_authenticate" parameter points to the current position in the header.
721 *
722 * Returns @code NULL@ if there are no (more) auth schemes present.
723 */
724
725 static const char * /* O - Start of scheme or @code NULL@ if not found */
cups_auth_scheme(const char * www_authenticate,char * scheme,size_t schemesize)726 cups_auth_scheme(const char *www_authenticate, /* I - Pointer into WWW-Authenticate header */
727 char *scheme, /* I - Scheme name buffer */
728 size_t schemesize) /* I - Size of buffer */
729 {
730 const char *start; /* Start of scheme data */
731 char *sptr = scheme, /* Pointer into scheme buffer */
732 *send = scheme + schemesize - 1;/* End of scheme buffer */
733 int param; /* Is this a parameter? */
734
735
736 DEBUG_printf(("8cups_auth_scheme(www_authenticate=\"%s\", scheme=%p, schemesize=%u)", www_authenticate, (void *)scheme, (unsigned)schemesize));
737
738 while (*www_authenticate)
739 {
740 /*
741 * Skip leading whitespace and commas...
742 */
743
744 while (isspace(*www_authenticate & 255) || *www_authenticate == ',')
745 www_authenticate ++;
746
747 /*
748 * Parse the scheme name or param="value" string...
749 */
750
751 for (sptr = scheme, start = www_authenticate, param = 0; *www_authenticate && *www_authenticate != ',' && !isspace(*www_authenticate & 255); www_authenticate ++)
752 {
753 if (*www_authenticate == '=')
754 param = 1;
755 else if (!param && sptr < send)
756 *sptr++ = *www_authenticate;
757 else if (*www_authenticate == '\"')
758 {
759 /*
760 * Skip quoted value...
761 */
762
763
764 do
765 www_authenticate ++;
766 while (*www_authenticate && *www_authenticate != '\"');
767 }
768 }
769
770 if (sptr > scheme && !param)
771 {
772 *sptr = '\0';
773
774 DEBUG_printf(("9cups_auth_scheme: Returning \"%s\".", start));
775
776 return (start);
777 }
778 }
779
780 *scheme = '\0';
781
782 DEBUG_puts("9cups_auth_scheme: Returning NULL.");
783
784 return (NULL);
785 }
786
787
788 #ifdef HAVE_GSSAPI
789 # ifdef HAVE_GSS_ACQUIRE_CRED_EX_F
790 /*
791 * 'cups_gss_acquire()' - Kerberos credentials callback.
792 */
793 static void
cups_gss_acquire(void * ctx,OM_uint32 major,gss_status_id_t status,gss_cred_id_t creds,gss_OID_set oids,OM_uint32 time_rec)794 cups_gss_acquire(
795 void *ctx, /* I - Caller context */
796 OM_uint32 major, /* I - Major error code */
797 gss_status_id_t status, /* I - Status (unused) */
798 gss_cred_id_t creds, /* I - Credentials (if any) */
799 gss_OID_set oids, /* I - Mechanism OIDs (unused) */
800 OM_uint32 time_rec) /* I - Timestamp (unused) */
801 {
802 uint32_t min; /* Minor error code */
803 _cups_gss_acquire_t *data; /* Callback data */
804
805
806 (void)status;
807 (void)time_rec;
808
809 data = (_cups_gss_acquire_t *)ctx;
810 data->major = major;
811 data->creds = creds;
812
813 gss_release_oid_set(&min, &oids);
814 dispatch_semaphore_signal(data->sem);
815 }
816 # endif /* HAVE_GSS_ACQUIRE_CRED_EX_F */
817
818
819 /*
820 * 'cups_gss_getname()' - Get CUPS service credentials for authentication.
821 */
822
823 static gss_name_t /* O - Server name */
cups_gss_getname(http_t * http,const char * service_name)824 cups_gss_getname(
825 http_t *http, /* I - Connection to server */
826 const char *service_name) /* I - Service name */
827 {
828 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
829 /* Service token */
830 OM_uint32 major_status, /* Major status code */
831 minor_status; /* Minor status code */
832 gss_name_t server_name; /* Server name */
833 char buf[1024]; /* Name buffer */
834
835
836 DEBUG_printf(("7cups_gss_getname(http=%p, service_name=\"%s\")", http,
837 service_name));
838
839
840 /*
841 * Get the hostname...
842 */
843
844 if (!http->gsshost[0])
845 {
846 httpGetHostname(http, http->gsshost, sizeof(http->gsshost));
847
848 if (!strcmp(http->gsshost, "localhost"))
849 {
850 if (gethostname(http->gsshost, sizeof(http->gsshost)) < 0)
851 {
852 DEBUG_printf(("1cups_gss_getname: gethostname() failed: %s",
853 strerror(errno)));
854 http->gsshost[0] = '\0';
855 return (NULL);
856 }
857
858 if (!strchr(http->gsshost, '.'))
859 {
860 /*
861 * The hostname is not a FQDN, so look it up...
862 */
863
864 struct hostent *host; /* Host entry to get FQDN */
865
866 if ((host = gethostbyname(http->gsshost)) != NULL && host->h_name)
867 {
868 /*
869 * Use the resolved hostname...
870 */
871
872 strlcpy(http->gsshost, host->h_name, sizeof(http->gsshost));
873 }
874 else
875 {
876 DEBUG_printf(("1cups_gss_getname: gethostbyname(\"%s\") failed.",
877 http->gsshost));
878 http->gsshost[0] = '\0';
879 return (NULL);
880 }
881 }
882 }
883 }
884
885 /*
886 * Get a service name we can use for authentication purposes...
887 */
888
889 snprintf(buf, sizeof(buf), "%s@%s", service_name, http->gsshost);
890
891 DEBUG_printf(("8cups_gss_getname: Looking up \"%s\".", buf));
892
893 token.value = buf;
894 token.length = strlen(buf);
895 server_name = GSS_C_NO_NAME;
896 major_status = gss_import_name(&minor_status, &token,
897 GSS_C_NT_HOSTBASED_SERVICE,
898 &server_name);
899
900 if (GSS_ERROR(major_status))
901 {
902 cups_gss_printf(major_status, minor_status,
903 "cups_gss_getname: gss_import_name() failed");
904 return (NULL);
905 }
906
907 return (server_name);
908 }
909
910
911 # ifdef DEBUG
912 /*
913 * 'cups_gss_printf()' - Show debug error messages from GSSAPI.
914 */
915
916 static void
cups_gss_printf(OM_uint32 major_status,OM_uint32 minor_status,const char * message)917 cups_gss_printf(OM_uint32 major_status,/* I - Major status code */
918 OM_uint32 minor_status,/* I - Minor status code */
919 const char *message) /* I - Prefix for error message */
920 {
921 OM_uint32 err_major_status, /* Major status code for display */
922 err_minor_status; /* Minor status code for display */
923 OM_uint32 msg_ctx; /* Message context */
924 gss_buffer_desc major_status_string = GSS_C_EMPTY_BUFFER,
925 /* Major status message */
926 minor_status_string = GSS_C_EMPTY_BUFFER;
927 /* Minor status message */
928
929
930 msg_ctx = 0;
931 err_major_status = gss_display_status(&err_minor_status,
932 major_status,
933 GSS_C_GSS_CODE,
934 GSS_C_NO_OID,
935 &msg_ctx,
936 &major_status_string);
937
938 if (!GSS_ERROR(err_major_status))
939 gss_display_status(&err_minor_status, minor_status, GSS_C_MECH_CODE,
940 GSS_C_NULL_OID, &msg_ctx, &minor_status_string);
941
942 DEBUG_printf(("1%s: %s, %s", message, (char *)major_status_string.value,
943 (char *)minor_status_string.value));
944
945 gss_release_buffer(&err_minor_status, &major_status_string);
946 gss_release_buffer(&err_minor_status, &minor_status_string);
947 }
948 # endif /* DEBUG */
949 #endif /* HAVE_GSSAPI */
950
951 static int /* O - 0 if not a local connection */
952 /* 1 if local connection */
cups_is_local_connection(http_t * http)953 cups_is_local_connection(http_t *http) /* I - HTTP connection to server */
954 {
955 if (!httpAddrLocalhost(http->hostaddr) && _cups_strcasecmp(http->hostname, "localhost") != 0)
956 return 0;
957 return 1;
958 }
959
960 /*
961 * 'cups_local_auth()' - Get the local authorization certificate if
962 * available/applicable.
963 */
964
965 static int /* O - 0 if available */
966 /* 1 if not available */
967 /* -1 error */
cups_local_auth(http_t * http)968 cups_local_auth(http_t *http) /* I - HTTP connection to server */
969 {
970 #if defined(_WIN32) || defined(__EMX__)
971 /*
972 * Currently _WIN32 and OS-2 do not support the CUPS server...
973 */
974
975 return (1);
976 #else
977 int pid; /* Current process ID */
978 FILE *fp; /* Certificate file */
979 char trc[16], /* Try Root Certificate parameter */
980 filename[1024]; /* Certificate filename */
981 const char *www_auth, /* WWW-Authenticate header */
982 *schemedata; /* Data for the named auth scheme */
983 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
984 # if defined(HAVE_AUTHORIZATION_H)
985 OSStatus status; /* Status */
986 AuthorizationItem auth_right; /* Authorization right */
987 AuthorizationRights auth_rights; /* Authorization rights */
988 AuthorizationFlags auth_flags; /* Authorization flags */
989 AuthorizationExternalForm auth_extrn; /* Authorization ref external */
990 char auth_key[1024]; /* Buffer */
991 char buffer[1024]; /* Buffer */
992 # endif /* HAVE_AUTHORIZATION_H */
993
994
995 DEBUG_printf(("7cups_local_auth(http=%p) hostaddr=%s, hostname=\"%s\"", (void *)http, httpAddrString(http->hostaddr, filename, sizeof(filename)), http->hostname));
996
997 /*
998 * See if we are accessing localhost...
999 */
1000
1001 if (!cups_is_local_connection(http))
1002 {
1003 DEBUG_puts("8cups_local_auth: Not a local connection!");
1004 return (1);
1005 }
1006
1007 www_auth = httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE);
1008
1009 # if defined(HAVE_AUTHORIZATION_H)
1010 /*
1011 * Delete any previous authorization reference...
1012 */
1013
1014 if (http->auth_ref)
1015 {
1016 AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
1017 http->auth_ref = NULL;
1018 }
1019
1020 if (!getenv("GATEWAY_INTERFACE") && (schemedata = cups_auth_find(www_auth, "AuthRef")) != NULL && cups_auth_param(schemedata, "key", auth_key, sizeof(auth_key)))
1021 {
1022 status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &http->auth_ref);
1023 if (status != errAuthorizationSuccess)
1024 {
1025 DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d",
1026 (int)status));
1027 return (-1);
1028 }
1029
1030 auth_right.name = auth_key;
1031 auth_right.valueLength = 0;
1032 auth_right.value = NULL;
1033 auth_right.flags = 0;
1034
1035 auth_rights.count = 1;
1036 auth_rights.items = &auth_right;
1037
1038 auth_flags = kAuthorizationFlagDefaults |
1039 kAuthorizationFlagPreAuthorize |
1040 kAuthorizationFlagInteractionAllowed |
1041 kAuthorizationFlagExtendRights;
1042
1043 status = AuthorizationCopyRights(http->auth_ref, &auth_rights,
1044 kAuthorizationEmptyEnvironment,
1045 auth_flags, NULL);
1046 if (status == errAuthorizationSuccess)
1047 status = AuthorizationMakeExternalForm(http->auth_ref, &auth_extrn);
1048
1049 if (status == errAuthorizationSuccess)
1050 {
1051 /*
1052 * Set the authorization string and return...
1053 */
1054
1055 httpEncode64_2(buffer, sizeof(buffer), (void *)&auth_extrn,
1056 sizeof(auth_extrn));
1057
1058 httpSetAuthString(http, "AuthRef", buffer);
1059
1060 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
1061 http->authstring));
1062 return (0);
1063 }
1064 else if (status == errAuthorizationCanceled)
1065 return (-1);
1066
1067 DEBUG_printf(("9cups_local_auth: AuthorizationCopyRights() returned %d", (int)status));
1068
1069 /*
1070 * Fall through to try certificates...
1071 */
1072 }
1073 # endif /* HAVE_AUTHORIZATION_H */
1074
1075 # if defined(SO_PEERCRED) && defined(AF_LOCAL)
1076 /*
1077 * See if we can authenticate using the peer credentials provided over a
1078 * domain socket; if so, specify "PeerCred username" as the authentication
1079 * information...
1080 */
1081
1082 if (http->hostaddr->addr.sa_family == AF_LOCAL &&
1083 !getenv("GATEWAY_INTERFACE") && /* Not via CGI programs... */
1084 cups_auth_find(www_auth, "PeerCred"))
1085 {
1086 /*
1087 * Verify that the current cupsUser() matches the current UID...
1088 */
1089
1090 struct passwd pwd; /* Password information */
1091 struct passwd *result; /* Auxiliary pointer */
1092 const char *username; /* Current username */
1093
1094 username = cupsUser();
1095
1096 getpwnam_r(username, &pwd, cg->pw_buf, PW_BUF_SIZE, &result);
1097 if (result && pwd.pw_uid == getuid())
1098 {
1099 httpSetAuthString(http, "PeerCred", username);
1100
1101 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
1102 http->authstring));
1103
1104 return (0);
1105 }
1106 }
1107 # endif /* SO_PEERCRED && AF_LOCAL */
1108
1109 if ((schemedata = cups_auth_find(www_auth, "Local")) == NULL)
1110 return (1);
1111
1112 /*
1113 * Try opening a certificate file for this PID. If that fails,
1114 * try the root certificate...
1115 */
1116
1117 pid = getpid();
1118 snprintf(filename, sizeof(filename), "%s/certs/%d", cg->cups_statedir, pid);
1119 if ((fp = fopen(filename, "r")) == NULL && pid > 0)
1120 {
1121 /*
1122 * No certificate for this PID; see if we can get the root certificate...
1123 */
1124
1125 DEBUG_printf(("9cups_local_auth: Unable to open file \"%s\": %s", filename, strerror(errno)));
1126
1127 if (!cups_auth_param(schemedata, "trc", trc, sizeof(trc)))
1128 {
1129 /*
1130 * Scheduler doesn't want us to use the root certificate...
1131 */
1132
1133 return (1);
1134 }
1135
1136 snprintf(filename, sizeof(filename), "%s/certs/0", cg->cups_statedir);
1137 if ((fp = fopen(filename, "r")) == NULL)
1138 DEBUG_printf(("9cups_local_auth: Unable to open file \"%s\": %s", filename, strerror(errno)));
1139 }
1140
1141 if (fp)
1142 {
1143 /*
1144 * Read the certificate from the file...
1145 */
1146
1147 char certificate[33], /* Certificate string */
1148 *certptr; /* Pointer to certificate string */
1149
1150 certptr = fgets(certificate, sizeof(certificate), fp);
1151 fclose(fp);
1152
1153 if (certptr)
1154 {
1155 /*
1156 * Set the authorization string and return...
1157 */
1158
1159 httpSetAuthString(http, "Local", certificate);
1160
1161 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
1162 http->authstring));
1163
1164 return (0);
1165 }
1166 }
1167
1168 return (1);
1169 #endif /* _WIN32 || __EMX__ */
1170 }
1171