]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/auth.c
Merge changes from CUPS 1.5svn-r9675.
[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-2011 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], "Basic", 5) ||
144 !strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Digest", 6)))
145 {
146 /*
147 * Nope - get a new password from the user...
148 */
149
150 cg = _cupsGlobals();
151
152 if (!cg->lang_default)
153 cg->lang_default = cupsLangDefault();
154
155 snprintf(prompt, sizeof(prompt),
156 _cupsLangString(cg->lang_default, _("Password for %s on %s? ")),
157 cupsUser(),
158 http->hostname[0] == '/' ? "localhost" : http->hostname);
159
160 http->digest_tries = strncasecmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE],
161 "Digest", 5) != 0;
162 http->userpass[0] = '\0';
163
164 if ((password = cupsGetPassword2(prompt, http, method, resource)) == NULL)
165 {
166 http->status = HTTP_AUTHORIZATION_CANCELED;
167 return (-1);
168 }
169
170 snprintf(http->userpass, sizeof(http->userpass), "%s:%s", cupsUser(),
171 password);
172 }
173 else if (http->status == HTTP_UNAUTHORIZED)
174 http->digest_tries ++;
175
176 if (http->status == HTTP_UNAUTHORIZED && http->digest_tries >= 3)
177 {
178 DEBUG_printf(("1cupsDoAuthentication: Too many authentication tries (%d)",
179 http->digest_tries));
180
181 http->status = HTTP_AUTHORIZATION_CANCELED;
182 return (-1);
183 }
184
185 /*
186 * Got a password; encode it for the server...
187 */
188
189 #ifdef HAVE_GSSAPI
190 if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
191 {
192 /*
193 * Kerberos authentication...
194 */
195
196 if (_cupsSetNegotiateAuthString(http))
197 {
198 http->status = HTTP_AUTHORIZATION_CANCELED;
199 return (-1);
200 }
201 }
202 else
203 #endif /* HAVE_GSSAPI */
204 if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Basic", 5))
205 {
206 /*
207 * Basic authentication...
208 */
209
210 char encode[256]; /* Base64 buffer */
211
212
213 httpEncode64_2(encode, sizeof(encode), http->userpass,
214 (int)strlen(http->userpass));
215 httpSetAuthString(http, "Basic", encode);
216 }
217 else if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Digest", 6))
218 {
219 /*
220 * Digest authentication...
221 */
222
223 char encode[33], /* MD5 buffer */
224 digest[1024]; /* Digest auth data */
225
226
227 httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "realm", realm);
228 httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "nonce", nonce);
229
230 httpMD5(cupsUser(), realm, strchr(http->userpass, ':') + 1, encode);
231 httpMD5Final(nonce, method, resource, encode);
232 snprintf(digest, sizeof(digest),
233 "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", "
234 "response=\"%s\"", cupsUser(), realm, nonce, resource, encode);
235 httpSetAuthString(http, "Digest", digest);
236 }
237 else
238 {
239 DEBUG_printf(("1cupsDoAuthentication: Unknown auth type: \"%s\"",
240 http->fields[HTTP_FIELD_WWW_AUTHENTICATE]));
241 http->status = HTTP_AUTHORIZATION_CANCELED;
242 return (-1);
243 }
244
245 DEBUG_printf(("1cupsDoAuthentication: authstring=\"%s\"", http->authstring));
246
247 return (0);
248 }
249
250
251 #ifdef HAVE_GSSAPI
252 /*
253 * '_cupsSetNegotiateAuthString()' - Set the Kerberos authentication string.
254 */
255
256 int /* O - 0 on success, -1 on error */
257 _cupsSetNegotiateAuthString(
258 http_t *http) /* I - Connection to server */
259 {
260 OM_uint32 minor_status, /* Minor status code */
261 major_status; /* Major status code */
262 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
263 /* Output token */
264 _cups_globals_t *cg = _cupsGlobals(); /* Thread globals */
265
266
267 # ifdef __APPLE__
268 /*
269 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
270 * to use it...
271 */
272
273 if (gss_init_sec_context == NULL)
274 {
275 DEBUG_puts("1_cupsSetNegotiateAuthString: Weak-linked GSSAPI/Kerberos "
276 "framework is not present");
277 return (-1);
278 }
279 # endif /* __APPLE__ */
280
281 if (http->gssname == GSS_C_NO_NAME)
282 {
283 if (!cg->gss_service_name[0])
284 _cupsSetDefaults();
285
286 http->gssname = cups_get_gssname(http, cg->gss_service_name);
287 }
288
289 if (http->gssctx != GSS_C_NO_CONTEXT)
290 {
291 gss_delete_sec_context(&minor_status, &http->gssctx, GSS_C_NO_BUFFER);
292 http->gssctx = GSS_C_NO_CONTEXT;
293 }
294
295 major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
296 &http->gssctx,
297 http->gssname, http->gssmech,
298 GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG,
299 GSS_C_INDEFINITE,
300 GSS_C_NO_CHANNEL_BINDINGS,
301 GSS_C_NO_BUFFER, &http->gssmech,
302 &output_token, NULL, NULL);
303
304 if (GSS_ERROR(major_status))
305 {
306 cups_gss_printf(major_status, minor_status,
307 "_cupsSetNegotiateAuthString: Unable to initialize "
308 "security context");
309 return (-1);
310 }
311
312 if (major_status == GSS_S_CONTINUE_NEEDED)
313 cups_gss_printf(major_status, minor_status,
314 "_cupsSetNegotiateAuthString: 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(("1_cupsSetNegotiateAuthString: Kerberos credentials too "
344 "large - %d bytes!", (int)output_token.length));
345 gss_release_buffer(&minor_status, &output_token);
346
347 return (-1);
348 }
349
350 return (0);
351 }
352
353
354 /*
355 * 'cups_get_gssname()' - Get CUPS service credentials for authentication.
356 */
357
358 static gss_name_t /* O - Server name */
359 cups_get_gssname(
360 http_t *http, /* I - Connection to server */
361 const char *service_name) /* I - Service name */
362 {
363 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
364 /* Service token */
365 OM_uint32 major_status, /* Major status code */
366 minor_status; /* Minor status code */
367 gss_name_t server_name; /* Server name */
368 char buf[1024], /* Name buffer */
369 fqdn[HTTP_MAX_URI]; /* Server name buffer */
370
371
372 DEBUG_printf(("7cups_get_gssname(http=%p, service_name=\"%s\")", http,
373 service_name));
374
375
376 /*
377 * Get the hostname...
378 */
379
380 httpGetHostname(http, fqdn, sizeof(fqdn));
381
382 if (!strcmp(fqdn, "localhost"))
383 httpGetHostname(NULL, fqdn, sizeof(fqdn));
384
385 /*
386 * Get a server name we can use for authentication purposes...
387 */
388
389 snprintf(buf, sizeof(buf), "%s@%s", service_name, fqdn);
390
391 DEBUG_printf(("9cups_get_gssname: Looking up %s...", buf));
392
393 token.value = buf;
394 token.length = strlen(buf);
395 server_name = GSS_C_NO_NAME;
396 major_status = gss_import_name(&minor_status, &token,
397 GSS_C_NT_HOSTBASED_SERVICE,
398 &server_name);
399
400 if (GSS_ERROR(major_status))
401 {
402 cups_gss_printf(major_status, minor_status,
403 "cups_get_gssname: gss_import_name() failed");
404 return (NULL);
405 }
406
407 return (server_name);
408 }
409
410
411 # ifdef DEBUG
412 /*
413 * 'cups_gss_printf()' - Show debug error messages from GSSAPI...
414 */
415
416 static void
417 cups_gss_printf(OM_uint32 major_status,/* I - Major status code */
418 OM_uint32 minor_status,/* I - Minor status code */
419 const char *message) /* I - Prefix for error message */
420 {
421 OM_uint32 err_major_status, /* Major status code for display */
422 err_minor_status; /* Minor status code for display */
423 OM_uint32 msg_ctx; /* Message context */
424 gss_buffer_desc major_status_string = GSS_C_EMPTY_BUFFER,
425 /* Major status message */
426 minor_status_string = GSS_C_EMPTY_BUFFER;
427 /* Minor status message */
428
429
430 msg_ctx = 0;
431 err_major_status = gss_display_status(&err_minor_status,
432 major_status,
433 GSS_C_GSS_CODE,
434 GSS_C_NO_OID,
435 &msg_ctx,
436 &major_status_string);
437
438 if (!GSS_ERROR(err_major_status))
439 gss_display_status(&err_minor_status, minor_status, GSS_C_MECH_CODE,
440 GSS_C_NULL_OID, &msg_ctx, &minor_status_string);
441
442 DEBUG_printf(("1%s: %s, %s", message, (char *)major_status_string.value,
443 (char *)minor_status_string.value));
444
445 gss_release_buffer(&err_minor_status, &major_status_string);
446 gss_release_buffer(&err_minor_status, &minor_status_string);
447 }
448 # endif /* DEBUG */
449 #endif /* HAVE_GSSAPI */
450
451
452 /*
453 * 'cups_local_auth()' - Get the local authorization certificate if
454 * available/applicable...
455 */
456
457 static int /* O - 0 if available */
458 /* 1 if not available */
459 /* -1 error */
460 cups_local_auth(http_t *http) /* I - HTTP connection to server */
461 {
462 #if defined(WIN32) || defined(__EMX__)
463 /*
464 * Currently WIN32 and OS-2 do not support the CUPS server...
465 */
466
467 return (1);
468 #else
469 int pid; /* Current process ID */
470 FILE *fp; /* Certificate file */
471 char trc[16], /* Try Root Certificate parameter */
472 filename[1024], /* Certificate filename */
473 certificate[33];/* Certificate string */
474 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
475 # if defined(HAVE_AUTHORIZATION_H)
476 OSStatus status; /* Status */
477 AuthorizationItem auth_right; /* Authorization right */
478 AuthorizationRights auth_rights; /* Authorization rights */
479 AuthorizationFlags auth_flags; /* Authorization flags */
480 AuthorizationExternalForm auth_extrn; /* Authorization ref external */
481 char auth_key[1024]; /* Buffer */
482 char buffer[1024]; /* Buffer */
483 # endif /* HAVE_AUTHORIZATION_H */
484
485
486 DEBUG_printf(("7cups_local_auth(http=%p) hostaddr=%s, hostname=\"%s\"",
487 http, httpAddrString(http->hostaddr, filename, sizeof(filename)), http->hostname));
488
489 /*
490 * See if we are accessing localhost...
491 */
492
493 if (!httpAddrLocalhost(http->hostaddr) &&
494 strcasecmp(http->hostname, "localhost") != 0)
495 {
496 DEBUG_puts("8cups_local_auth: Not a local connection!");
497 return (1);
498 }
499
500 # if defined(HAVE_AUTHORIZATION_H)
501 /*
502 * Delete any previous authorization reference...
503 */
504
505 if (http->auth_ref)
506 {
507 AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
508 http->auth_ref = NULL;
509 }
510
511 if (!getenv("GATEWAY_INTERFACE") &&
512 httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
513 auth_key, sizeof(auth_key)))
514 {
515 status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
516 kAuthorizationFlagDefaults, &http->auth_ref);
517 if (status != errAuthorizationSuccess)
518 {
519 DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d (%s)",
520 (int)status, cssmErrorString(status)));
521 return (-1);
522 }
523
524 auth_right.name = auth_key;
525 auth_right.valueLength = 0;
526 auth_right.value = NULL;
527 auth_right.flags = 0;
528
529 auth_rights.count = 1;
530 auth_rights.items = &auth_right;
531
532 auth_flags = kAuthorizationFlagDefaults |
533 kAuthorizationFlagPreAuthorize |
534 kAuthorizationFlagInteractionAllowed |
535 kAuthorizationFlagExtendRights;
536
537 status = AuthorizationCopyRights(http->auth_ref, &auth_rights,
538 kAuthorizationEmptyEnvironment,
539 auth_flags, NULL);
540 if (status == errAuthorizationSuccess)
541 status = AuthorizationMakeExternalForm(http->auth_ref, &auth_extrn);
542
543 if (status == errAuthorizationSuccess)
544 {
545 /*
546 * Set the authorization string and return...
547 */
548
549 httpEncode64_2(buffer, sizeof(buffer), (void *)&auth_extrn,
550 sizeof(auth_extrn));
551
552 httpSetAuthString(http, "AuthRef", buffer);
553
554 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
555 http->authstring));
556 return (0);
557 }
558 else if (status == errAuthorizationCanceled)
559 return (-1);
560
561 DEBUG_printf(("9cups_local_auth: AuthorizationCopyRights() returned %d (%s)",
562 (int)status, cssmErrorString(status)));
563
564 /*
565 * Fall through to try certificates...
566 */
567 }
568 # endif /* HAVE_AUTHORIZATION_H */
569
570 # if defined(SO_PEERCRED) && defined(AF_LOCAL)
571 /*
572 * See if we can authenticate using the peer credentials provided over a
573 * domain socket; if so, specify "PeerCred username" as the authentication
574 * information...
575 */
576
577 if (
578 # ifdef HAVE_GSSAPI
579 strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9) &&
580 # endif /* HAVE_GSSAPI */
581 # ifdef HAVE_AUTHORIZATION_H
582 !httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
583 auth_key, sizeof(auth_key)) &&
584 # endif /* HAVE_AUTHORIZATION_H */
585 http->hostaddr->addr.sa_family == AF_LOCAL &&
586 !getenv("GATEWAY_INTERFACE")) /* Not via CGI programs... */
587 {
588 /*
589 * Verify that the current cupsUser() matches the current UID...
590 */
591
592 struct passwd *pwd; /* Password information */
593 const char *username; /* Current username */
594
595 username = cupsUser();
596
597 if ((pwd = getpwnam(username)) != NULL && pwd->pw_uid == getuid())
598 {
599 httpSetAuthString(http, "PeerCred", username);
600
601 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
602 http->authstring));
603
604 return (0);
605 }
606 }
607 # endif /* SO_PEERCRED && AF_LOCAL */
608
609 /*
610 * Try opening a certificate file for this PID. If that fails,
611 * try the root certificate...
612 */
613
614 pid = getpid();
615 snprintf(filename, sizeof(filename), "%s/certs/%d", cg->cups_statedir, pid);
616 if ((fp = fopen(filename, "r")) == NULL && pid > 0)
617 {
618 /*
619 * No certificate for this PID; see if we can get the root certificate...
620 */
621
622 DEBUG_printf(("9cups_local_auth: Unable to open file %s: %s",
623 filename, strerror(errno)));
624
625 # ifdef HAVE_GSSAPI
626 if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
627 {
628 /*
629 * Kerberos required, don't try the root certificate...
630 */
631
632 return (1);
633 }
634 # endif /* HAVE_GSSAPI */
635
636 # ifdef HAVE_AUTHORIZATION_H
637 if (httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
638 auth_key, sizeof(auth_key)))
639 {
640 /*
641 * Don't use the root certificate as a replacement for an authkey...
642 */
643
644 return (1);
645 }
646 # endif /* HAVE_AUTHORIZATION_H */
647 if (!httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "trc", trc,
648 sizeof(trc)))
649 {
650 /*
651 * Scheduler doesn't want us to use the root certificate...
652 */
653
654 return (1);
655 }
656
657 snprintf(filename, sizeof(filename), "%s/certs/0", cg->cups_statedir);
658 fp = fopen(filename, "r");
659 }
660
661 if (fp)
662 {
663 /*
664 * Read the certificate from the file...
665 */
666
667 fgets(certificate, sizeof(certificate), fp);
668 fclose(fp);
669
670 /*
671 * Set the authorization string and return...
672 */
673
674 httpSetAuthString(http, "Local", certificate);
675
676 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
677 http->authstring));
678
679 return (0);
680 }
681
682 return (1);
683 #endif /* WIN32 || __EMX__ */
684 }
685
686
687 /*
688 * End of "$Id: auth.c 7720 2008-07-11 22:46:21Z mike $".
689 */