]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/auth.c
Merge changes from CUPS 1.5svn-r9374.
[thirdparty/cups.git] / cups / auth.c
1 /*
2 * "$Id: auth.c 7720 2008-07-11 22:46:21Z mike $"
3 *
4 * Authentication functions for CUPS.
5 *
6 * Copyright 2007-2010 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products.
8 *
9 * This file contains Kerberos support code, copyright 2006 by
10 * Jelmer Vernooij.
11 *
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
17 *
18 * This file is subject to the Apple OS-Developed Software exception.
19 *
20 * Contents:
21 *
22 * cupsDoAuthentication() - Authenticate a request.
23 * cups_get_gssname() - Get GSSAPI name for authentication.
24 * cups_gss_printf() - Show error messages from GSSAPI...
25 * cups_local_auth() - Get the local authorization certificate if
26 * available/applicable...
27 */
28
29 /*
30 * Include necessary headers...
31 */
32
33 #include "cups-private.h"
34 #include <fcntl.h>
35 #include <sys/stat.h>
36 #if defined(WIN32) || defined(__EMX__)
37 # include <io.h>
38 #else
39 # include <unistd.h>
40 #endif /* WIN32 || __EMX__ */
41
42 #if HAVE_AUTHORIZATION_H
43 # include <Security/Authorization.h>
44 # ifdef HAVE_SECBASEPRIV_H
45 # include <Security/SecBasePriv.h>
46 # else
47 extern const char *cssmErrorString(int error);
48 # endif /* HAVE_SECBASEPRIV_H */
49 #endif /* HAVE_AUTHORIZATION_H */
50
51 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
52 # include <pwd.h>
53 #endif /* SO_PEERCRED && AF_LOCAL */
54
55
56 /*
57 * Local functions...
58 */
59
60 #ifdef HAVE_GSSAPI
61 static gss_name_t cups_get_gssname(http_t *http, const char *service_name);
62 # ifdef DEBUG
63 static void cups_gss_printf(OM_uint32 major_status, OM_uint32 minor_status,
64 const char *message);
65 # else
66 # define cups_gss_printf(major, minor, message)
67 # endif /* DEBUG */
68 #endif /* HAVE_GSSAPI */
69 static int cups_local_auth(http_t *http);
70
71
72 /*
73 * 'cupsDoAuthentication()' - Authenticate a request.
74 *
75 * This function should be called in response to a @code HTTP_UNAUTHORIZED@
76 * status, prior to resubmitting your request.
77 *
78 * @since CUPS 1.1.20/Mac OS X 10.4@
79 */
80
81 int /* O - 0 on success, -1 on error */
82 cupsDoAuthentication(
83 http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
84 const char *method, /* I - Request method ("GET", "POST", "PUT") */
85 const char *resource) /* I - Resource path */
86 {
87 const char *password; /* Password string */
88 char prompt[1024], /* Prompt for user */
89 realm[HTTP_MAX_VALUE], /* realm="xyz" string */
90 nonce[HTTP_MAX_VALUE]; /* nonce="xyz" string */
91 int localauth; /* Local authentication result */
92 _cups_globals_t *cg; /* Global data */
93
94
95 DEBUG_printf(("cupsDoAuthentication(http=%p, method=\"%s\", resource=\"%s\")",
96 http, method, resource));
97
98 if (!http)
99 http = _cupsConnect();
100
101 if (!http || !method || !resource)
102 return (-1);
103
104 DEBUG_printf(("2cupsDoAuthentication: digest_tries=%d, userpass=\"%s\"",
105 http->digest_tries, http->userpass));
106 DEBUG_printf(("2cupsDoAuthentication: WWW-Authenticate=\"%s\"",
107 httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE)));
108
109 /*
110 * Clear the current authentication string...
111 */
112
113 httpSetAuthString(http, NULL, NULL);
114
115 /*
116 * See if we can do local authentication...
117 */
118
119 if (http->digest_tries < 3)
120 {
121 if ((localauth = cups_local_auth(http)) == 0)
122 {
123 DEBUG_printf(("2cupsDoAuthentication: authstring=\"%s\"",
124 http->authstring));
125
126 if (http->status == HTTP_UNAUTHORIZED)
127 http->digest_tries ++;
128
129 return (0);
130 }
131 else if (localauth == -1)
132 {
133 http->status = HTTP_AUTHORIZATION_CANCELED;
134 return (-1); /* Error or canceled */
135 }
136 }
137
138 /*
139 * Nope, see if we should retry the current username:password...
140 */
141
142 if ((http->digest_tries > 1 || !http->userpass[0]) &&
143 strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
144 {
145 /*
146 * Nope - get a new password from the user...
147 */
148
149 cg = _cupsGlobals();
150
151 if (!cg->lang_default)
152 cg->lang_default = cupsLangDefault();
153
154 snprintf(prompt, sizeof(prompt),
155 _cupsLangString(cg->lang_default, _("Password for %s on %s? ")),
156 cupsUser(),
157 http->hostname[0] == '/' ? "localhost" : http->hostname);
158
159 http->digest_tries = strncasecmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE],
160 "Digest", 5) != 0;
161 http->userpass[0] = '\0';
162
163 if ((password = cupsGetPassword2(prompt, http, method, resource)) == NULL)
164 {
165 http->status = HTTP_AUTHORIZATION_CANCELED;
166 return (-1);
167 }
168
169 snprintf(http->userpass, sizeof(http->userpass), "%s:%s", cupsUser(),
170 password);
171 }
172 else if (http->status == HTTP_UNAUTHORIZED)
173 http->digest_tries ++;
174
175 if (http->status == HTTP_UNAUTHORIZED && http->digest_tries >= 3)
176 {
177 DEBUG_printf(("1cupsDoAuthentication: Too many authentication tries (%d)",
178 http->digest_tries));
179
180 http->status = HTTP_AUTHORIZATION_CANCELED;
181 return (-1);
182 }
183
184 /*
185 * Got a password; encode it for the server...
186 */
187
188 if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
189 {
190 #ifdef HAVE_GSSAPI
191 /*
192 * Kerberos authentication...
193 */
194
195 OM_uint32 minor_status, /* Minor status code */
196 major_status; /* Major status code */
197 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER,
198 /* Output token */
199 input_token = GSS_C_EMPTY_BUFFER;
200 /* Input token */
201 char *gss_service_name;
202 /* GSS service name */
203 # ifdef USE_SPNEGO
204 const char *authorization;
205 /* Pointer into Authorization string */
206 # endif /* USE_SPNEGO */
207
208
209 # ifdef __APPLE__
210 /*
211 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
212 * to use it...
213 */
214
215 if (gss_init_sec_context == NULL)
216 {
217 DEBUG_puts("1cupsDoAuthentication: Weak-linked GSSAPI/Kerberos framework "
218 "is not present");
219 http->status = HTTP_AUTHORIZATION_CANCELED;
220
221 return (-1);
222 }
223 # endif /* __APPLE__ */
224
225 if (http->gssname == GSS_C_NO_NAME)
226 {
227 if ((gss_service_name = getenv("CUPS_GSSSERVICENAME")) == NULL)
228 gss_service_name = CUPS_DEFAULT_GSSSERVICENAME;
229 else
230 DEBUG_puts("2cupsDoAuthentication: GSS service name set via "
231 "environment variable");
232
233 http->gssname = cups_get_gssname(http, gss_service_name);
234 }
235
236 # ifdef USE_SPNEGO /* We don't implement SPNEGO just yet... */
237 /*
238 * Find the start of the Kerberos input token...
239 */
240
241 authorization = httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE);
242
243 authorization += 9;
244 while (*authorization && _cups_isspace(*authorization))
245 authorization ++;
246
247 if (*authorization)
248 {
249 /*
250 * Decode the authorization string to get the input token...
251 */
252
253 int len = strlen(authorization);
254
255 input_token.value = malloc(len);
256 input_token.value = httpDecode64_2(input_token.value, &len,
257 authorization);
258 input_token.length = len;
259
260 # ifdef DEBUG
261 {
262 char *ptr = (char *)input_token.value;
263 int left = len;
264
265 fputs("input_token=", stdout);
266 while (left > 0)
267 {
268 if (*ptr < ' ')
269 printf("\\%03o", *ptr & 255);
270 else
271 putchar(*ptr);
272 ptr ++;
273 left --;
274 }
275 putchar('\n');
276 }
277 # endif /* DEBUG */
278 }
279 # endif /* USE_SPNEGO */
280
281 if (http->gssctx != GSS_C_NO_CONTEXT)
282 {
283 gss_delete_sec_context(&minor_status, &http->gssctx, GSS_C_NO_BUFFER);
284 http->gssctx = GSS_C_NO_CONTEXT;
285 }
286
287 major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
288 &http->gssctx,
289 http->gssname, http->gssmech,
290 #ifdef GSS_C_DELEG_POLICY_FLAG
291 GSS_C_DELEG_POLICY_FLAG |
292 #endif /* GSS_C_DELEG_POLICY_FLAG */
293 GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG,
294 GSS_C_INDEFINITE,
295 GSS_C_NO_CHANNEL_BINDINGS,
296 &input_token, &http->gssmech,
297 &output_token, NULL, NULL);
298
299 if (input_token.value)
300 free(input_token.value);
301
302 if (GSS_ERROR(major_status))
303 {
304 cups_gss_printf(major_status, minor_status,
305 "cupsDoAuthentication: Unable to initialize security "
306 "context");
307 http->status = HTTP_AUTHORIZATION_CANCELED;
308
309 return (-1);
310 }
311
312 if (major_status == GSS_S_CONTINUE_NEEDED)
313 cups_gss_printf(major_status, minor_status,
314 "cupsDoAuthentication: Continuation needed!");
315
316 if (output_token.length > 0 && output_token.length <= 65536)
317 {
318 /*
319 * Allocate the authorization string since Windows KDCs can have
320 * arbitrarily large credentials...
321 */
322
323 int authsize = 10 + /* "Negotiate " */
324 output_token.length * 4 / 3 + 1 + /* Base64 */
325 1; /* nul */
326
327 httpSetAuthString(http, NULL, NULL);
328
329 if ((http->authstring = malloc(authsize)) == NULL)
330 {
331 http->authstring = http->_authstring;
332 authsize = sizeof(http->_authstring);
333 }
334
335 strcpy(http->authstring, "Negotiate ");
336 httpEncode64_2(http->authstring + 10, authsize - 10, output_token.value,
337 output_token.length);
338
339 gss_release_buffer(&minor_status, &output_token);
340 }
341 else
342 {
343 DEBUG_printf(("1cupsDoAuthentication: Kerberos credentials too large - "
344 "%d bytes!", (int)output_token.length));
345 http->status = HTTP_AUTHORIZATION_CANCELED;
346 gss_release_buffer(&minor_status, &output_token);
347
348 return (-1);
349 }
350 #endif /* HAVE_GSSAPI */
351 }
352 else if (strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Digest", 6))
353 {
354 /*
355 * Basic authentication...
356 */
357
358 char encode[256]; /* Base64 buffer */
359
360
361 httpEncode64_2(encode, sizeof(encode), http->userpass,
362 (int)strlen(http->userpass));
363 httpSetAuthString(http, "Basic", encode);
364 }
365 else
366 {
367 /*
368 * Digest authentication...
369 */
370
371 char encode[33], /* MD5 buffer */
372 digest[1024]; /* Digest auth data */
373
374
375 httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "realm", realm);
376 httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "nonce", nonce);
377
378 httpMD5(cupsUser(), realm, strchr(http->userpass, ':') + 1, encode);
379 httpMD5Final(nonce, method, resource, encode);
380 snprintf(digest, sizeof(digest),
381 "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", "
382 "response=\"%s\"", cupsUser(), realm, nonce, resource, encode);
383 httpSetAuthString(http, "Digest", digest);
384 }
385
386 DEBUG_printf(("1cupsDoAuthentication: authstring=\"%s\"", http->authstring));
387
388 return (0);
389 }
390
391
392 #ifdef HAVE_GSSAPI
393 /*
394 * 'cups_get_gssname()' - Get CUPS service credentials for authentication.
395 */
396
397 static gss_name_t /* O - Server name */
398 cups_get_gssname(
399 http_t *http, /* I - Connection to server */
400 const char *service_name) /* I - Service name */
401 {
402 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
403 /* Service token */
404 OM_uint32 major_status, /* Major status code */
405 minor_status; /* Minor status code */
406 gss_name_t server_name; /* Server name */
407 char buf[1024], /* Name buffer */
408 fqdn[HTTP_MAX_URI]; /* Server name buffer */
409
410
411 DEBUG_printf(("7cups_get_gssname(http=%p, service_name=\"%s\")", http,
412 service_name));
413
414
415 /*
416 * Get the hostname...
417 */
418
419 httpGetHostname(http, fqdn, sizeof(fqdn));
420
421 if (!strcmp(fqdn, "localhost"))
422 httpGetHostname(NULL, fqdn, sizeof(fqdn));
423
424 /*
425 * Get a server name we can use for authentication purposes...
426 */
427
428 snprintf(buf, sizeof(buf), "%s@%s", service_name, fqdn);
429
430 DEBUG_printf(("9cups_get_gssname: Looking up %s...", buf));
431
432 token.value = buf;
433 token.length = strlen(buf);
434 server_name = GSS_C_NO_NAME;
435 major_status = gss_import_name(&minor_status, &token,
436 GSS_C_NT_HOSTBASED_SERVICE,
437 &server_name);
438
439 if (GSS_ERROR(major_status))
440 {
441 cups_gss_printf(major_status, minor_status,
442 "cups_get_gssname: gss_import_name() failed");
443 return (NULL);
444 }
445
446 return (server_name);
447 }
448
449
450 # ifdef DEBUG
451 /*
452 * 'cups_gss_printf()' - Show debug error messages from GSSAPI...
453 */
454
455 static void
456 cups_gss_printf(OM_uint32 major_status,/* I - Major status code */
457 OM_uint32 minor_status,/* I - Minor status code */
458 const char *message) /* I - Prefix for error message */
459 {
460 OM_uint32 err_major_status, /* Major status code for display */
461 err_minor_status; /* Minor status code for display */
462 OM_uint32 msg_ctx; /* Message context */
463 gss_buffer_desc major_status_string = GSS_C_EMPTY_BUFFER,
464 /* Major status message */
465 minor_status_string = GSS_C_EMPTY_BUFFER;
466 /* Minor status message */
467
468
469 msg_ctx = 0;
470 err_major_status = gss_display_status(&err_minor_status,
471 major_status,
472 GSS_C_GSS_CODE,
473 GSS_C_NO_OID,
474 &msg_ctx,
475 &major_status_string);
476
477 if (!GSS_ERROR(err_major_status))
478 gss_display_status(&err_minor_status, minor_status, GSS_C_MECH_CODE,
479 GSS_C_NULL_OID, &msg_ctx, &minor_status_string);
480
481 DEBUG_printf(("1%s: %s, %s", message, (char *)major_status_string.value,
482 (char *)minor_status_string.value));
483
484 gss_release_buffer(&err_minor_status, &major_status_string);
485 gss_release_buffer(&err_minor_status, &minor_status_string);
486 }
487 # endif /* DEBUG */
488 #endif /* HAVE_GSSAPI */
489
490
491 /*
492 * 'cups_local_auth()' - Get the local authorization certificate if
493 * available/applicable...
494 */
495
496 static int /* O - 0 if available */
497 /* 1 if not available */
498 /* -1 error */
499 cups_local_auth(http_t *http) /* I - HTTP connection to server */
500 {
501 #if defined(WIN32) || defined(__EMX__)
502 /*
503 * Currently WIN32 and OS-2 do not support the CUPS server...
504 */
505
506 return (1);
507 #else
508 int pid; /* Current process ID */
509 FILE *fp; /* Certificate file */
510 char trc[16], /* Try Root Certificate parameter */
511 filename[1024], /* Certificate filename */
512 certificate[33];/* Certificate string */
513 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
514 # if defined(HAVE_AUTHORIZATION_H)
515 OSStatus status; /* Status */
516 AuthorizationItem auth_right; /* Authorization right */
517 AuthorizationRights auth_rights; /* Authorization rights */
518 AuthorizationFlags auth_flags; /* Authorization flags */
519 AuthorizationExternalForm auth_extrn; /* Authorization ref external */
520 char auth_key[1024]; /* Buffer */
521 char buffer[1024]; /* Buffer */
522 # endif /* HAVE_AUTHORIZATION_H */
523
524
525 DEBUG_printf(("7cups_local_auth(http=%p) hostaddr=%s, hostname=\"%s\"",
526 http, httpAddrString(http->hostaddr, filename, sizeof(filename)), http->hostname));
527
528 /*
529 * See if we are accessing localhost...
530 */
531
532 if (!httpAddrLocalhost(http->hostaddr) &&
533 strcasecmp(http->hostname, "localhost") != 0)
534 {
535 DEBUG_puts("8cups_local_auth: Not a local connection!");
536 return (1);
537 }
538
539 # if defined(HAVE_AUTHORIZATION_H)
540 /*
541 * Delete any previous authorization reference...
542 */
543
544 if (http->auth_ref)
545 {
546 AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
547 http->auth_ref = NULL;
548 }
549
550 if (!getenv("GATEWAY_INTERFACE") &&
551 httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
552 auth_key, sizeof(auth_key)))
553 {
554 status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
555 kAuthorizationFlagDefaults, &http->auth_ref);
556 if (status != errAuthorizationSuccess)
557 {
558 DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d (%s)",
559 (int)status, cssmErrorString(status)));
560 return (-1);
561 }
562
563 auth_right.name = auth_key;
564 auth_right.valueLength = 0;
565 auth_right.value = NULL;
566 auth_right.flags = 0;
567
568 auth_rights.count = 1;
569 auth_rights.items = &auth_right;
570
571 auth_flags = kAuthorizationFlagDefaults |
572 kAuthorizationFlagPreAuthorize |
573 kAuthorizationFlagInteractionAllowed |
574 kAuthorizationFlagExtendRights;
575
576 status = AuthorizationCopyRights(http->auth_ref, &auth_rights,
577 kAuthorizationEmptyEnvironment,
578 auth_flags, NULL);
579 if (status == errAuthorizationSuccess)
580 status = AuthorizationMakeExternalForm(http->auth_ref, &auth_extrn);
581
582 if (status == errAuthorizationSuccess)
583 {
584 /*
585 * Set the authorization string and return...
586 */
587
588 httpEncode64_2(buffer, sizeof(buffer), (void *)&auth_extrn,
589 sizeof(auth_extrn));
590
591 httpSetAuthString(http, "AuthRef", buffer);
592
593 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
594 http->authstring));
595 return (0);
596 }
597 else if (status == errAuthorizationCanceled)
598 return (-1);
599
600 DEBUG_printf(("9cups_local_auth: AuthorizationCopyRights() returned %d (%s)",
601 (int)status, cssmErrorString(status)));
602
603 /*
604 * Fall through to try certificates...
605 */
606 }
607 # endif /* HAVE_AUTHORIZATION_H */
608
609 # if defined(SO_PEERCRED) && defined(AF_LOCAL)
610 /*
611 * See if we can authenticate using the peer credentials provided over a
612 * domain socket; if so, specify "PeerCred username" as the authentication
613 * information...
614 */
615
616 # ifdef HAVE_GSSAPI
617 if (strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9) &&
618 # else
619 if (
620 # endif /* HAVE_GSSAPI */
621 http->hostaddr->addr.sa_family == AF_LOCAL &&
622 !getenv("GATEWAY_INTERFACE")) /* Not via CGI programs... */
623 {
624 /*
625 * Verify that the current cupsUser() matches the current UID...
626 */
627
628 struct passwd *pwd; /* Password information */
629 const char *username; /* Current username */
630
631 username = cupsUser();
632
633 if ((pwd = getpwnam(username)) != NULL && pwd->pw_uid == getuid())
634 {
635 httpSetAuthString(http, "PeerCred", username);
636
637 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
638 http->authstring));
639
640 return (0);
641 }
642 }
643 # endif /* SO_PEERCRED && AF_LOCAL */
644
645 /*
646 * Try opening a certificate file for this PID. If that fails,
647 * try the root certificate...
648 */
649
650 pid = getpid();
651 snprintf(filename, sizeof(filename), "%s/certs/%d", cg->cups_statedir, pid);
652 if ((fp = fopen(filename, "r")) == NULL && pid > 0)
653 {
654 /*
655 * No certificate for this PID; see if we can get the root certificate...
656 */
657
658 DEBUG_printf(("9cups_local_auth: Unable to open file %s: %s",
659 filename, strerror(errno)));
660
661 #ifdef HAVE_GSSAPI
662 if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
663 {
664 /*
665 * Kerberos required, don't try the root certificate...
666 */
667
668 return (1);
669 }
670 #endif /* HAVE_GSSAPI */
671
672 if (!httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "trc", trc,
673 sizeof(trc)))
674 {
675 /*
676 * Scheduler doesn't want us to use the root certificate...
677 */
678
679 return (1);
680 }
681
682 snprintf(filename, sizeof(filename), "%s/certs/0", cg->cups_statedir);
683 fp = fopen(filename, "r");
684 }
685
686 if (fp)
687 {
688 /*
689 * Read the certificate from the file...
690 */
691
692 fgets(certificate, sizeof(certificate), fp);
693 fclose(fp);
694
695 /*
696 * Set the authorization string and return...
697 */
698
699 httpSetAuthString(http, "Local", certificate);
700
701 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
702 http->authstring));
703
704 return (0);
705 }
706
707 return (1);
708 #endif /* WIN32 || __EMX__ */
709 }
710
711
712 /*
713 * End of "$Id: auth.c 7720 2008-07-11 22:46:21Z mike $".
714 */