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