2 * "$Id: auth.c 7720 2008-07-11 22:46:21Z mike $"
4 * Authentication functions for the Common UNIX Printing System (CUPS).
6 * Copyright 2007-2009 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products.
9 * This file contains Kerberos support code, copyright 2006 by
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/".
18 * This file is subject to the Apple OS-Developed Software exception.
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...
30 * Include necessary headers...
40 #if defined(WIN32) || defined(__EMX__)
44 #endif /* WIN32 || __EMX__ */
46 #if HAVE_AUTHORIZATION_H
47 # include <Security/Authorization.h>
48 # ifdef HAVE_SECBASEPRIV_H
49 # include <Security/SecBasePriv.h>
51 extern const char *cssmErrorString(int error
);
52 # endif /* HAVE_SECBASEPRIV_H */
53 #endif /* HAVE_AUTHORIZATION_H */
55 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
57 #endif /* SO_PEERCRED && AF_LOCAL */
65 static gss_name_t
cups_get_gssname(http_t
*http
, const char *service_name
);
67 static void cups_gss_printf(OM_uint32 major_status
, OM_uint32 minor_status
,
70 # define cups_gss_printf(major, minor, message)
72 #endif /* HAVE_GSSAPI */
73 static int cups_local_auth(http_t
*http
);
77 * 'cupsDoAuthentication()' - Authenticate a request.
79 * This function should be called in response to a @code HTTP_UNAUTHORIZED@
80 * status, prior to resubmitting your request.
82 * @since CUPS 1.1.20/Mac OS X 10.4@
85 int /* O - 0 on success, -1 on error */
87 http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
88 const char *method
, /* I - Request method ("GET", "POST", "PUT") */
89 const char *resource
) /* I - Resource path */
91 const char *password
; /* Password string */
92 char prompt
[1024], /* Prompt for user */
93 realm
[HTTP_MAX_VALUE
], /* realm="xyz" string */
94 nonce
[HTTP_MAX_VALUE
]; /* nonce="xyz" string */
95 int localauth
; /* Local authentication result */
96 _cups_globals_t
*cg
; /* Global data */
99 DEBUG_printf(("cupsDoAuthentication(http=%p, method=\"%s\", resource=\"%s\")",
100 http
, method
, resource
));
101 DEBUG_printf(("2cupsDoAuthentication: digest_tries=%d, userpass=\"%s\"",
102 http
->digest_tries
, http
->userpass
));
103 DEBUG_printf(("2cupsDoAuthentication: WWW-Authenticate=\"%s\"",
104 httpGetField(http
, HTTP_FIELD_WWW_AUTHENTICATE
)));
107 http
= _cupsConnect();
109 if (!http
|| !method
|| !resource
)
113 * Clear the current authentication string...
116 httpSetAuthString(http
, NULL
, NULL
);
119 * See if we can do local authentication...
122 if (http
->digest_tries
< 3)
124 if ((localauth
= cups_local_auth(http
)) == 0)
126 DEBUG_printf(("2cupsDoAuthentication: authstring=\"%s\"",
129 if (http
->status
== HTTP_UNAUTHORIZED
)
130 http
->digest_tries
++;
134 else if (localauth
== -1)
136 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
137 return (-1); /* Error or canceled */
142 * Nope, see if we should retry the current username:password...
145 if ((http
->digest_tries
> 1 || !http
->userpass
[0]) &&
146 strncmp(http
->fields
[HTTP_FIELD_WWW_AUTHENTICATE
], "Negotiate", 9))
149 * Nope - get a new password from the user...
154 if (!cg
->lang_default
)
155 cg
->lang_default
= cupsLangDefault();
157 snprintf(prompt
, sizeof(prompt
),
158 _cupsLangString(cg
->lang_default
, _("Password for %s on %s? ")),
160 http
->hostname
[0] == '/' ? "localhost" : http
->hostname
);
162 http
->digest_tries
= strncasecmp(http
->fields
[HTTP_FIELD_WWW_AUTHENTICATE
],
164 http
->userpass
[0] = '\0';
166 if ((password
= cupsGetPassword2(prompt
, http
, method
, resource
)) == NULL
)
168 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
174 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
178 snprintf(http
->userpass
, sizeof(http
->userpass
), "%s:%s", cupsUser(),
181 else if (http
->status
== HTTP_UNAUTHORIZED
)
182 http
->digest_tries
++;
185 * Got a password; encode it for the server...
188 if (!strncmp(http
->fields
[HTTP_FIELD_WWW_AUTHENTICATE
], "Negotiate", 9))
192 * Kerberos authentication...
195 OM_uint32 minor_status
, /* Minor status code */
196 major_status
; /* Major status code */
197 gss_buffer_desc output_token
= GSS_C_EMPTY_BUFFER
,
199 input_token
= GSS_C_EMPTY_BUFFER
;
201 char *gss_service_name
;
202 /* GSS service name */
204 const char *authorization
;
205 /* Pointer into Authorization string */
206 # endif /* USE_SPNEGO */
211 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
215 if (gss_init_sec_context
== NULL
)
217 DEBUG_puts("1cupsDoAuthentication: Weak-linked GSSAPI/Kerberos framework "
219 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
223 # endif /* __APPLE__ */
225 if (http
->status
== HTTP_UNAUTHORIZED
&& http
->digest_tries
>= 3)
227 DEBUG_printf(("1cupsDoAuthentication: too many Negotiate tries (%d)",
228 http
->digest_tries
));
229 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
234 if (http
->gssname
== GSS_C_NO_NAME
)
236 if ((gss_service_name
= getenv("CUPS_GSSSERVICENAME")) == NULL
)
237 gss_service_name
= CUPS_DEFAULT_GSSSERVICENAME
;
239 DEBUG_puts("2cupsDoAuthentication: GSS service name set via "
240 "environment variable");
242 http
->gssname
= cups_get_gssname(http
, gss_service_name
);
245 # ifdef USE_SPNEGO /* We don't implement SPNEGO just yet... */
247 * Find the start of the Kerberos input token...
250 authorization
= httpGetField(http
, HTTP_FIELD_WWW_AUTHENTICATE
);
253 while (*authorization
&& isspace(*authorization
& 255))
259 * Decode the authorization string to get the input token...
262 int len
= strlen(authorization
);
264 input_token
.value
= malloc(len
);
265 input_token
.value
= httpDecode64_2(input_token
.value
, &len
,
267 input_token
.length
= len
;
271 char *ptr
= (char *)input_token
.value
;
274 fputs("input_token=", stdout
);
278 printf("\\%03o", *ptr
& 255);
288 # endif /* USE_SPNEGO */
290 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
292 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
293 http
->gssctx
= GSS_C_NO_CONTEXT
;
296 major_status
= gss_init_sec_context(&minor_status
, GSS_C_NO_CREDENTIAL
,
298 http
->gssname
, http
->gssmech
,
299 #ifdef GSS_C_DELEG_POLICY_FLAG
300 GSS_C_DELEG_POLICY_FLAG
|
301 #endif /* GSS_C_DELEG_POLICY_FLAG */
302 GSS_C_MUTUAL_FLAG
| GSS_C_INTEG_FLAG
,
304 GSS_C_NO_CHANNEL_BINDINGS
,
305 &input_token
, &http
->gssmech
,
306 &output_token
, NULL
, NULL
);
308 if (input_token
.value
)
309 free(input_token
.value
);
311 if (GSS_ERROR(major_status
))
313 cups_gss_printf(major_status
, minor_status
,
314 "cupsDoAuthentication: Unable to initialize security "
316 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
321 if (major_status
== GSS_S_CONTINUE_NEEDED
)
322 cups_gss_printf(major_status
, minor_status
,
323 "cupsDoAuthentication: Continuation needed!");
325 if (output_token
.length
> 0 && output_token
.length
<= 65536)
328 * Allocate the authorization string since Windows KDCs can have
329 * arbitrarily large credentials...
332 int authsize
= 10 + /* "Negotiate " */
333 output_token
.length
* 4 / 3 + 1 + /* Base64 */
336 httpSetAuthString(http
, NULL
, NULL
);
338 if ((http
->authstring
= malloc(authsize
)) == NULL
)
340 http
->authstring
= http
->_authstring
;
341 authsize
= sizeof(http
->_authstring
);
344 strcpy(http
->authstring
, "Negotiate ");
345 httpEncode64_2(http
->authstring
+ 10, authsize
- 10, output_token
.value
,
346 output_token
.length
);
348 gss_release_buffer(&minor_status
, &output_token
);
352 DEBUG_printf(("1cupsDoAuthentication: Kerberos credentials too large - "
353 "%d bytes!", (int)output_token
.length
));
354 http
->status
= HTTP_AUTHORIZATION_CANCELED
;
355 gss_release_buffer(&minor_status
, &output_token
);
359 #endif /* HAVE_GSSAPI */
361 else if (strncmp(http
->fields
[HTTP_FIELD_WWW_AUTHENTICATE
], "Digest", 6))
364 * Basic authentication...
367 char encode
[256]; /* Base64 buffer */
370 httpEncode64_2(encode
, sizeof(encode
), http
->userpass
,
371 (int)strlen(http
->userpass
));
372 httpSetAuthString(http
, "Basic", encode
);
377 * Digest authentication...
380 char encode
[33], /* MD5 buffer */
381 digest
[1024]; /* Digest auth data */
384 httpGetSubField(http
, HTTP_FIELD_WWW_AUTHENTICATE
, "realm", realm
);
385 httpGetSubField(http
, HTTP_FIELD_WWW_AUTHENTICATE
, "nonce", nonce
);
387 httpMD5(cupsUser(), realm
, strchr(http
->userpass
, ':') + 1, encode
);
388 httpMD5Final(nonce
, method
, resource
, encode
);
389 snprintf(digest
, sizeof(digest
),
390 "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", "
391 "response=\"%s\"", cupsUser(), realm
, nonce
, resource
, encode
);
392 httpSetAuthString(http
, "Digest", digest
);
395 DEBUG_printf(("1cupsDoAuthentication: authstring=\"%s\"", http
->authstring
));
403 * 'cups_get_gssname()' - Get CUPS service credentials for authentication.
406 static gss_name_t
/* O - Server name */
408 http_t
*http
, /* I - Connection to server */
409 const char *service_name
) /* I - Service name */
411 gss_buffer_desc token
= GSS_C_EMPTY_BUFFER
;
413 OM_uint32 major_status
, /* Major status code */
414 minor_status
; /* Minor status code */
415 gss_name_t server_name
; /* Server name */
416 char buf
[1024], /* Name buffer */
417 fqdn
[HTTP_MAX_URI
]; /* Server name buffer */
420 DEBUG_printf(("7cups_get_gssname(http=%p, service_name=\"%s\")", http
,
425 * Get the hostname...
428 httpGetHostname(http
, fqdn
, sizeof(fqdn
));
430 if (!strcmp(fqdn
, "localhost"))
431 httpGetHostname(NULL
, fqdn
, sizeof(fqdn
));
434 * Get a server name we can use for authentication purposes...
437 snprintf(buf
, sizeof(buf
), "%s@%s", service_name
, fqdn
);
439 DEBUG_printf(("9cups_get_gssname: Looking up %s...", buf
));
442 token
.length
= strlen(buf
);
443 server_name
= GSS_C_NO_NAME
;
444 major_status
= gss_import_name(&minor_status
, &token
,
445 GSS_C_NT_HOSTBASED_SERVICE
,
448 if (GSS_ERROR(major_status
))
450 cups_gss_printf(major_status
, minor_status
,
451 "cups_get_gssname: gss_import_name() failed");
455 return (server_name
);
461 * 'cups_gss_printf()' - Show debug error messages from GSSAPI...
465 cups_gss_printf(OM_uint32 major_status
,/* I - Major status code */
466 OM_uint32 minor_status
,/* I - Minor status code */
467 const char *message
) /* I - Prefix for error message */
469 OM_uint32 err_major_status
, /* Major status code for display */
470 err_minor_status
; /* Minor status code for display */
471 OM_uint32 msg_ctx
; /* Message context */
472 gss_buffer_desc major_status_string
= GSS_C_EMPTY_BUFFER
,
473 /* Major status message */
474 minor_status_string
= GSS_C_EMPTY_BUFFER
;
475 /* Minor status message */
479 err_major_status
= gss_display_status(&err_minor_status
,
484 &major_status_string
);
486 if (!GSS_ERROR(err_major_status
))
487 gss_display_status(&err_minor_status
, minor_status
, GSS_C_MECH_CODE
,
488 GSS_C_NULL_OID
, &msg_ctx
, &minor_status_string
);
490 DEBUG_printf(("1%s: %s, %s", message
, (char *)major_status_string
.value
,
491 (char *)minor_status_string
.value
));
493 gss_release_buffer(&err_minor_status
, &major_status_string
);
494 gss_release_buffer(&err_minor_status
, &minor_status_string
);
497 #endif /* HAVE_GSSAPI */
501 * 'cups_local_auth()' - Get the local authorization certificate if
502 * available/applicable...
505 static int /* O - 0 if available */
506 /* 1 if not available */
508 cups_local_auth(http_t
*http
) /* I - HTTP connection to server */
510 #if defined(WIN32) || defined(__EMX__)
512 * Currently WIN32 and OS-2 do not support the CUPS server...
517 int pid
; /* Current process ID */
518 FILE *fp
; /* Certificate file */
519 char trc
[16], /* Try Root Certificate parameter */
520 filename
[1024], /* Certificate filename */
521 certificate
[33];/* Certificate string */
522 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
523 # if defined(HAVE_AUTHORIZATION_H)
524 OSStatus status
; /* Status */
525 AuthorizationItem auth_right
; /* Authorization right */
526 AuthorizationRights auth_rights
; /* Authorization rights */
527 AuthorizationFlags auth_flags
; /* Authorization flags */
528 AuthorizationExternalForm auth_extrn
; /* Authorization ref external */
529 char auth_key
[1024]; /* Buffer */
530 char buffer
[1024]; /* Buffer */
531 # endif /* HAVE_AUTHORIZATION_H */
534 DEBUG_printf(("7cups_local_auth(http=%p) hostaddr=%s, hostname=\"%s\"",
535 http
, httpAddrString(http
->hostaddr
, filename
, sizeof(filename
)), http
->hostname
));
538 * See if we are accessing localhost...
541 if (!httpAddrLocalhost(http
->hostaddr
) &&
542 strcasecmp(http
->hostname
, "localhost") != 0)
544 DEBUG_puts("8cups_local_auth: Not a local connection!");
548 # if defined(HAVE_AUTHORIZATION_H)
550 * Delete any previous authorization reference...
555 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
556 http
->auth_ref
= NULL
;
559 if (!getenv("GATEWAY_INTERFACE") &&
560 httpGetSubField2(http
, HTTP_FIELD_WWW_AUTHENTICATE
, "authkey",
561 auth_key
, sizeof(auth_key
)))
563 status
= AuthorizationCreate(NULL
, kAuthorizationEmptyEnvironment
,
564 kAuthorizationFlagDefaults
, &http
->auth_ref
);
565 if (status
!= errAuthorizationSuccess
)
567 DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d (%s)",
568 (int)status
, cssmErrorString(status
)));
572 auth_right
.name
= auth_key
;
573 auth_right
.valueLength
= 0;
574 auth_right
.value
= NULL
;
575 auth_right
.flags
= 0;
577 auth_rights
.count
= 1;
578 auth_rights
.items
= &auth_right
;
580 auth_flags
= kAuthorizationFlagDefaults
|
581 kAuthorizationFlagPreAuthorize
|
582 kAuthorizationFlagInteractionAllowed
|
583 kAuthorizationFlagExtendRights
;
585 status
= AuthorizationCopyRights(http
->auth_ref
, &auth_rights
,
586 kAuthorizationEmptyEnvironment
,
588 if (status
== errAuthorizationSuccess
)
589 status
= AuthorizationMakeExternalForm(http
->auth_ref
, &auth_extrn
);
591 if (status
== errAuthorizationSuccess
)
594 * Set the authorization string and return...
597 httpEncode64_2(buffer
, sizeof(buffer
), (void *)&auth_extrn
,
600 httpSetAuthString(http
, "AuthRef", buffer
);
602 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
606 else if (status
== errAuthorizationCanceled
)
609 DEBUG_printf(("9cups_local_auth: AuthorizationCopyRights() returned %d (%s)",
610 (int)status
, cssmErrorString(status
)));
613 * Fall through to try certificates...
616 # endif /* HAVE_AUTHORIZATION_H */
618 # if defined(SO_PEERCRED) && defined(AF_LOCAL)
620 * See if we can authenticate using the peer credentials provided over a
621 * domain socket; if so, specify "PeerCred username" as the authentication
626 if (strncmp(http
->fields
[HTTP_FIELD_WWW_AUTHENTICATE
], "Negotiate", 9) &&
629 # endif /* HAVE_GSSAPI */
630 http
->hostaddr
->addr
.sa_family
== AF_LOCAL
&&
631 !getenv("GATEWAY_INTERFACE")) /* Not via CGI programs... */
634 * Verify that the current cupsUser() matches the current UID...
637 struct passwd
*pwd
; /* Password information */
638 const char *username
; /* Current username */
640 username
= cupsUser();
642 if ((pwd
= getpwnam(username
)) != NULL
&& pwd
->pw_uid
== getuid())
644 httpSetAuthString(http
, "PeerCred", username
);
646 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
652 # endif /* SO_PEERCRED && AF_LOCAL */
655 * Try opening a certificate file for this PID. If that fails,
656 * try the root certificate...
660 snprintf(filename
, sizeof(filename
), "%s/certs/%d", cg
->cups_statedir
, pid
);
661 if ((fp
= fopen(filename
, "r")) == NULL
&& pid
> 0)
664 * No certificate for this PID; see if we can get the root certificate...
667 DEBUG_printf(("9cups_local_auth: Unable to open file %s: %s",
668 filename
, strerror(errno
)));
671 if (!strncmp(http
->fields
[HTTP_FIELD_WWW_AUTHENTICATE
], "Negotiate", 9))
674 * Kerberos required, don't try the root certificate...
679 #endif /* HAVE_GSSAPI */
681 if (!httpGetSubField2(http
, HTTP_FIELD_WWW_AUTHENTICATE
, "trc", trc
,
685 * Scheduler doesn't want us to use the root certificate...
691 snprintf(filename
, sizeof(filename
), "%s/certs/0", cg
->cups_statedir
);
692 fp
= fopen(filename
, "r");
698 * Read the certificate from the file...
701 fgets(certificate
, sizeof(certificate
), fp
);
705 * Set the authorization string and return...
708 httpSetAuthString(http
, "Local", certificate
);
710 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
717 #endif /* WIN32 || __EMX__ */
722 * End of "$Id: auth.c 7720 2008-07-11 22:46:21Z mike $".