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