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