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