2 * "$Id: auth.c 10288 2012-02-15 19:21:37Z mike $"
4 * Authentication functions for CUPS.
6 * Copyright 2007-2011 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 * _cupsSetNegotiateAuthString() - Set the Kerberos authentication string.
24 * cups_gss_acquire() - Kerberos credentials callback.
25 * cups_gss_getname() - Get CUPS service credentials for
27 * cups_gss_printf() - Show debug error messages from GSSAPI.
28 * cups_local_auth() - Get the local authorization certificate if
29 * available/applicable.
33 * Include necessary headers...
36 #include "cups-private.h"
39 #if defined(WIN32) || defined(__EMX__)
43 #endif /* WIN32 || __EMX__ */
45 #if HAVE_AUTHORIZATION_H
46 # include <Security/Authorization.h>
47 # ifdef HAVE_SECBASEPRIV_H
48 # include <Security/SecBasePriv.h>
50 extern const char *cssmErrorString(int error);
51 # endif /* HAVE_SECBASEPRIV_H */
52 #endif /* HAVE_AUTHORIZATION_H */
54 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
56 #endif /* SO_PEERCRED && AF_LOCAL */
64 # ifdef HAVE_GSS_ACQUIRE_CRED_EX_F
65 # ifdef HAVE_GSS_GSSAPI_SPI_H
66 # include <GSS/gssapi_spi.h>
68 # define GSS_AUTH_IDENTITY_TYPE_1 1
69 # define gss_acquire_cred_ex_f __ApplePrivate_gss_acquire_cred_ex_f
70 typedef struct gss_auth_identity
77 gss_buffer_t *credentialsRef;
78 } gss_auth_identity_desc;
79 extern OM_uint32 gss_acquire_cred_ex_f(gss_status_id_t, const gss_name_t,
80 OM_uint32, OM_uint32, const gss_OID,
81 gss_cred_usage_t, gss_auth_identity_t,
82 void *, void (*)(void *, OM_uint32,
87 # endif /* HAVE_GSS_GSSAPI_SPI_H */
88 # include <dispatch/dispatch.h>
89 typedef struct _cups_gss_acquire_s /* Acquire callback data */
91 dispatch_semaphore_t sem; /* Synchronization semaphore */
92 OM_uint32 major; /* Returned status code */
93 gss_cred_id_t creds; /* Returned credentials */
94 } _cups_gss_acquire_t;
96 static void cups_gss_acquire(void *ctx, OM_uint32 major,
97 gss_status_id_t status,
98 gss_cred_id_t creds, gss_OID_set oids,
100 # endif /* HAVE_GSS_ACQUIRE_CRED_EX_F */
101 static gss_name_t cups_gss_getname(http_t *http, const char *service_name);
103 static void cups_gss_printf(OM_uint32 major_status, OM_uint32 minor_status,
104 const char *message);
106 # define cups_gss_printf(major, minor, message)
108 #endif /* HAVE_GSSAPI */
109 static int cups_local_auth(http_t *http);
113 * 'cupsDoAuthentication()' - Authenticate a request.
115 * This function should be called in response to a @code HTTP_UNAUTHORIZED@
116 * status, prior to resubmitting your request.
118 * @since CUPS 1.1.20/Mac OS X 10.4@
121 int /* O - 0 on success, -1 on error */
122 cupsDoAuthentication(
123 http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
124 const char *method, /* I - Request method ("GET", "POST", "PUT") */
125 const char *resource) /* I - Resource path */
127 const char *password, /* Password string */
128 *www_auth; /* WWW-Authenticate header */
129 char prompt[1024], /* Prompt for user */
130 realm[HTTP_MAX_VALUE], /* realm="xyz" string */
131 nonce[HTTP_MAX_VALUE]; /* nonce="xyz" string */
132 int localauth; /* Local authentication result */
133 _cups_globals_t *cg; /* Global data */
136 DEBUG_printf(("cupsDoAuthentication(http=%p, method=\"%s\", resource=\"%s\")",
137 http, method, resource));
140 http = _cupsConnect();
142 if (!http || !method || !resource)
145 DEBUG_printf(("2cupsDoAuthentication: digest_tries=%d, userpass=\"%s\"",
146 http->digest_tries, http->userpass));
147 DEBUG_printf(("2cupsDoAuthentication: WWW-Authenticate=\"%s\"",
148 httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE)));
151 * Clear the current authentication string...
154 httpSetAuthString(http, NULL, NULL);
157 * See if we can do local authentication...
160 if (http->digest_tries < 3)
162 if ((localauth = cups_local_auth(http)) == 0)
164 DEBUG_printf(("2cupsDoAuthentication: authstring=\"%s\"",
167 if (http->status == HTTP_UNAUTHORIZED)
168 http->digest_tries ++;
172 else if (localauth == -1)
174 http->status = HTTP_AUTHORIZATION_CANCELED;
175 return (-1); /* Error or canceled */
180 * Nope, see if we should retry the current username:password...
183 www_auth = http->fields[HTTP_FIELD_WWW_AUTHENTICATE];
185 if ((http->digest_tries > 1 || !http->userpass[0]) &&
186 (!_cups_strncasecmp(www_auth, "Basic", 5) ||
187 !_cups_strncasecmp(www_auth, "Digest", 6)))
190 * Nope - get a new password from the user...
195 if (!cg->lang_default)
196 cg->lang_default = cupsLangDefault();
198 snprintf(prompt, sizeof(prompt),
199 _cupsLangString(cg->lang_default, _("Password for %s on %s? ")),
201 http->hostname[0] == '/' ? "localhost" : http->hostname);
203 http->digest_tries = _cups_strncasecmp(www_auth, "Digest", 6) != 0;
204 http->userpass[0] = '\0';
206 if ((password = cupsGetPassword2(prompt, http, method, resource)) == NULL)
208 http->status = HTTP_AUTHORIZATION_CANCELED;
212 snprintf(http->userpass, sizeof(http->userpass), "%s:%s", cupsUser(),
215 else if (http->status == HTTP_UNAUTHORIZED)
216 http->digest_tries ++;
218 if (http->status == HTTP_UNAUTHORIZED && http->digest_tries >= 3)
220 DEBUG_printf(("1cupsDoAuthentication: Too many authentication tries (%d)",
221 http->digest_tries));
223 http->status = HTTP_AUTHORIZATION_CANCELED;
228 * Got a password; encode it for the server...
232 if (!_cups_strncasecmp(www_auth, "Negotiate", 9))
235 * Kerberos authentication...
238 if (_cupsSetNegotiateAuthString(http, method, resource))
240 http->status = HTTP_AUTHORIZATION_CANCELED;
245 #endif /* HAVE_GSSAPI */
246 if (!_cups_strncasecmp(www_auth, "Basic", 5))
249 * Basic authentication...
252 char encode[256]; /* Base64 buffer */
255 httpEncode64_2(encode, sizeof(encode), http->userpass,
256 (int)strlen(http->userpass));
257 httpSetAuthString(http, "Basic", encode);
259 else if (!_cups_strncasecmp(www_auth, "Digest", 6))
262 * Digest authentication...
265 char encode[33], /* MD5 buffer */
266 digest[1024]; /* Digest auth data */
269 httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "realm", realm);
270 httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "nonce", nonce);
272 httpMD5(cupsUser(), realm, strchr(http->userpass, ':') + 1, encode);
273 httpMD5Final(nonce, method, resource, encode);
274 snprintf(digest, sizeof(digest),
275 "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", "
276 "response=\"%s\"", cupsUser(), realm, nonce, resource, encode);
277 httpSetAuthString(http, "Digest", digest);
281 DEBUG_printf(("1cupsDoAuthentication: Unknown auth type: \"%s\"",
283 http->status = HTTP_AUTHORIZATION_CANCELED;
287 DEBUG_printf(("1cupsDoAuthentication: authstring=\"%s\"", http->authstring));
295 * '_cupsSetNegotiateAuthString()' - Set the Kerberos authentication string.
298 int /* O - 0 on success, -1 on error */
299 _cupsSetNegotiateAuthString(
300 http_t *http, /* I - Connection to server */
301 const char *method, /* I - Request method ("GET", "POST", "PUT") */
302 const char *resource) /* I - Resource path */
304 OM_uint32 minor_status, /* Minor status code */
305 major_status; /* Major status code */
306 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
315 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
319 if (gss_init_sec_context == NULL)
321 DEBUG_puts("1_cupsSetNegotiateAuthString: Weak-linked GSSAPI/Kerberos "
322 "framework is not present");
325 # endif /* __APPLE__ */
327 if (http->gssname == GSS_C_NO_NAME)
329 http->gssname = cups_gss_getname(http, _cupsGSSServiceName());
332 if (http->gssctx != GSS_C_NO_CONTEXT)
334 gss_delete_sec_context(&minor_status, &http->gssctx, GSS_C_NO_BUFFER);
335 http->gssctx = GSS_C_NO_CONTEXT;
338 major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
340 http->gssname, http->gssmech,
341 GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG,
343 GSS_C_NO_CHANNEL_BINDINGS,
344 GSS_C_NO_BUFFER, &http->gssmech,
345 &output_token, NULL, NULL);
347 #ifdef HAVE_GSS_ACQUIRE_CRED_EX_F
348 if (major_status == GSS_S_NO_CRED)
351 * Ask the user for credentials...
354 char prompt[1024], /* Prompt for user */
355 userbuf[256]; /* Kerberos username */
356 const char *username, /* Username string */
357 *password; /* Password string */
358 _cups_gss_acquire_t data; /* Callback data */
359 gss_auth_identity_desc identity; /* Kerberos user identity */
360 _cups_globals_t *cg = _cupsGlobals();
361 /* Per-thread global data */
363 if (!cg->lang_default)
364 cg->lang_default = cupsLangDefault();
366 snprintf(prompt, sizeof(prompt),
367 _cupsLangString(cg->lang_default, _("Password for %s on %s? ")),
368 cupsUser(), http->gsshost);
370 if ((password = cupsGetPassword2(prompt, http, method, resource)) == NULL)
374 * Try to acquire credentials...
377 username = cupsUser();
378 if (!strchr(username, '@'))
380 snprintf(userbuf, sizeof(userbuf), "%s@%s", username, http->gsshost);
384 identity.type = GSS_AUTH_IDENTITY_TYPE_1;
386 identity.username = (char *)username;
387 identity.realm = (char *)"";
388 identity.password = (char *)password;
389 identity.credentialsRef = NULL;
391 data.sem = dispatch_semaphore_create(0);
397 major_status = gss_acquire_cred_ex_f(NULL, GSS_C_NO_NAME, 0,
398 GSS_C_INDEFINITE, GSS_KRB5_MECHANISM,
399 GSS_C_INITIATE, &identity, &data,
402 if (major_status == GSS_S_COMPLETE)
404 dispatch_semaphore_wait(data.sem, DISPATCH_TIME_FOREVER);
405 major_status = data.major;
408 dispatch_release(data.sem);
410 if (major_status == GSS_S_COMPLETE)
412 OM_uint32 release_minor; /* Minor status from releasing creds */
414 major_status = gss_init_sec_context(&minor_status, data.creds,
416 http->gssname, http->gssmech,
417 GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG,
419 GSS_C_NO_CHANNEL_BINDINGS,
420 GSS_C_NO_BUFFER, &http->gssmech,
421 &output_token, NULL, NULL);
422 gss_release_cred(&release_minor, &data.creds);
426 #endif /* HAVE_GSS_ACQUIRED_CRED_EX_F */
428 if (GSS_ERROR(major_status))
430 cups_gss_printf(major_status, minor_status,
431 "_cupsSetNegotiateAuthString: Unable to initialize "
437 else if (major_status == GSS_S_CONTINUE_NEEDED)
438 cups_gss_printf(major_status, minor_status,
439 "_cupsSetNegotiateAuthString: Continuation needed!");
442 if (output_token.length > 0 && output_token.length <= 65536)
445 * Allocate the authorization string since Windows KDCs can have
446 * arbitrarily large credentials...
449 int authsize = 10 + /* "Negotiate " */
450 output_token.length * 4 / 3 + 1 + /* Base64 */
453 httpSetAuthString(http, NULL, NULL);
455 if ((http->authstring = malloc(authsize)) == NULL)
457 http->authstring = http->_authstring;
458 authsize = sizeof(http->_authstring);
461 strcpy(http->authstring, "Negotiate ");
462 httpEncode64_2(http->authstring + 10, authsize - 10, output_token.value,
463 output_token.length);
465 gss_release_buffer(&minor_status, &output_token);
469 DEBUG_printf(("1_cupsSetNegotiateAuthString: Kerberos credentials too "
470 "large - %d bytes!", (int)output_token.length));
471 gss_release_buffer(&minor_status, &output_token);
480 # ifdef HAVE_GSS_ACQUIRE_CRED_EX_F
482 * 'cups_gss_acquire()' - Kerberos credentials callback.
486 void *ctx, /* I - Caller context */
487 OM_uint32 major, /* I - Major error code */
488 gss_status_id_t status, /* I - Status (unused) */
489 gss_cred_id_t creds, /* I - Credentials (if any) */
490 gss_OID_set oids, /* I - Mechanism OIDs (unused) */
491 OM_uint32 time_rec) /* I - Timestamp (unused) */
493 uint32_t min; /* Minor error code */
494 _cups_gss_acquire_t *data; /* Callback data */
500 data = (_cups_gss_acquire_t *)ctx;
504 gss_release_oid_set(&min, &oids);
505 dispatch_semaphore_signal(data->sem);
507 # endif /* HAVE_GSS_ACQUIRE_CRED_EX_F */
511 * 'cups_gss_getname()' - Get CUPS service credentials for authentication.
514 static gss_name_t /* O - Server name */
516 http_t *http, /* I - Connection to server */
517 const char *service_name) /* I - Service name */
519 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
521 OM_uint32 major_status, /* Major status code */
522 minor_status; /* Minor status code */
523 gss_name_t server_name; /* Server name */
524 char buf[1024]; /* Name buffer */
527 DEBUG_printf(("7cups_gss_getname(http=%p, service_name=\"%s\")", http,
532 * Get the hostname...
535 if (!http->gsshost[0])
537 httpGetHostname(http, http->gsshost, sizeof(http->gsshost));
539 if (!strcmp(http->gsshost, "localhost"))
541 if (gethostname(http->gsshost, sizeof(http->gsshost)) < 0)
543 DEBUG_printf(("1cups_gss_getname: gethostname() failed: %s",
545 http->gsshost[0] = '\0';
549 if (!strchr(http->gsshost, '.'))
552 * The hostname is not a FQDN, so look it up...
555 struct hostent *host; /* Host entry to get FQDN */
557 if ((host = gethostbyname(http->gsshost)) != NULL && host->h_name)
560 * Use the resolved hostname...
563 strlcpy(http->gsshost, host->h_name, sizeof(http->gsshost));
567 DEBUG_printf(("1cups_gss_getname: gethostbyname(\"%s\") failed.",
569 http->gsshost[0] = '\0';
577 * Get a service name we can use for authentication purposes...
580 snprintf(buf, sizeof(buf), "%s@%s", service_name, http->gsshost);
582 DEBUG_printf(("8cups_gss_getname: Looking up \"%s\".", buf));
585 token.length = strlen(buf);
586 server_name = GSS_C_NO_NAME;
587 major_status = gss_import_name(&minor_status, &token,
588 GSS_C_NT_HOSTBASED_SERVICE,
591 if (GSS_ERROR(major_status))
593 cups_gss_printf(major_status, minor_status,
594 "cups_gss_getname: gss_import_name() failed");
598 return (server_name);
604 * 'cups_gss_printf()' - Show debug error messages from GSSAPI.
608 cups_gss_printf(OM_uint32 major_status,/* I - Major status code */
609 OM_uint32 minor_status,/* I - Minor status code */
610 const char *message) /* I - Prefix for error message */
612 OM_uint32 err_major_status, /* Major status code for display */
613 err_minor_status; /* Minor status code for display */
614 OM_uint32 msg_ctx; /* Message context */
615 gss_buffer_desc major_status_string = GSS_C_EMPTY_BUFFER,
616 /* Major status message */
617 minor_status_string = GSS_C_EMPTY_BUFFER;
618 /* Minor status message */
622 err_major_status = gss_display_status(&err_minor_status,
627 &major_status_string);
629 if (!GSS_ERROR(err_major_status))
630 gss_display_status(&err_minor_status, minor_status, GSS_C_MECH_CODE,
631 GSS_C_NULL_OID, &msg_ctx, &minor_status_string);
633 DEBUG_printf(("1%s: %s, %s", message, (char *)major_status_string.value,
634 (char *)minor_status_string.value));
636 gss_release_buffer(&err_minor_status, &major_status_string);
637 gss_release_buffer(&err_minor_status, &minor_status_string);
640 #endif /* HAVE_GSSAPI */
644 * 'cups_local_auth()' - Get the local authorization certificate if
645 * available/applicable.
648 static int /* O - 0 if available */
649 /* 1 if not available */
651 cups_local_auth(http_t *http) /* I - HTTP connection to server */
653 #if defined(WIN32) || defined(__EMX__)
655 * Currently WIN32 and OS-2 do not support the CUPS server...
660 int pid; /* Current process ID */
661 FILE *fp; /* Certificate file */
662 char trc[16], /* Try Root Certificate parameter */
663 filename[1024], /* Certificate filename */
664 certificate[33];/* Certificate string */
665 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
666 # if defined(HAVE_AUTHORIZATION_H)
667 OSStatus status; /* Status */
668 AuthorizationItem auth_right; /* Authorization right */
669 AuthorizationRights auth_rights; /* Authorization rights */
670 AuthorizationFlags auth_flags; /* Authorization flags */
671 AuthorizationExternalForm auth_extrn; /* Authorization ref external */
672 char auth_key[1024]; /* Buffer */
673 char buffer[1024]; /* Buffer */
674 # endif /* HAVE_AUTHORIZATION_H */
677 DEBUG_printf(("7cups_local_auth(http=%p) hostaddr=%s, hostname=\"%s\"",
678 http, httpAddrString(http->hostaddr, filename, sizeof(filename)), http->hostname));
681 * See if we are accessing localhost...
684 if (!httpAddrLocalhost(http->hostaddr) &&
685 _cups_strcasecmp(http->hostname, "localhost") != 0)
687 DEBUG_puts("8cups_local_auth: Not a local connection!");
691 # if defined(HAVE_AUTHORIZATION_H)
693 * Delete any previous authorization reference...
698 AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
699 http->auth_ref = NULL;
702 if (!getenv("GATEWAY_INTERFACE") &&
703 httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
704 auth_key, sizeof(auth_key)))
706 status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
707 kAuthorizationFlagDefaults, &http->auth_ref);
708 if (status != errAuthorizationSuccess)
710 DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d (%s)",
711 (int)status, cssmErrorString(status)));
715 auth_right.name = auth_key;
716 auth_right.valueLength = 0;
717 auth_right.value = NULL;
718 auth_right.flags = 0;
720 auth_rights.count = 1;
721 auth_rights.items = &auth_right;
723 auth_flags = kAuthorizationFlagDefaults |
724 kAuthorizationFlagPreAuthorize |
725 kAuthorizationFlagInteractionAllowed |
726 kAuthorizationFlagExtendRights;
728 status = AuthorizationCopyRights(http->auth_ref, &auth_rights,
729 kAuthorizationEmptyEnvironment,
731 if (status == errAuthorizationSuccess)
732 status = AuthorizationMakeExternalForm(http->auth_ref, &auth_extrn);
734 if (status == errAuthorizationSuccess)
737 * Set the authorization string and return...
740 httpEncode64_2(buffer, sizeof(buffer), (void *)&auth_extrn,
743 httpSetAuthString(http, "AuthRef", buffer);
745 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
749 else if (status == errAuthorizationCanceled)
752 DEBUG_printf(("9cups_local_auth: AuthorizationCopyRights() returned %d (%s)",
753 (int)status, cssmErrorString(status)));
756 * Fall through to try certificates...
759 # endif /* HAVE_AUTHORIZATION_H */
761 # if defined(SO_PEERCRED) && defined(AF_LOCAL)
763 * See if we can authenticate using the peer credentials provided over a
764 * domain socket; if so, specify "PeerCred username" as the authentication
770 strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9) &&
771 # endif /* HAVE_GSSAPI */
772 # ifdef HAVE_AUTHORIZATION_H
773 !httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
774 auth_key, sizeof(auth_key)) &&
775 # endif /* HAVE_AUTHORIZATION_H */
776 http->hostaddr->addr.sa_family == AF_LOCAL &&
777 !getenv("GATEWAY_INTERFACE")) /* Not via CGI programs... */
780 * Verify that the current cupsUser() matches the current UID...
783 struct passwd *pwd; /* Password information */
784 const char *username; /* Current username */
786 username = cupsUser();
788 if ((pwd = getpwnam(username)) != NULL && pwd->pw_uid == getuid())
790 httpSetAuthString(http, "PeerCred", username);
792 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
798 # endif /* SO_PEERCRED && AF_LOCAL */
801 * Try opening a certificate file for this PID. If that fails,
802 * try the root certificate...
806 snprintf(filename, sizeof(filename), "%s/certs/%d", cg->cups_statedir, pid);
807 if ((fp = fopen(filename, "r")) == NULL && pid > 0)
810 * No certificate for this PID; see if we can get the root certificate...
813 DEBUG_printf(("9cups_local_auth: Unable to open file %s: %s",
814 filename, strerror(errno)));
817 if (!strncmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
820 * Kerberos required, don't try the root certificate...
825 # endif /* HAVE_GSSAPI */
827 # ifdef HAVE_AUTHORIZATION_H
828 if (httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
829 auth_key, sizeof(auth_key)))
832 * Don't use the root certificate as a replacement for an authkey...
837 # endif /* HAVE_AUTHORIZATION_H */
838 if (!httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "trc", trc,
842 * Scheduler doesn't want us to use the root certificate...
848 snprintf(filename, sizeof(filename), "%s/certs/0", cg->cups_statedir);
849 fp = fopen(filename, "r");
855 * Read the certificate from the file...
858 fgets(certificate, sizeof(certificate), fp);
862 * Set the authorization string and return...
865 httpSetAuthString(http, "Local", certificate);
867 DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
874 #endif /* WIN32 || __EMX__ */
879 * End of "$Id: auth.c 10288 2012-02-15 19:21:37Z mike $".