]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/auth.c
Merge changes from CUPS 1.5svn-r9602.
[thirdparty/cups.git] / scheduler / auth.c
1 /*
2 * "$Id: auth.c 7830 2008-08-04 20:38:50Z mike $"
3 *
4 * Authorization routines for the CUPS scheduler.
5 *
6 * Copyright 2007-2011 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
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 * Contents:
19 *
20 * cupsdAddIPMask() - Add an IP address authorization mask.
21 * cupsdAddLocation() - Add a location for authorization.
22 * cupsdAddName() - Add a name to a location...
23 * cupsdAddNameMask() - Add a host or interface name authorization
24 * mask.
25 * cupsdAuthorize() - Validate any authorization credentials.
26 * cupsdCheckAccess() - Check whether the given address is allowed to
27 * access a location.
28 * cupsdCheckAuth() - Check authorization masks.
29 * cupsdCheckGroup() - Check for a user's group membership.
30 * cupsdCopyKrb5Creds() - Get a copy of the Kerberos credentials.
31 * cupsdCopyLocation() - Make a copy of a location...
32 * cupsdDeleteAllLocations() - Free all memory used for location
33 * authorization.
34 * cupsdFindBest() - Find the location entry that best matches the
35 * resource.
36 * cupsdFindLocation() - Find the named location.
37 * cupsdFreeLocation() - Free all memory used by a location.
38 * cupsdIsAuthorized() - Check to see if the user is authorized...
39 * cupsdNewLocation() - Create a new location for authorization.
40 * check_authref() - Check if an authorization services reference
41 * has the supplied right.
42 * compare_locations() - Compare two locations.
43 * copy_authmask() - Copy function for auth masks.
44 * cups_crypt() - Encrypt the password using the DES or MD5
45 * algorithms, as needed.
46 * free_authmask() - Free function for auth masks.
47 * get_md5_password() - Get an MD5 password.
48 * pam_func() - PAM conversation function.
49 * to64() - Base64-encode an integer value...
50 */
51
52 /*
53 * Include necessary headers...
54 */
55
56 #include "cupsd.h"
57 #include <grp.h>
58 #ifdef HAVE_SHADOW_H
59 # include <shadow.h>
60 #endif /* HAVE_SHADOW_H */
61 #ifdef HAVE_CRYPT_H
62 # include <crypt.h>
63 #endif /* HAVE_CRYPT_H */
64 #if HAVE_LIBPAM
65 # ifdef HAVE_PAM_PAM_APPL_H
66 # include <pam/pam_appl.h>
67 # else
68 # include <security/pam_appl.h>
69 # endif /* HAVE_PAM_PAM_APPL_H */
70 #endif /* HAVE_LIBPAM */
71 #ifdef HAVE_USERSEC_H
72 # include <usersec.h>
73 #endif /* HAVE_USERSEC_H */
74 #ifdef HAVE_MEMBERSHIP_H
75 # include <membership.h>
76 #endif /* HAVE_MEMBERSHIP_H */
77 #ifdef HAVE_AUTHORIZATION_H
78 # include <Security/AuthorizationTags.h>
79 # ifdef HAVE_SECBASEPRIV_H
80 # include <Security/SecBasePriv.h>
81 # else
82 extern const char *cssmErrorString(int error);
83 # endif /* HAVE_SECBASEPRIV_H */
84 #endif /* HAVE_AUTHORIZATION_H */
85 #ifdef HAVE_SYS_PARAM_H
86 # include <sys/param.h>
87 #endif /* HAVE_SYS_PARAM_H */
88 #ifdef HAVE_SYS_UCRED_H
89 # include <sys/ucred.h>
90 typedef struct xucred cupsd_ucred_t;
91 # define CUPSD_UCRED_UID(c) (c).cr_uid
92 #else
93 typedef struct ucred cupsd_ucred_t;
94 # define CUPSD_UCRED_UID(c) (c).uid
95 #endif /* HAVE_SYS_UCRED_H */
96 #ifdef HAVE_KRB5_IPC_CLIENT_SET_TARGET_UID
97 /* Not in public headers... */
98 extern void krb5_ipc_client_set_target_uid(uid_t);
99 extern void krb5_ipc_client_clear_target(void);
100 #endif /* HAVE_KRB5_IPC_CLIENT_SET_TARGET_UID */
101
102
103 /*
104 * Local functions...
105 */
106
107 #ifdef HAVE_AUTHORIZATION_H
108 static int check_authref(cupsd_client_t *con, const char *right);
109 #endif /* HAVE_AUTHORIZATION_H */
110 static int compare_locations(cupsd_location_t *a,
111 cupsd_location_t *b);
112 static cupsd_authmask_t *copy_authmask(cupsd_authmask_t *am, void *data);
113 #if !HAVE_LIBPAM && !defined(HAVE_USERSEC_H)
114 static char *cups_crypt(const char *pw, const char *salt);
115 #endif /* !HAVE_LIBPAM && !HAVE_USERSEC_H */
116 static void free_authmask(cupsd_authmask_t *am, void *data);
117 static char *get_md5_password(const char *username,
118 const char *group, char passwd[33]);
119 #if HAVE_LIBPAM
120 static int pam_func(int, const struct pam_message **,
121 struct pam_response **, void *);
122 #elif !defined(HAVE_USERSEC_H)
123 static void to64(char *s, unsigned long v, int n);
124 #endif /* HAVE_LIBPAM */
125
126
127 /*
128 * Local structures...
129 */
130
131 #if HAVE_LIBPAM
132 typedef struct cupsd_authdata_s /**** Authentication data ****/
133 {
134 char username[33], /* Username string */
135 password[33]; /* Password string */
136 } cupsd_authdata_t;
137 #endif /* HAVE_LIBPAM */
138
139
140 /*
141 * Local globals...
142 */
143
144 #if defined(__hpux) && HAVE_LIBPAM
145 static cupsd_authdata_t *auth_data; /* Current client being authenticated */
146 #endif /* __hpux && HAVE_LIBPAM */
147
148
149 /*
150 * 'cupsdAddIPMask()' - Add an IP address authorization mask.
151 */
152
153 int /* O - 1 on success, 0 on failure */
154 cupsdAddIPMask(
155 cups_array_t **masks, /* IO - Masks array (created as needed) */
156 const unsigned address[4], /* I - IP address */
157 const unsigned netmask[4]) /* I - IP netmask */
158 {
159 cupsd_authmask_t temp; /* New host/domain mask */
160
161
162 cupsdLogMessage(CUPSD_LOG_DEBUG2,
163 "cupsdAddIPMask(masks=%p(%p), address=%x:%x:%x:%x, "
164 "netmask=%x:%x:%x:%x)",
165 masks, *masks,
166 address[0], address[1], address[2], address[3],
167 netmask[0], netmask[1], netmask[2], netmask[3]);
168
169 temp.type = CUPSD_AUTH_IP;
170 memcpy(temp.mask.ip.address, address, sizeof(temp.mask.ip.address));
171 memcpy(temp.mask.ip.netmask, netmask, sizeof(temp.mask.ip.netmask));
172
173 /*
174 * Create the masks array as needed and add...
175 */
176
177 if (!*masks)
178 *masks = cupsArrayNew3(NULL, NULL, NULL, 0,
179 (cups_acopy_func_t)copy_authmask,
180 (cups_afree_func_t)free_authmask);
181
182 return (cupsArrayAdd(*masks, &temp));
183 }
184
185
186 /*
187 * 'cupsdAddLocation()' - Add a location for authorization.
188 */
189
190 void
191 cupsdAddLocation(cupsd_location_t *loc) /* I - Location to add */
192 {
193 /*
194 * Make sure the locations array is created...
195 */
196
197 if (!Locations)
198 Locations = cupsArrayNew3((cups_array_func_t)compare_locations, NULL,
199 (cups_ahash_func_t)NULL, 0,
200 (cups_acopy_func_t)NULL,
201 (cups_afree_func_t)cupsdFreeLocation);
202
203 if (Locations)
204 {
205 cupsArrayAdd(Locations, loc);
206
207 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAddLocation: Added location \"%s\"",
208 loc->location ? loc->location : "(null)");
209 }
210 }
211
212
213 /*
214 * 'cupsdAddName()' - Add a name to a location...
215 */
216
217 void
218 cupsdAddName(cupsd_location_t *loc, /* I - Location to add to */
219 char *name) /* I - Name to add */
220 {
221 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAddName(loc=%p, name=\"%s\")",
222 loc, name);
223
224 if (!loc->names)
225 loc->names = cupsArrayNew3(NULL, NULL, NULL, 0,
226 (cups_acopy_func_t)_cupsStrAlloc,
227 (cups_afree_func_t)_cupsStrFree);
228
229 if (!cupsArrayAdd(loc->names, name))
230 {
231 cupsdLogMessage(CUPSD_LOG_ERROR,
232 "Unable to duplicate name for location %s: %s",
233 loc->location ? loc->location : "nil", strerror(errno));
234 return;
235 }
236 }
237
238
239 /*
240 * 'cupsdAddNameMask()' - Add a host or interface name authorization mask.
241 */
242
243 int /* O - 1 on success, 0 on failure */
244 cupsdAddNameMask(cups_array_t **masks, /* IO - Masks array (created as needed) */
245 char *name) /* I - Host or interface name */
246 {
247 cupsd_authmask_t temp; /* New host/domain mask */
248 char ifname[32], /* Interface name */
249 *ifptr; /* Pointer to end of name */
250
251
252 cupsdLogMessage(CUPSD_LOG_DEBUG2,
253 "cupsdAddNameMask(masks=%p(%p), name=\"%s\")",
254 masks, *masks, name);
255
256 if (!strcasecmp(name, "@LOCAL"))
257 {
258 /*
259 * Deny *interface*...
260 */
261
262 temp.type = CUPSD_AUTH_INTERFACE;
263 temp.mask.name.name = (char *)"*";
264 }
265 else if (!strncasecmp(name, "@IF(", 4))
266 {
267 /*
268 * Deny *interface*...
269 */
270
271 strlcpy(ifname, name + 4, sizeof(ifname));
272
273 ifptr = ifname + strlen(ifname) - 1;
274
275 if (ifptr >= ifname && *ifptr == ')')
276 {
277 ifptr --;
278 *ifptr = '\0';
279 }
280
281 temp.type = CUPSD_AUTH_INTERFACE;
282 temp.mask.name.name = ifname;
283 }
284 else
285 {
286 /*
287 * Deny name...
288 */
289
290 if (*name == '*')
291 name ++;
292
293 temp.type = CUPSD_AUTH_NAME;
294 temp.mask.name.name = (char *)name;
295 }
296
297 /*
298 * Set the name length...
299 */
300
301 temp.mask.name.length = strlen(temp.mask.name.name);
302
303 /*
304 * Create the masks array as needed and add...
305 */
306
307 if (!*masks)
308 *masks = cupsArrayNew3(NULL, NULL, NULL, 0,
309 (cups_acopy_func_t)copy_authmask,
310 (cups_afree_func_t)free_authmask);
311
312 return (cupsArrayAdd(*masks, &temp));
313 }
314
315
316 /*
317 * 'cupsdAuthorize()' - Validate any authorization credentials.
318 */
319
320 void
321 cupsdAuthorize(cupsd_client_t *con) /* I - Client connection */
322 {
323 int type; /* Authentication type */
324 const char *authorization; /* Pointer into Authorization string */
325 char *ptr, /* Pointer into string */
326 username[256], /* Username string */
327 password[33]; /* Password string */
328 cupsd_cert_t *localuser; /* Certificate username */
329 char nonce[HTTP_MAX_VALUE], /* Nonce value from client */
330 md5[33], /* MD5 password */
331 basicmd5[33]; /* MD5 of Basic password */
332 static const char * const states[] = /* HTTP client states... */
333 {
334 "WAITING",
335 "OPTIONS",
336 "GET",
337 "GET",
338 "HEAD",
339 "POST",
340 "POST",
341 "POST",
342 "PUT",
343 "PUT",
344 "DELETE",
345 "TRACE",
346 "CLOSE",
347 "STATUS"
348 };
349
350
351 /*
352 * Locate the best matching location so we know what kind of
353 * authentication to expect...
354 */
355
356 con->best = cupsdFindBest(con->uri, con->http.state);
357 con->type = CUPSD_AUTH_NONE;
358
359 cupsdLogMessage(CUPSD_LOG_DEBUG2,
360 "cupsdAuthorize: con->uri=\"%s\", con->best=%p(%s)",
361 con->uri, con->best, con->best ? con->best->location : "");
362
363 if (con->best && con->best->type != CUPSD_AUTH_NONE)
364 {
365 if (con->best->type == CUPSD_AUTH_DEFAULT)
366 type = DefaultAuthType;
367 else
368 type = con->best->type;
369 }
370 else
371 type = DefaultAuthType;
372
373 /*
374 * Decode the Authorization string...
375 */
376
377 authorization = httpGetField(&con->http, HTTP_FIELD_AUTHORIZATION);
378
379 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAuthorize: Authorization=\"%s\"",
380 authorization);
381
382 username[0] = '\0';
383 password[0] = '\0';
384
385 #ifdef HAVE_AUTHORIZATION_H
386 if (con->authref)
387 {
388 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
389 con->authref = NULL;
390 }
391 #endif /* HAVE_AUTHORIZATION_H */
392
393 if (!*authorization)
394 {
395 /*
396 * No authorization data provided, return early...
397 */
398
399 cupsdLogMessage(CUPSD_LOG_DEBUG,
400 "cupsdAuthorize: No authentication data provided.");
401 return;
402 }
403 #ifdef HAVE_AUTHORIZATION_H
404 else if (!strncmp(authorization, "AuthRef ", 8) &&
405 !strcasecmp(con->http.hostname, "localhost"))
406 {
407 OSStatus status; /* Status */
408 int authlen; /* Auth string length */
409 AuthorizationItemSet *authinfo; /* Authorization item set */
410
411 /*
412 * Get the Authorization Services data...
413 */
414
415 authorization += 8;
416 while (isspace(*authorization & 255))
417 authorization ++;
418
419 authlen = sizeof(nonce);
420 httpDecode64_2(nonce, &authlen, authorization);
421
422 if (authlen != kAuthorizationExternalFormLength)
423 {
424 cupsdLogMessage(CUPSD_LOG_ERROR,
425 "External Authorization reference size is incorrect!");
426 return;
427 }
428
429 if ((status = AuthorizationCreateFromExternalForm(
430 (AuthorizationExternalForm *)nonce, &con->authref)) != 0)
431 {
432 cupsdLogMessage(CUPSD_LOG_ERROR,
433 "AuthorizationCreateFromExternalForm returned %d (%s)",
434 (int)status, cssmErrorString(status));
435 return;
436 }
437
438 username[0] = '\0';
439
440 if (!AuthorizationCopyInfo(con->authref, kAuthorizationEnvironmentUsername,
441 &authinfo))
442 {
443 if (authinfo->count == 1 && authinfo->items[0].value &&
444 authinfo->items[0].valueLength >= 2)
445 {
446 strlcpy(username, authinfo->items[0].value, sizeof(username));
447
448 cupsdLogMessage(CUPSD_LOG_DEBUG,
449 "cupsdAuthorize: Authorized as \"%s\" using AuthRef",
450 username);
451 }
452
453 AuthorizationFreeItemSet(authinfo);
454 }
455
456 if (!username[0])
457 {
458 /*
459 * No username in AuthRef, grab username using peer credentials...
460 */
461
462 struct passwd *pwd; /* Password entry for this user */
463 cupsd_ucred_t peercred; /* Peer credentials */
464 socklen_t peersize; /* Size of peer credentials */
465
466 peersize = sizeof(peercred);
467
468 if (getsockopt(con->http.fd, 0, LOCAL_PEERCRED, &peercred, &peersize))
469 {
470 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get peer credentials - %s",
471 strerror(errno));
472 return;
473 }
474
475 if ((pwd = getpwuid(CUPSD_UCRED_UID(peercred))) == NULL)
476 {
477 cupsdLogMessage(CUPSD_LOG_ERROR,
478 "Unable to find UID %d for peer credentials.",
479 (int)CUPSD_UCRED_UID(peercred));
480 return;
481 }
482
483 strlcpy(username, pwd->pw_name, sizeof(username));
484
485 cupsdLogMessage(CUPSD_LOG_DEBUG,
486 "cupsdAuthorize: Authorized as \"%s\" using "
487 "AuthRef + PeerCred", username);
488 }
489
490 con->type = CUPSD_AUTH_BASIC;
491 }
492 #endif /* HAVE_AUTHORIZATION_H */
493 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
494 else if (!strncmp(authorization, "PeerCred ", 9) &&
495 con->http.hostaddr->addr.sa_family == AF_LOCAL)
496 {
497 /*
498 * Use peer credentials from domain socket connection...
499 */
500
501 struct passwd *pwd; /* Password entry for this user */
502 cupsd_ucred_t peercred; /* Peer credentials */
503 socklen_t peersize; /* Size of peer credentials */
504 #ifdef HAVE_AUTHORIZATION_H
505 const char *name; /* Authorizing name */
506
507 for (name = (char *)cupsArrayFirst(con->best->names);
508 name;
509 name = (char *)cupsArrayNext(con->best->names))
510 if (!strncasecmp(name, "@AUTHKEY(", 9) || !strcasecmp(name, "@SYSTEM"))
511 {
512 cupsdLogMessage(CUPSD_LOG_ERROR,
513 "PeerCred authentication not allowed for resource.");
514 return;
515 }
516 #endif /* HAVE_AUTHORIZATION_H */
517
518 if ((pwd = getpwnam(authorization + 9)) == NULL)
519 {
520 cupsdLogMessage(CUPSD_LOG_ERROR, "User \"%s\" does not exist.",
521 authorization + 9);
522 return;
523 }
524
525 peersize = sizeof(peercred);
526
527 # ifdef __APPLE__
528 if (getsockopt(con->http.fd, 0, LOCAL_PEERCRED, &peercred, &peersize))
529 # else
530 if (getsockopt(con->http.fd, SOL_SOCKET, SO_PEERCRED, &peercred, &peersize))
531 # endif /* __APPLE__ */
532 {
533 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get peer credentials - %s",
534 strerror(errno));
535 return;
536 }
537
538 if (pwd->pw_uid != CUPSD_UCRED_UID(peercred))
539 {
540 cupsdLogMessage(CUPSD_LOG_ERROR,
541 "Invalid peer credentials for \"%s\" - got %d, "
542 "expected %d!", authorization + 9,
543 CUPSD_UCRED_UID(peercred), pwd->pw_uid);
544 # ifdef HAVE_SYS_UCRED_H
545 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAuthorize: cr_version=%d",
546 peercred.cr_version);
547 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAuthorize: cr_uid=%d",
548 peercred.cr_uid);
549 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAuthorize: cr_ngroups=%d",
550 peercred.cr_ngroups);
551 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAuthorize: cr_groups[0]=%d",
552 peercred.cr_groups[0]);
553 # endif /* HAVE_SYS_UCRED_H */
554 return;
555 }
556
557 strlcpy(username, authorization + 9, sizeof(username));
558
559 cupsdLogMessage(CUPSD_LOG_DEBUG,
560 "cupsdAuthorize: Authorized as %s using PeerCred",
561 username);
562
563 con->type = CUPSD_AUTH_BASIC;
564 }
565 #endif /* SO_PEERCRED && AF_LOCAL */
566 else if (!strncmp(authorization, "Local", 5) &&
567 !strcasecmp(con->http.hostname, "localhost"))
568 {
569 /*
570 * Get Local certificate authentication data...
571 */
572
573 authorization += 5;
574 while (isspace(*authorization & 255))
575 authorization ++;
576
577 if ((localuser = cupsdFindCert(authorization)) != NULL)
578 {
579 strlcpy(username, localuser->username, sizeof(username));
580
581 cupsdLogMessage(CUPSD_LOG_DEBUG,
582 "cupsdAuthorize: Authorized as %s using Local",
583 username);
584 }
585 else
586 {
587 cupsdLogMessage(CUPSD_LOG_ERROR,
588 "cupsdAuthorize: Local authentication certificate not "
589 "found!");
590 return;
591 }
592
593 #ifdef HAVE_GSSAPI
594 if (localuser->ccache)
595 con->type = CUPSD_AUTH_NEGOTIATE;
596 else
597 #endif /* HAVE_GSSAPI */
598 con->type = CUPSD_AUTH_BASIC;
599 }
600 else if (!strncmp(authorization, "Basic", 5))
601 {
602 /*
603 * Get the Basic authentication data...
604 */
605
606 int userlen; /* Username:password length */
607
608
609 authorization += 5;
610 while (isspace(*authorization & 255))
611 authorization ++;
612
613 userlen = sizeof(username);
614 httpDecode64_2(username, &userlen, authorization);
615
616 /*
617 * Pull the username and password out...
618 */
619
620 if ((ptr = strchr(username, ':')) == NULL)
621 {
622 cupsdLogMessage(CUPSD_LOG_ERROR,
623 "cupsdAuthorize: Missing Basic password!");
624 return;
625 }
626
627 *ptr++ = '\0';
628
629 if (!username[0])
630 {
631 /*
632 * Username must not be empty...
633 */
634
635 cupsdLogMessage(CUPSD_LOG_ERROR,
636 "cupsdAuthorize: Empty Basic username!");
637 return;
638 }
639
640 if (!*ptr)
641 {
642 /*
643 * Password must not be empty...
644 */
645
646 cupsdLogMessage(CUPSD_LOG_ERROR,
647 "cupsdAuthorize: Empty Basic password!");
648 return;
649 }
650
651 strlcpy(password, ptr, sizeof(password));
652
653 /*
654 * Validate the username and password...
655 */
656
657 switch (type)
658 {
659 default :
660 case CUPSD_AUTH_BASIC :
661 {
662 #if HAVE_LIBPAM
663 /*
664 * Only use PAM to do authentication. This supports MD5
665 * passwords, among other things...
666 */
667
668 pam_handle_t *pamh; /* PAM authentication handle */
669 int pamerr; /* PAM error code */
670 struct pam_conv pamdata;/* PAM conversation data */
671 cupsd_authdata_t data; /* Authentication data */
672
673
674 strlcpy(data.username, username, sizeof(data.username));
675 strlcpy(data.password, password, sizeof(data.password));
676
677 # if defined(__sun) || defined(__hpux)
678 pamdata.conv = (int (*)(int, struct pam_message **,
679 struct pam_response **,
680 void *))pam_func;
681 # else
682 pamdata.conv = pam_func;
683 # endif /* __sun || __hpux */
684 pamdata.appdata_ptr = &data;
685
686 # ifdef __hpux
687 /*
688 * Workaround for HP-UX bug in pam_unix; see pam_func() below for
689 * more info...
690 */
691
692 auth_data = &data;
693 # endif /* __hpux */
694
695 pamerr = pam_start("cups", username, &pamdata, &pamh);
696 if (pamerr != PAM_SUCCESS)
697 {
698 cupsdLogMessage(CUPSD_LOG_ERROR,
699 "cupsdAuthorize: pam_start() returned %d (%s)!",
700 pamerr, pam_strerror(pamh, pamerr));
701 return;
702 }
703
704 # ifdef HAVE_PAM_SET_ITEM
705 # ifdef PAM_RHOST
706 pamerr = pam_set_item(pamh, PAM_RHOST, con->http.hostname);
707 if (pamerr != PAM_SUCCESS)
708 cupsdLogMessage(CUPSD_LOG_WARN,
709 "cupsdAuthorize: pam_set_item(PAM_RHOST) "
710 "returned %d (%s)!", pamerr,
711 pam_strerror(pamh, pamerr));
712 # endif /* PAM_RHOST */
713
714 # ifdef PAM_TTY
715 pamerr = pam_set_item(pamh, PAM_TTY, "cups");
716 if (pamerr != PAM_SUCCESS)
717 cupsdLogMessage(CUPSD_LOG_WARN,
718 "cupsdAuthorize: pam_set_item(PAM_TTY) "
719 "returned %d (%s)!", pamerr,
720 pam_strerror(pamh, pamerr));
721 # endif /* PAM_TTY */
722 # endif /* HAVE_PAM_SET_ITEM */
723
724 pamerr = pam_authenticate(pamh, PAM_SILENT);
725 if (pamerr != PAM_SUCCESS)
726 {
727 cupsdLogMessage(CUPSD_LOG_ERROR,
728 "cupsdAuthorize: pam_authenticate() returned %d "
729 "(%s)!",
730 pamerr, pam_strerror(pamh, pamerr));
731 pam_end(pamh, 0);
732 return;
733 }
734
735 # ifdef HAVE_PAM_SETCRED
736 pamerr = pam_setcred(pamh, PAM_ESTABLISH_CRED | PAM_SILENT);
737 if (pamerr != PAM_SUCCESS)
738 cupsdLogMessage(CUPSD_LOG_WARN,
739 "cupsdAuthorize: pam_setcred() "
740 "returned %d (%s)!", pamerr,
741 pam_strerror(pamh, pamerr));
742 # endif /* HAVE_PAM_SETCRED */
743
744 pamerr = pam_acct_mgmt(pamh, PAM_SILENT);
745 if (pamerr != PAM_SUCCESS)
746 {
747 cupsdLogMessage(CUPSD_LOG_ERROR,
748 "cupsdAuthorize: pam_acct_mgmt() returned %d "
749 "(%s)!",
750 pamerr, pam_strerror(pamh, pamerr));
751 pam_end(pamh, 0);
752 return;
753 }
754
755 pam_end(pamh, PAM_SUCCESS);
756
757 #elif defined(HAVE_USERSEC_H)
758 /*
759 * Use AIX authentication interface...
760 */
761
762 char *authmsg; /* Authentication message */
763 int reenter; /* ??? */
764
765
766 cupsdLogMessage(CUPSD_LOG_DEBUG,
767 "cupsdAuthorize: AIX authenticate of username "
768 "\"%s\"", username);
769
770 reenter = 1;
771 if (authenticate(username, password, &reenter, &authmsg) != 0)
772 {
773 cupsdLogMessage(CUPSD_LOG_DEBUG,
774 "cupsdAuthorize: Unable to authenticate username "
775 "\"%s\": %s",
776 username, strerror(errno));
777 return;
778 }
779
780 #else
781 /*
782 * Use normal UNIX password file-based authentication...
783 */
784
785 char *pass; /* Encrypted password */
786 struct passwd *pw; /* User password data */
787 # ifdef HAVE_SHADOW_H
788 struct spwd *spw; /* Shadow password data */
789 # endif /* HAVE_SHADOW_H */
790
791
792 pw = getpwnam(username); /* Get the current password */
793 endpwent(); /* Close the password file */
794
795 if (!pw)
796 {
797 /*
798 * No such user...
799 */
800
801 cupsdLogMessage(CUPSD_LOG_ERROR,
802 "cupsdAuthorize: Unknown username \"%s\"!",
803 username);
804 return;
805 }
806
807 # ifdef HAVE_SHADOW_H
808 spw = getspnam(username);
809 endspent();
810
811 if (!spw && !strcmp(pw->pw_passwd, "x"))
812 {
813 /*
814 * Don't allow blank passwords!
815 */
816
817 cupsdLogMessage(CUPSD_LOG_ERROR,
818 "cupsdAuthorize: Username \"%s\" has no shadow "
819 "password!", username);
820 return;
821 }
822
823 if (spw && !spw->sp_pwdp[0] && !pw->pw_passwd[0])
824 # else
825 if (!pw->pw_passwd[0])
826 # endif /* HAVE_SHADOW_H */
827 {
828 /*
829 * Don't allow blank passwords!
830 */
831
832 cupsdLogMessage(CUPSD_LOG_ERROR,
833 "cupsdAuthorize: Username \"%s\" has no password!",
834 username);
835 return;
836 }
837
838 /*
839 * OK, the password isn't blank, so compare with what came from the
840 * client...
841 */
842
843 pass = cups_crypt(password, pw->pw_passwd);
844
845 cupsdLogMessage(CUPSD_LOG_DEBUG2,
846 "cupsdAuthorize: pw_passwd=\"%s\", crypt=\"%s\"",
847 pw->pw_passwd, pass);
848
849 if (!pass || strcmp(pw->pw_passwd, pass))
850 {
851 # ifdef HAVE_SHADOW_H
852 if (spw)
853 {
854 pass = cups_crypt(password, spw->sp_pwdp);
855
856 cupsdLogMessage(CUPSD_LOG_DEBUG2,
857 "cupsdAuthorize: sp_pwdp=\"%s\", crypt=\"%s\"",
858 spw->sp_pwdp, pass);
859
860 if (pass == NULL || strcmp(spw->sp_pwdp, pass))
861 {
862 cupsdLogMessage(CUPSD_LOG_ERROR,
863 "cupsdAuthorize: Authentication failed for "
864 "user \"%s\"!",
865 username);
866 return;
867 }
868 }
869 else
870 # endif /* HAVE_SHADOW_H */
871 {
872 cupsdLogMessage(CUPSD_LOG_ERROR,
873 "cupsdAuthorize: Authentication failed for "
874 "user \"%s\"!",
875 username);
876 return;
877 }
878 }
879 #endif /* HAVE_LIBPAM */
880 }
881
882 cupsdLogMessage(CUPSD_LOG_DEBUG,
883 "cupsdAuthorize: Authorized as %s using Basic",
884 username);
885 break;
886
887 case CUPSD_AUTH_BASICDIGEST :
888 /*
889 * Do Basic authentication with the Digest password file...
890 */
891
892 if (!get_md5_password(username, NULL, md5))
893 {
894 cupsdLogMessage(CUPSD_LOG_ERROR,
895 "cupsdAuthorize: Unknown MD5 username \"%s\"!",
896 username);
897 return;
898 }
899
900 httpMD5(username, "CUPS", password, basicmd5);
901
902 if (strcmp(md5, basicmd5))
903 {
904 cupsdLogMessage(CUPSD_LOG_ERROR,
905 "cupsdAuthorize: Authentication failed for \"%s\"!",
906 username);
907 return;
908 }
909
910 cupsdLogMessage(CUPSD_LOG_DEBUG,
911 "cupsdAuthorize: Authorized as %s using BasicDigest",
912 username);
913 break;
914 }
915
916 con->type = type;
917 }
918 else if (!strncmp(authorization, "Digest", 6))
919 {
920 /*
921 * Get the username, password, and nonce from the Digest attributes...
922 */
923
924 if (!httpGetSubField2(&(con->http), HTTP_FIELD_AUTHORIZATION, "username",
925 username, sizeof(username)) || !username[0])
926 {
927 /*
928 * Username must not be empty...
929 */
930
931 cupsdLogMessage(CUPSD_LOG_ERROR,
932 "cupsdAuthorize: Empty or missing Digest username!");
933 return;
934 }
935
936 if (!httpGetSubField2(&(con->http), HTTP_FIELD_AUTHORIZATION, "response",
937 password, sizeof(password)) || !password[0])
938 {
939 /*
940 * Password must not be empty...
941 */
942
943 cupsdLogMessage(CUPSD_LOG_ERROR,
944 "cupsdAuthorize: Empty or missing Digest password!");
945 return;
946 }
947
948 if (!httpGetSubField(&(con->http), HTTP_FIELD_AUTHORIZATION, "nonce",
949 nonce))
950 {
951 cupsdLogMessage(CUPSD_LOG_ERROR,
952 "cupsdAuthorize: No nonce value for Digest "
953 "authentication!");
954 return;
955 }
956
957 if (strcmp(con->http.hostname, nonce))
958 {
959 cupsdLogMessage(CUPSD_LOG_ERROR,
960 "cupsdAuthorize: Bad nonce value, expected \"%s\", "
961 "got \"%s\"!", con->http.hostname, nonce);
962 return;
963 }
964
965 /*
966 * Validate the username and password...
967 */
968
969 if (!get_md5_password(username, NULL, md5))
970 {
971 cupsdLogMessage(CUPSD_LOG_ERROR,
972 "cupsdAuthorize: Unknown MD5 username \"%s\"!",
973 username);
974 return;
975 }
976
977 httpMD5Final(nonce, states[con->http.state], con->uri, md5);
978
979 if (strcmp(md5, password))
980 {
981 cupsdLogMessage(CUPSD_LOG_ERROR,
982 "cupsdAuthorize: Authentication failed for \"%s\"!",
983 username);
984 return;
985 }
986
987 cupsdLogMessage(CUPSD_LOG_DEBUG,
988 "cupsdAuthorize: Authorized as %s using Digest",
989 username);
990
991 con->type = CUPSD_AUTH_DIGEST;
992 }
993 #ifdef HAVE_GSSAPI
994 # ifdef HAVE_KRB5_IPC_CLIENT_SET_TARGET_UID
995 else if (con->http.hostaddr->addr.sa_family == AF_LOCAL &&
996 !strncmp(authorization, "Negotiate", 9))
997 {
998 /*
999 * Pull the credentials directly from the user...
1000 */
1001
1002 krb5_error_code error; /* Kerberos error code */
1003 cupsd_ucred_t peercred; /* Peer credentials */
1004 socklen_t peersize; /* Size of peer credentials */
1005 krb5_ccache peerccache; /* Peer Kerberos credentials */
1006 krb5_principal peerprncpl; /* Peer's default principal */
1007 char *peername; /* Peer username */
1008
1009 peersize = sizeof(peercred);
1010
1011 # ifdef __APPLE__
1012 if (getsockopt(con->http.fd, 0, LOCAL_PEERCRED, &peercred, &peersize))
1013 # else
1014 if (getsockopt(con->http.fd, SOL_SOCKET, SO_PEERCRED, &peercred, &peersize))
1015 # endif /* __APPLE__ */
1016 {
1017 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get peer credentials - %s",
1018 strerror(errno));
1019 return;
1020 }
1021
1022 cupsdLogMessage(CUPSD_LOG_DEBUG,
1023 "cupsdAuthorize: Copying credentials for UID %d...",
1024 CUPSD_UCRED_UID(peercred));
1025
1026 if (!KerberosInitialized)
1027 {
1028 /*
1029 * Setup a Kerberos context for the scheduler to use...
1030 */
1031
1032 KerberosInitialized = 1;
1033
1034 if (krb5_init_context(&KerberosContext))
1035 {
1036 KerberosContext = NULL;
1037
1038 cupsdLogMessage(CUPSD_LOG_ERROR,
1039 "Unable to initialize Kerberos context");
1040 return;
1041 }
1042 }
1043
1044 krb5_ipc_client_set_target_uid(CUPSD_UCRED_UID(peercred));
1045
1046 if ((error = krb5_cc_default(KerberosContext, &peerccache)) != 0)
1047 {
1048 cupsdLogMessage(CUPSD_LOG_ERROR,
1049 "Unable to get credentials cache for UID %d (%d/%s)",
1050 (int)CUPSD_UCRED_UID(peercred), error, strerror(errno));
1051 krb5_ipc_client_clear_target();
1052 return;
1053 }
1054
1055 if ((error = krb5_cc_get_principal(KerberosContext, peerccache,
1056 &peerprncpl)) != 0)
1057 {
1058 cupsdLogMessage(CUPSD_LOG_ERROR,
1059 "Unable to get Kerberos principal for UID %d",
1060 (int)CUPSD_UCRED_UID(peercred));
1061 krb5_cc_close(KerberosContext, peerccache);
1062 krb5_ipc_client_clear_target();
1063 return;
1064 }
1065
1066 if ((error = krb5_unparse_name(KerberosContext, peerprncpl,
1067 &peername)) != 0)
1068 {
1069 cupsdLogMessage(CUPSD_LOG_ERROR,
1070 "Unable to get Kerberos name for UID %d",
1071 (int)CUPSD_UCRED_UID(peercred));
1072 krb5_cc_close(KerberosContext, peerccache);
1073 krb5_ipc_client_clear_target();
1074 return;
1075 }
1076
1077 strlcpy(username, peername, sizeof(username));
1078
1079 con->have_gss = 1;
1080 con->type = CUPSD_AUTH_NEGOTIATE;
1081
1082 free(peername);
1083
1084 cupsdLogMessage(CUPSD_LOG_DEBUG,
1085 "cupsdAuthorize: Authorized as %s using Negotiate",
1086 username);
1087
1088 krb5_cc_close(KerberosContext, peerccache);
1089 krb5_ipc_client_clear_target();
1090 }
1091 # endif /* HAVE_KRB5_IPC_CLIENT_SET_TARGET_UID */
1092 else if (!strncmp(authorization, "Negotiate", 9))
1093 {
1094 int len; /* Length of authorization string */
1095 gss_ctx_id_t context; /* Authorization context */
1096 OM_uint32 major_status, /* Major status code */
1097 minor_status; /* Minor status code */
1098 gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER,
1099 /* Input token from string */
1100 output_token = GSS_C_EMPTY_BUFFER;
1101 /* Output token for username */
1102 gss_name_t client_name; /* Client name */
1103
1104
1105 # ifdef __APPLE__
1106 /*
1107 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1108 * to use it...
1109 */
1110
1111 if (gss_init_sec_context == NULL)
1112 {
1113 cupsdLogMessage(CUPSD_LOG_WARN,
1114 "GSSAPI/Kerberos authentication failed because the "
1115 "Kerberos framework is not present.");
1116 return;
1117 }
1118 # endif /* __APPLE__ */
1119
1120 con->gss_output_token.length = 0;
1121
1122 /*
1123 * Find the start of the Kerberos input token...
1124 */
1125
1126 authorization += 9;
1127 while (isspace(*authorization & 255))
1128 authorization ++;
1129
1130 if (!*authorization)
1131 {
1132 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1133 "cupsdAuthorize: No authentication data specified.");
1134 return;
1135 }
1136
1137 /*
1138 * Decode the authorization string to get the input token...
1139 */
1140
1141 len = strlen(authorization);
1142 input_token.value = malloc(len);
1143 input_token.value = httpDecode64_2(input_token.value, &len,
1144 authorization);
1145 input_token.length = len;
1146
1147 /*
1148 * Accept the input token to get the authorization info...
1149 */
1150
1151 context = GSS_C_NO_CONTEXT;
1152 client_name = GSS_C_NO_NAME;
1153 major_status = gss_accept_sec_context(&minor_status,
1154 &context,
1155 GSS_C_NO_CREDENTIAL,
1156 &input_token,
1157 GSS_C_NO_CHANNEL_BINDINGS,
1158 &client_name,
1159 NULL,
1160 &con->gss_output_token,
1161 &con->gss_flags,
1162 NULL,
1163 &con->gss_creds);
1164
1165 if (GSS_ERROR(major_status))
1166 {
1167 cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status,
1168 "cupsdAuthorize: Error accepting GSSAPI security "
1169 "context");
1170
1171 if (context != GSS_C_NO_CONTEXT)
1172 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1173 return;
1174 }
1175
1176 con->have_gss = 1;
1177
1178 /*
1179 * Get the username associated with the client's credentials...
1180 */
1181
1182 if (!con->gss_creds)
1183 cupsdLogMessage(CUPSD_LOG_DEBUG,
1184 "cupsdAuthorize: No delegated credentials!");
1185
1186 if (major_status == GSS_S_CONTINUE_NEEDED)
1187 cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status,
1188 "cupsdAuthorize: Credentials not complete");
1189 else if (major_status == GSS_S_COMPLETE)
1190 {
1191 major_status = gss_display_name(&minor_status, client_name,
1192 &output_token, NULL);
1193
1194 if (GSS_ERROR(major_status))
1195 {
1196 cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status,
1197 "cupsdAuthorize: Error getting username");
1198 gss_release_cred(&minor_status, &con->gss_creds);
1199 gss_release_name(&minor_status, &client_name);
1200 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1201 return;
1202 }
1203
1204 strlcpy(username, output_token.value, sizeof(username));
1205
1206 cupsdLogMessage(CUPSD_LOG_DEBUG,
1207 "cupsdAuthorize: Authorized as %s using Negotiate",
1208 username);
1209
1210 gss_release_name(&minor_status, &client_name);
1211 gss_release_buffer(&minor_status, &output_token);
1212
1213 con->type = CUPSD_AUTH_NEGOTIATE;
1214 }
1215 else
1216 gss_release_cred(&minor_status, &con->gss_creds);
1217
1218 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1219 }
1220 #endif /* HAVE_GSSAPI */
1221 else
1222 {
1223 char scheme[256]; /* Auth scheme... */
1224
1225
1226 if (sscanf(authorization, "%255s", scheme) != 1)
1227 strcpy(scheme, "UNKNOWN");
1228
1229 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad authentication data \"%s ...\"",
1230 scheme);
1231 return;
1232 }
1233
1234 /*
1235 * If we get here, then we were able to validate the username and
1236 * password - copy the validated username and password to the client
1237 * data and return...
1238 */
1239
1240 strlcpy(con->username, username, sizeof(con->username));
1241 strlcpy(con->password, password, sizeof(con->password));
1242 }
1243
1244
1245 /*
1246 * 'cupsdCheckAccess()' - Check whether the given address is allowed to
1247 * access a location.
1248 */
1249
1250 int /* O - 1 if allowed, 0 otherwise */
1251 cupsdCheckAccess(
1252 unsigned ip[4], /* I - Client address */
1253 char *name, /* I - Client hostname */
1254 int namelen, /* I - Length of hostname */
1255 cupsd_location_t *loc) /* I - Location to check */
1256 {
1257 int allow; /* 1 if allowed, 0 otherwise */
1258
1259
1260 if (!strcasecmp(name, "localhost"))
1261 {
1262 /*
1263 * Access from localhost (127.0.0.1 or ::1) is always allowed...
1264 */
1265
1266 return (1);
1267 }
1268 else
1269 {
1270 /*
1271 * Do authorization checks on the domain/address...
1272 */
1273
1274 switch (loc->order_type)
1275 {
1276 default :
1277 allow = 0; /* anti-compiler-warning-code */
1278 break;
1279
1280 case CUPSD_AUTH_ALLOW : /* Order Deny,Allow */
1281 allow = 1;
1282
1283 if (cupsdCheckAuth(ip, name, namelen, loc->deny))
1284 allow = 0;
1285
1286 if (cupsdCheckAuth(ip, name, namelen, loc->allow))
1287 allow = 1;
1288 break;
1289
1290 case CUPSD_AUTH_DENY : /* Order Allow,Deny */
1291 allow = 0;
1292
1293 if (cupsdCheckAuth(ip, name, namelen, loc->allow))
1294 allow = 1;
1295
1296 if (cupsdCheckAuth(ip, name, namelen, loc->deny))
1297 allow = 0;
1298 break;
1299 }
1300 }
1301
1302 return (allow);
1303 }
1304
1305
1306 /*
1307 * 'cupsdCheckAuth()' - Check authorization masks.
1308 */
1309
1310 int /* O - 1 if mask matches, 0 otherwise */
1311 cupsdCheckAuth(unsigned ip[4], /* I - Client address */
1312 char *name, /* I - Client hostname */
1313 int name_len, /* I - Length of hostname */
1314 cups_array_t *masks) /* I - Masks */
1315 {
1316 int i; /* Looping var */
1317 cupsd_authmask_t *mask; /* Current mask */
1318 cupsd_netif_t *iface; /* Network interface */
1319 unsigned netip4; /* IPv4 network address */
1320 #ifdef AF_INET6
1321 unsigned netip6[4]; /* IPv6 network address */
1322 #endif /* AF_INET6 */
1323
1324
1325 for (mask = (cupsd_authmask_t *)cupsArrayFirst(masks);
1326 mask;
1327 mask = (cupsd_authmask_t *)cupsArrayNext(masks))
1328 {
1329 switch (mask->type)
1330 {
1331 case CUPSD_AUTH_INTERFACE :
1332 /*
1333 * Check for a match with a network interface...
1334 */
1335
1336 netip4 = htonl(ip[3]);
1337
1338 #ifdef AF_INET6
1339 netip6[0] = htonl(ip[0]);
1340 netip6[1] = htonl(ip[1]);
1341 netip6[2] = htonl(ip[2]);
1342 netip6[3] = htonl(ip[3]);
1343 #endif /* AF_INET6 */
1344
1345 if (!strcmp(mask->mask.name.name, "*"))
1346 {
1347 #ifdef __APPLE__
1348 /*
1349 * Allow Back-to-My-Mac addresses...
1350 */
1351
1352 if ((ip[0] & 0xff000000) == 0xfd000000)
1353 return (1);
1354 #endif /* __APPLE__ */
1355
1356 /*
1357 * Check against all local interfaces...
1358 */
1359
1360 cupsdNetIFUpdate();
1361
1362 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
1363 iface;
1364 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
1365 {
1366 /*
1367 * Only check local interfaces...
1368 */
1369
1370 if (!iface->is_local)
1371 continue;
1372
1373 if (iface->address.addr.sa_family == AF_INET)
1374 {
1375 /*
1376 * Check IPv4 address...
1377 */
1378
1379 if ((netip4 & iface->mask.ipv4.sin_addr.s_addr) ==
1380 (iface->address.ipv4.sin_addr.s_addr &
1381 iface->mask.ipv4.sin_addr.s_addr))
1382 return (1);
1383 }
1384 #ifdef AF_INET6
1385 else
1386 {
1387 /*
1388 * Check IPv6 address...
1389 */
1390
1391 for (i = 0; i < 4; i ++)
1392 if ((netip6[i] & iface->mask.ipv6.sin6_addr.s6_addr32[i]) !=
1393 (iface->address.ipv6.sin6_addr.s6_addr32[i] &
1394 iface->mask.ipv6.sin6_addr.s6_addr32[i]))
1395 break;
1396
1397 if (i == 4)
1398 return (1);
1399 }
1400 #endif /* AF_INET6 */
1401 }
1402 }
1403 else
1404 {
1405 /*
1406 * Check the named interface...
1407 */
1408
1409 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
1410 iface;
1411 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
1412 {
1413 if (strcmp(mask->mask.name.name, iface->name))
1414 continue;
1415
1416 if (iface->address.addr.sa_family == AF_INET)
1417 {
1418 /*
1419 * Check IPv4 address...
1420 */
1421
1422 if ((netip4 & iface->mask.ipv4.sin_addr.s_addr) ==
1423 (iface->address.ipv4.sin_addr.s_addr &
1424 iface->mask.ipv4.sin_addr.s_addr))
1425 return (1);
1426 }
1427 #ifdef AF_INET6
1428 else
1429 {
1430 /*
1431 * Check IPv6 address...
1432 */
1433
1434 for (i = 0; i < 4; i ++)
1435 if ((netip6[i] & iface->mask.ipv6.sin6_addr.s6_addr32[i]) !=
1436 (iface->address.ipv6.sin6_addr.s6_addr32[i] &
1437 iface->mask.ipv6.sin6_addr.s6_addr32[i]))
1438 break;
1439
1440 if (i == 4)
1441 return (1);
1442 }
1443 #endif /* AF_INET6 */
1444 }
1445 }
1446 break;
1447
1448 case CUPSD_AUTH_NAME :
1449 /*
1450 * Check for exact name match...
1451 */
1452
1453 if (!strcasecmp(name, mask->mask.name.name))
1454 return (1);
1455
1456 /*
1457 * Check for domain match...
1458 */
1459
1460 if (name_len >= mask->mask.name.length &&
1461 mask->mask.name.name[0] == '.' &&
1462 !strcasecmp(name + name_len - mask->mask.name.length,
1463 mask->mask.name.name))
1464 return (1);
1465 break;
1466
1467 case CUPSD_AUTH_IP :
1468 /*
1469 * Check for IP/network address match...
1470 */
1471
1472 for (i = 0; i < 4; i ++)
1473 if ((ip[i] & mask->mask.ip.netmask[i]) !=
1474 mask->mask.ip.address[i])
1475 break;
1476
1477 if (i == 4)
1478 return (1);
1479 break;
1480 }
1481 }
1482
1483 return (0);
1484 }
1485
1486
1487 /*
1488 * 'cupsdCheckGroup()' - Check for a user's group membership.
1489 */
1490
1491 int /* O - 1 if user is a member, 0 otherwise */
1492 cupsdCheckGroup(
1493 const char *username, /* I - User name */
1494 struct passwd *user, /* I - System user info */
1495 const char *groupname) /* I - Group name */
1496 {
1497 int i; /* Looping var */
1498 struct group *group; /* System group info */
1499 char junk[33]; /* MD5 password (not used) */
1500 #ifdef HAVE_MBR_UID_TO_UUID
1501 uuid_t useruuid, /* UUID for username */
1502 groupuuid; /* UUID for groupname */
1503 int is_member; /* True if user is a member of group */
1504 #endif /* HAVE_MBR_UID_TO_UUID */
1505
1506
1507 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1508 "cupsdCheckGroup(username=\"%s\", user=%p, groupname=\"%s\")",
1509 username, user, groupname);
1510
1511 /*
1512 * Validate input...
1513 */
1514
1515 if (!username || !groupname)
1516 return (0);
1517
1518 /*
1519 * Check to see if the user is a member of the named group...
1520 */
1521
1522 group = getgrnam(groupname);
1523 endgrent();
1524
1525 if (group != NULL)
1526 {
1527 /*
1528 * Group exists, check it...
1529 */
1530
1531 for (i = 0; group->gr_mem[i]; i ++)
1532 if (!strcasecmp(username, group->gr_mem[i]))
1533 return (1);
1534 }
1535
1536 /*
1537 * Group doesn't exist or user not in group list, check the group ID
1538 * against the user's group ID...
1539 */
1540
1541 if (user && group && group->gr_gid == user->pw_gid)
1542 return (1);
1543
1544 #ifdef HAVE_MBR_UID_TO_UUID
1545 /*
1546 * Check group membership through MacOS X membership API...
1547 */
1548
1549 if (user && !mbr_uid_to_uuid(user->pw_uid, useruuid))
1550 {
1551 if (group)
1552 {
1553 /*
1554 * Map group name to UUID and check membership...
1555 */
1556
1557 if (!mbr_gid_to_uuid(group->gr_gid, groupuuid))
1558 if (!mbr_check_membership(useruuid, groupuuid, &is_member))
1559 if (is_member)
1560 return (1);
1561 }
1562 else if (groupname[0] == '#')
1563 {
1564 /*
1565 * Use UUID directly and check for equality (user UUID) and
1566 * membership (group UUID)...
1567 */
1568
1569 if (!uuid_parse((char *)groupname + 1, groupuuid))
1570 {
1571 if (!uuid_compare(useruuid, groupuuid))
1572 return (1);
1573 else if (!mbr_check_membership(useruuid, groupuuid, &is_member))
1574 if (is_member)
1575 return (1);
1576 }
1577
1578 return (0);
1579 }
1580 }
1581 else if (groupname[0] == '#')
1582 return (0);
1583 #endif /* HAVE_MBR_UID_TO_UUID */
1584
1585 /*
1586 * Username not found, group not found, or user is not part of the
1587 * system group... Check for a user and group in the MD5 password
1588 * file...
1589 */
1590
1591 if (get_md5_password(username, groupname, junk) != NULL)
1592 return (1);
1593
1594 /*
1595 * If we get this far, then the user isn't part of the named group...
1596 */
1597
1598 return (0);
1599 }
1600
1601
1602 #ifdef HAVE_GSSAPI
1603 /*
1604 * 'cupsdCopyKrb5Creds()' - Get a copy of the Kerberos credentials.
1605 */
1606
1607 krb5_ccache /* O - Credentials or NULL */
1608 cupsdCopyKrb5Creds(cupsd_client_t *con) /* I - Client connection */
1609 {
1610 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
1611 cupsdLogMessage(CUPSD_LOG_INFO,
1612 "Sorry, your version of Kerberos does not support delegated "
1613 "credentials!");
1614 return (NULL);
1615
1616 # else
1617 krb5_ccache ccache = NULL; /* Credentials */
1618 krb5_error_code error; /* Kerberos error code */
1619 OM_uint32 major_status, /* Major status code */
1620 minor_status; /* Minor status code */
1621 krb5_principal principal; /* Kerberos principal */
1622
1623
1624 # ifdef __APPLE__
1625 /*
1626 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1627 * to use it...
1628 */
1629
1630 if (krb5_init_context == NULL)
1631 return (NULL);
1632 # endif /* __APPLE__ */
1633
1634 if (!KerberosInitialized)
1635 {
1636 /*
1637 * Setup a Kerberos context for the scheduler to use...
1638 */
1639
1640 KerberosInitialized = 1;
1641
1642 if (krb5_init_context(&KerberosContext))
1643 {
1644 KerberosContext = NULL;
1645
1646 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to initialize Kerberos context");
1647 return (NULL);
1648 }
1649 }
1650
1651 /*
1652 * We MUST create a file-based cache because memory-based caches are
1653 * only valid for the current process/address space.
1654 *
1655 * Due to various bugs/features in different versions of Kerberos, we
1656 * need either the krb5_cc_new_unique() function or Heimdal's version
1657 * of krb5_cc_gen_new() to create a new FILE: credential cache that
1658 * can be passed to the backend. These functions create a temporary
1659 * file (typically in /tmp) containing the cached credentials, which
1660 * are removed when we have successfully printed a job.
1661 */
1662
1663 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
1664 if ((error = krb5_cc_new_unique(KerberosContext, "FILE", NULL, &ccache)) != 0)
1665 # else /* HAVE_HEIMDAL */
1666 if ((error = krb5_cc_gen_new(KerberosContext, &krb5_fcc_ops, &ccache)) != 0)
1667 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
1668 {
1669 cupsdLogMessage(CUPSD_LOG_ERROR,
1670 "Unable to create new credentials cache (%d/%s)",
1671 error, strerror(errno));
1672 return (NULL);
1673 }
1674
1675 if ((error = krb5_parse_name(KerberosContext, con->username, &principal)) != 0)
1676 {
1677 cupsdLogMessage(CUPSD_LOG_ERROR,
1678 "Unable to parse kerberos username (%d/%s)", error,
1679 strerror(errno));
1680 krb5_cc_destroy(KerberosContext, ccache);
1681 return (NULL);
1682 }
1683
1684 if ((error = krb5_cc_initialize(KerberosContext, ccache, principal)))
1685 {
1686 cupsdLogMessage(CUPSD_LOG_ERROR,
1687 "Unable to initialize credentials cache (%d/%s)", error,
1688 strerror(errno));
1689 krb5_cc_destroy(KerberosContext, ccache);
1690 krb5_free_principal(KerberosContext, principal);
1691 return (NULL);
1692 }
1693
1694 krb5_free_principal(KerberosContext, principal);
1695
1696 /*
1697 * Copy the user's credentials to the new cache file...
1698 */
1699
1700 # ifdef HAVE_KRB5_IPC_CLIENT_SET_TARGET_UID
1701 if (con->http.hostaddr->addr.sa_family == AF_LOCAL &&
1702 !(con->gss_flags & GSS_C_DELEG_FLAG))
1703 {
1704 /*
1705 * Pull the credentials directly from the user...
1706 */
1707
1708 cupsd_ucred_t peercred; /* Peer credentials */
1709 socklen_t peersize; /* Size of peer credentials */
1710 krb5_ccache peerccache; /* Peer Kerberos credentials */
1711
1712 peersize = sizeof(peercred);
1713
1714 # ifdef __APPLE__
1715 if (getsockopt(con->http.fd, 0, LOCAL_PEERCRED, &peercred, &peersize))
1716 # else
1717 if (getsockopt(con->http.fd, SOL_SOCKET, SO_PEERCRED, &peercred, &peersize))
1718 # endif /* __APPLE__ */
1719 {
1720 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get peer credentials - %s",
1721 strerror(errno));
1722 krb5_cc_destroy(KerberosContext, ccache);
1723 return (NULL);
1724 }
1725
1726 cupsdLogMessage(CUPSD_LOG_DEBUG,
1727 "cupsdCopyKrb5Creds: Copying credentials for UID %d...",
1728 CUPSD_UCRED_UID(peercred));
1729
1730 krb5_ipc_client_set_target_uid(CUPSD_UCRED_UID(peercred));
1731
1732 if ((error = krb5_cc_default(KerberosContext, &peerccache)) != 0)
1733 {
1734 cupsdLogMessage(CUPSD_LOG_ERROR,
1735 "Unable to get credentials cache for UID %d (%d/%s)",
1736 (int)CUPSD_UCRED_UID(peercred), error, strerror(errno));
1737 krb5_cc_destroy(KerberosContext, ccache);
1738 return (NULL);
1739 }
1740
1741 error = krb5_cc_copy_creds(KerberosContext, peerccache, ccache);
1742 krb5_cc_close(KerberosContext, peerccache);
1743 krb5_ipc_client_clear_target();
1744
1745 if (error)
1746 {
1747 cupsdLogMessage(CUPSD_LOG_ERROR,
1748 "Unable to copy credentials cache for UID %d (%d/%s)",
1749 (int)CUPSD_UCRED_UID(peercred), error, strerror(errno));
1750 krb5_cc_destroy(KerberosContext, ccache);
1751 return (NULL);
1752 }
1753 }
1754 else
1755 # endif /* HAVE_KRB5_IPC_CLIENT_SET_TARGET_UID */
1756 {
1757 major_status = gss_krb5_copy_ccache(&minor_status, con->gss_creds, ccache);
1758
1759 if (GSS_ERROR(major_status))
1760 {
1761 cupsdLogGSSMessage(CUPSD_LOG_ERROR, major_status, minor_status,
1762 "Unable to copy client credentials cache");
1763 krb5_cc_destroy(KerberosContext, ccache);
1764 return (NULL);
1765 }
1766 }
1767
1768 return (ccache);
1769 # endif /* !HAVE_KRB5_CC_NEW_UNIQUE && !HAVE_HEIMDAL */
1770 }
1771 #endif /* HAVE_GSSAPI */
1772
1773
1774 /*
1775 * 'cupsdCopyLocation()' - Make a copy of a location...
1776 */
1777
1778 cupsd_location_t * /* O - New location */
1779 cupsdCopyLocation(
1780 cupsd_location_t *loc) /* I - Original location */
1781 {
1782 cupsd_location_t *temp; /* New location */
1783
1784
1785 /*
1786 * Make a copy of the original location...
1787 */
1788
1789 if ((temp = calloc(1, sizeof(cupsd_location_t))) == NULL)
1790 return (NULL);
1791
1792 /*
1793 * Copy the information from the original location to the new one.
1794 */
1795
1796 if (!loc)
1797 return (temp);
1798
1799 if (loc->location)
1800 temp->location = _cupsStrAlloc(loc->location);
1801
1802 temp->limit = loc->limit;
1803 temp->order_type = loc->order_type;
1804 temp->type = loc->type;
1805 temp->level = loc->level;
1806 temp->satisfy = loc->satisfy;
1807 temp->encryption = loc->encryption;
1808
1809 if (loc->names)
1810 {
1811 if ((temp->names = cupsArrayDup(loc->names)) == NULL)
1812 {
1813 cupsdLogMessage(CUPSD_LOG_ERROR,
1814 "Unable to allocate memory for %d names: %s",
1815 cupsArrayCount(loc->names), strerror(errno));
1816
1817 cupsdFreeLocation(temp);
1818 return (NULL);
1819 }
1820 }
1821
1822 if (loc->allow)
1823 {
1824 /*
1825 * Copy allow rules...
1826 */
1827
1828 if ((temp->allow = cupsArrayDup(loc->allow)) == NULL)
1829 {
1830 cupsdLogMessage(CUPSD_LOG_ERROR,
1831 "Unable to allocate memory for %d allow rules: %s",
1832 cupsArrayCount(loc->allow), strerror(errno));
1833 cupsdFreeLocation(temp);
1834 return (NULL);
1835 }
1836 }
1837
1838 if (loc->deny)
1839 {
1840 /*
1841 * Copy deny rules...
1842 */
1843
1844 if ((temp->deny = cupsArrayDup(loc->deny)) == NULL)
1845 {
1846 cupsdLogMessage(CUPSD_LOG_ERROR,
1847 "Unable to allocate memory for %d deny rules: %s",
1848 cupsArrayCount(loc->deny), strerror(errno));
1849 cupsdFreeLocation(temp);
1850 return (NULL);
1851 }
1852 }
1853
1854 return (temp);
1855 }
1856
1857
1858 /*
1859 * 'cupsdDeleteAllLocations()' - Free all memory used for location authorization.
1860 */
1861
1862 void
1863 cupsdDeleteAllLocations(void)
1864 {
1865 /*
1866 * Free the location array, which will free all of the locations...
1867 */
1868
1869 cupsArrayDelete(Locations);
1870 Locations = NULL;
1871 }
1872
1873
1874 /*
1875 * 'cupsdFindBest()' - Find the location entry that best matches the resource.
1876 */
1877
1878 cupsd_location_t * /* O - Location that matches */
1879 cupsdFindBest(const char *path, /* I - Resource path */
1880 http_state_t state) /* I - HTTP state/request */
1881 {
1882 char uri[HTTP_MAX_URI],
1883 /* URI in request... */
1884 *uriptr; /* Pointer into URI */
1885 cupsd_location_t *loc, /* Current location */
1886 *best; /* Best match for location so far */
1887 int bestlen; /* Length of best match */
1888 int limit; /* Limit field */
1889 static const int limits[] = /* Map http_status_t to CUPSD_AUTH_LIMIT_xyz */
1890 {
1891 CUPSD_AUTH_LIMIT_ALL,
1892 CUPSD_AUTH_LIMIT_OPTIONS,
1893 CUPSD_AUTH_LIMIT_GET,
1894 CUPSD_AUTH_LIMIT_GET,
1895 CUPSD_AUTH_LIMIT_HEAD,
1896 CUPSD_AUTH_LIMIT_POST,
1897 CUPSD_AUTH_LIMIT_POST,
1898 CUPSD_AUTH_LIMIT_POST,
1899 CUPSD_AUTH_LIMIT_PUT,
1900 CUPSD_AUTH_LIMIT_PUT,
1901 CUPSD_AUTH_LIMIT_DELETE,
1902 CUPSD_AUTH_LIMIT_TRACE,
1903 CUPSD_AUTH_LIMIT_ALL,
1904 CUPSD_AUTH_LIMIT_ALL
1905 };
1906
1907
1908 /*
1909 * First copy the connection URI to a local string so we have drop
1910 * any .ppd extension from the pathname in /printers or /classes
1911 * URIs...
1912 */
1913
1914 strlcpy(uri, path, sizeof(uri));
1915
1916 if (!strncmp(uri, "/printers/", 10) ||
1917 !strncmp(uri, "/classes/", 9))
1918 {
1919 /*
1920 * Check if the URI has .ppd on the end...
1921 */
1922
1923 uriptr = uri + strlen(uri) - 4; /* len > 4 if we get here... */
1924
1925 if (!strcmp(uriptr, ".ppd"))
1926 *uriptr = '\0';
1927 }
1928
1929 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFindBest: uri = \"%s\"...", uri);
1930
1931 /*
1932 * Loop through the list of locations to find a match...
1933 */
1934
1935 limit = limits[state];
1936 best = NULL;
1937 bestlen = 0;
1938
1939 for (loc = (cupsd_location_t *)cupsArrayFirst(Locations);
1940 loc;
1941 loc = (cupsd_location_t *)cupsArrayNext(Locations))
1942 {
1943 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFindBest: Location %s Limit %x",
1944 loc->location ? loc->location : "nil", loc->limit);
1945
1946 if (!strncmp(uri, "/printers/", 10) || !strncmp(uri, "/classes/", 9))
1947 {
1948 /*
1949 * Use case-insensitive comparison for queue names...
1950 */
1951
1952 if (loc->length > bestlen && loc->location &&
1953 !strncasecmp(uri, loc->location, loc->length) &&
1954 loc->location[0] == '/' &&
1955 (limit & loc->limit) != 0)
1956 {
1957 best = loc;
1958 bestlen = loc->length;
1959 }
1960 }
1961 else
1962 {
1963 /*
1964 * Use case-sensitive comparison for other URIs...
1965 */
1966
1967 if (loc->length > bestlen && loc->location &&
1968 !strncmp(uri, loc->location, loc->length) &&
1969 loc->location[0] == '/' &&
1970 (limit & loc->limit) != 0)
1971 {
1972 best = loc;
1973 bestlen = loc->length;
1974 }
1975 }
1976 }
1977
1978 /*
1979 * Return the match, if any...
1980 */
1981
1982 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFindBest: best = %s",
1983 best ? best->location : "NONE");
1984
1985 return (best);
1986 }
1987
1988
1989 /*
1990 * 'cupsdFindLocation()' - Find the named location.
1991 */
1992
1993 cupsd_location_t * /* O - Location that matches */
1994 cupsdFindLocation(const char *location) /* I - Connection */
1995 {
1996 cupsd_location_t key; /* Search key */
1997
1998
1999 key.location = (char *)location;
2000
2001 return ((cupsd_location_t *)cupsArrayFind(Locations, &key));
2002 }
2003
2004
2005 /*
2006 * 'cupsdFreeLocation()' - Free all memory used by a location.
2007 */
2008
2009 void
2010 cupsdFreeLocation(cupsd_location_t *loc)/* I - Location to free */
2011 {
2012 cupsArrayDelete(loc->names);
2013 cupsArrayDelete(loc->allow);
2014 cupsArrayDelete(loc->deny);
2015
2016 _cupsStrFree(loc->location);
2017 free(loc);
2018 }
2019
2020
2021 /*
2022 * 'cupsdIsAuthorized()' - Check to see if the user is authorized...
2023 */
2024
2025 http_status_t /* O - HTTP_OK if authorized or error code */
2026 cupsdIsAuthorized(cupsd_client_t *con, /* I - Connection */
2027 const char *owner)/* I - Owner of object */
2028 {
2029 int i, /* Looping vars */
2030 auth, /* Authorization status */
2031 type; /* Type of authentication */
2032 unsigned address[4]; /* Authorization address */
2033 cupsd_location_t *best; /* Best match for location so far */
2034 int hostlen; /* Length of hostname */
2035 char *name, /* Current username */
2036 username[256], /* Username to authorize */
2037 ownername[256], /* Owner name to authorize */
2038 *ptr; /* Pointer into username */
2039 struct passwd *pw; /* User password data */
2040 static const char * const levels[] = /* Auth levels */
2041 {
2042 "ANON",
2043 "USER",
2044 "GROUP"
2045 };
2046 static const char * const types[] = /* Auth types */
2047 {
2048 "None",
2049 "Basic",
2050 "Digest",
2051 "BasicDigest",
2052 "Negotiate"
2053 };
2054
2055
2056 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2057 "cupsdIsAuthorized: con->uri=\"%s\", con->best=%p(%s)",
2058 con->uri, con->best, con->best ? con->best->location ?
2059 con->best->location : "(null)" : "");
2060 if (owner)
2061 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2062 "cupsdIsAuthorized: owner=\"%s\"", owner);
2063
2064 /*
2065 * If there is no "best" authentication rule for this request, then
2066 * access is allowed from the local system and denied from other
2067 * addresses...
2068 */
2069
2070 if (!con->best)
2071 {
2072 if (!strcmp(con->http.hostname, "localhost") ||
2073 !strcmp(con->http.hostname, ServerName))
2074 return (HTTP_OK);
2075 else
2076 return (HTTP_FORBIDDEN);
2077 }
2078
2079 best = con->best;
2080
2081 if ((type = best->type) == CUPSD_AUTH_DEFAULT)
2082 type = DefaultAuthType;
2083
2084 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2085 "cupsdIsAuthorized: level=CUPSD_AUTH_%s, type=%s, "
2086 "satisfy=CUPSD_AUTH_SATISFY_%s, num_names=%d",
2087 levels[best->level], types[type],
2088 best->satisfy ? "ANY" : "ALL", cupsArrayCount(best->names));
2089
2090 if (best->limit == CUPSD_AUTH_LIMIT_IPP)
2091 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: op=%x(%s)",
2092 best->op, ippOpString(best->op));
2093
2094 /*
2095 * Check host/ip-based accesses...
2096 */
2097
2098 #ifdef AF_INET6
2099 if (con->http.hostaddr->addr.sa_family == AF_INET6)
2100 {
2101 /*
2102 * Copy IPv6 address...
2103 */
2104
2105 address[0] = ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[0]);
2106 address[1] = ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[1]);
2107 address[2] = ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2]);
2108 address[3] = ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[3]);
2109 }
2110 else
2111 #endif /* AF_INET6 */
2112 if (con->http.hostaddr->addr.sa_family == AF_INET)
2113 {
2114 /*
2115 * Copy IPv4 address...
2116 */
2117
2118 address[0] = 0;
2119 address[1] = 0;
2120 address[2] = 0;
2121 address[3] = ntohl(con->http.hostaddr->ipv4.sin_addr.s_addr);
2122 }
2123 else
2124 memset(address, 0, sizeof(address));
2125
2126 hostlen = strlen(con->http.hostname);
2127
2128 auth = cupsdCheckAccess(address, con->http.hostname, hostlen, best)
2129 ? CUPSD_AUTH_ALLOW : CUPSD_AUTH_DENY;
2130
2131 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: auth=CUPSD_AUTH_%s...",
2132 auth ? "DENY" : "ALLOW");
2133
2134 if (auth == CUPSD_AUTH_DENY && best->satisfy == CUPSD_AUTH_SATISFY_ALL)
2135 return (HTTP_FORBIDDEN);
2136
2137 #ifdef HAVE_SSL
2138 /*
2139 * See if encryption is required...
2140 */
2141
2142 if ((best->encryption >= HTTP_ENCRYPT_REQUIRED && !con->http.tls &&
2143 strcasecmp(con->http.hostname, "localhost") &&
2144 best->satisfy == CUPSD_AUTH_SATISFY_ALL) &&
2145 !(type == CUPSD_AUTH_NEGOTIATE ||
2146 (type == CUPSD_AUTH_NONE && DefaultAuthType == CUPSD_AUTH_NEGOTIATE)))
2147 {
2148 cupsdLogMessage(CUPSD_LOG_DEBUG,
2149 "cupsdIsAuthorized: Need upgrade to TLS...");
2150 return (HTTP_UPGRADE_REQUIRED);
2151 }
2152 #endif /* HAVE_SSL */
2153
2154 /*
2155 * Now see what access level is required...
2156 */
2157
2158 if (best->level == CUPSD_AUTH_ANON || /* Anonymous access - allow it */
2159 (type == CUPSD_AUTH_NONE && cupsArrayCount(best->names) == 0))
2160 return (HTTP_OK);
2161
2162 if (!con->username[0] && type == CUPSD_AUTH_NONE &&
2163 best->limit == CUPSD_AUTH_LIMIT_IPP)
2164 {
2165 /*
2166 * Check for unauthenticated username...
2167 */
2168
2169 ipp_attribute_t *attr; /* requesting-user-name attribute */
2170
2171
2172 attr = ippFindAttribute(con->request, "requesting-user-name", IPP_TAG_NAME);
2173 if (attr)
2174 {
2175 cupsdLogMessage(CUPSD_LOG_DEBUG,
2176 "cupsdIsAuthorized: requesting-user-name=\"%s\"",
2177 attr->values[0].string.text);
2178 strlcpy(username, attr->values[0].string.text, sizeof(username));
2179 }
2180 else if (best->satisfy == CUPSD_AUTH_SATISFY_ALL || auth == CUPSD_AUTH_DENY)
2181 return (HTTP_UNAUTHORIZED); /* Non-anonymous needs user/pass */
2182 else
2183 return (HTTP_OK); /* unless overridden with Satisfy */
2184 }
2185 else
2186 {
2187 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdIsAuthorized: username=\"%s\"",
2188 con->username);
2189
2190 #ifdef HAVE_AUTHORIZATION_H
2191 if (!con->username[0] && !con->authref)
2192 #else
2193 if (!con->username[0])
2194 #endif /* HAVE_AUTHORIZATION_H */
2195 {
2196 if (best->satisfy == CUPSD_AUTH_SATISFY_ALL || auth == CUPSD_AUTH_DENY)
2197 return (HTTP_UNAUTHORIZED); /* Non-anonymous needs user/pass */
2198 else
2199 return (HTTP_OK); /* unless overridden with Satisfy */
2200 }
2201
2202 if (con->type != type && type != CUPSD_AUTH_NONE &&
2203 (con->type != CUPSD_AUTH_BASIC || type != CUPSD_AUTH_BASICDIGEST))
2204 {
2205 cupsdLogMessage(CUPSD_LOG_ERROR, "Authorized using %s, expected %s!",
2206 types[con->type], types[type]);
2207
2208 return (HTTP_UNAUTHORIZED);
2209 }
2210
2211 strlcpy(username, con->username, sizeof(username));
2212 }
2213
2214 /*
2215 * OK, got a username. See if we need normal user access, or group
2216 * access... (root always matches)
2217 */
2218
2219 if (!strcmp(username, "root"))
2220 return (HTTP_OK);
2221
2222 /*
2223 * Strip any @domain or @KDC from the username and owner...
2224 */
2225
2226 if ((ptr = strchr(username, '@')) != NULL)
2227 *ptr = '\0';
2228
2229 if (owner)
2230 {
2231 strlcpy(ownername, owner, sizeof(ownername));
2232
2233 if ((ptr = strchr(ownername, '@')) != NULL)
2234 *ptr = '\0';
2235 }
2236 else
2237 ownername[0] = '\0';
2238
2239 /*
2240 * Get the user info...
2241 */
2242
2243 if (username[0])
2244 {
2245 pw = getpwnam(username);
2246 endpwent();
2247 }
2248 else
2249 pw = NULL;
2250
2251 if (best->level == CUPSD_AUTH_USER)
2252 {
2253 /*
2254 * If there are no names associated with this location, then
2255 * any valid user is OK...
2256 */
2257
2258 if (cupsArrayCount(best->names) == 0)
2259 return (HTTP_OK);
2260
2261 /*
2262 * Otherwise check the user list and return OK if this user is
2263 * allowed...
2264 */
2265
2266 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2267 "cupsdIsAuthorized: Checking user membership...");
2268
2269 #ifdef HAVE_AUTHORIZATION_H
2270 /*
2271 * If an authorization reference was supplied it must match a right name...
2272 */
2273
2274 if (con->authref)
2275 {
2276 for (name = (char *)cupsArrayFirst(best->names);
2277 name;
2278 name = (char *)cupsArrayNext(best->names))
2279 {
2280 if (!strncasecmp(name, "@AUTHKEY(", 9) && check_authref(con, name + 9))
2281 return (HTTP_OK);
2282 else if (!strcasecmp(name, "@SYSTEM") && SystemGroupAuthKey &&
2283 check_authref(con, SystemGroupAuthKey))
2284 return (HTTP_OK);
2285 }
2286
2287 return (HTTP_FORBIDDEN);
2288 }
2289 #endif /* HAVE_AUTHORIZATION_H */
2290
2291 for (name = (char *)cupsArrayFirst(best->names);
2292 name;
2293 name = (char *)cupsArrayNext(best->names))
2294 {
2295 if (!strcasecmp(name, "@OWNER") && owner &&
2296 !strcasecmp(username, ownername))
2297 return (HTTP_OK);
2298 else if (!strcasecmp(name, "@SYSTEM"))
2299 {
2300 for (i = 0; i < NumSystemGroups; i ++)
2301 if (cupsdCheckGroup(username, pw, SystemGroups[i]))
2302 return (HTTP_OK);
2303 }
2304 else if (name[0] == '@')
2305 {
2306 if (cupsdCheckGroup(username, pw, name + 1))
2307 return (HTTP_OK);
2308 }
2309 else if (!strcasecmp(username, name))
2310 return (HTTP_OK);
2311 }
2312
2313 return (HTTP_FORBIDDEN);
2314 }
2315
2316 /*
2317 * Check to see if this user is in any of the named groups...
2318 */
2319
2320 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2321 "cupsdIsAuthorized: Checking group membership...");
2322
2323 /*
2324 * Check to see if this user is in any of the named groups...
2325 */
2326
2327 for (name = (char *)cupsArrayFirst(best->names);
2328 name;
2329 name = (char *)cupsArrayNext(best->names))
2330 {
2331 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2332 "cupsdIsAuthorized: Checking group \"%s\" membership...",
2333 name);
2334
2335 if (!strcasecmp(name, "@SYSTEM"))
2336 {
2337 for (i = 0; i < NumSystemGroups; i ++)
2338 if (cupsdCheckGroup(username, pw, SystemGroups[i]))
2339 return (HTTP_OK);
2340 }
2341 else if (cupsdCheckGroup(username, pw, name))
2342 return (HTTP_OK);
2343 }
2344
2345 /*
2346 * The user isn't part of the specified group, so deny access...
2347 */
2348
2349 cupsdLogMessage(CUPSD_LOG_DEBUG,
2350 "cupsdIsAuthorized: User not in group(s)!");
2351
2352 return (HTTP_FORBIDDEN);
2353 }
2354
2355
2356 /*
2357 * 'cupsdNewLocation()' - Create a new location for authorization.
2358 *
2359 * Note: Still need to call cupsdAddLocation() to add it to the list of global
2360 * locations.
2361 */
2362
2363 cupsd_location_t * /* O - Pointer to new location record */
2364 cupsdNewLocation(const char *location) /* I - Location path */
2365 {
2366 cupsd_location_t *temp; /* New location */
2367
2368
2369 /*
2370 * Try to allocate memory for the new location.
2371 */
2372
2373 if ((temp = calloc(1, sizeof(cupsd_location_t))) == NULL)
2374 return (NULL);
2375
2376 /*
2377 * Initialize the record and copy the name over...
2378 */
2379
2380 if ((temp->location = _cupsStrAlloc(location)) == NULL)
2381 {
2382 free(temp);
2383 return (NULL);
2384 }
2385
2386 temp->length = strlen(temp->location);
2387
2388 /*
2389 * Return the new record...
2390 */
2391
2392 return (temp);
2393 }
2394
2395
2396 #ifdef HAVE_AUTHORIZATION_H
2397 /*
2398 * 'check_authref()' - Check if an authorization services reference has the
2399 * supplied right.
2400 */
2401
2402 static int /* O - 1 if right is valid, 0 otherwise */
2403 check_authref(cupsd_client_t *con, /* I - Connection */
2404 const char *right) /* I - Right name */
2405 {
2406 OSStatus status; /* OS Status */
2407 AuthorizationItem authright; /* Authorization right */
2408 AuthorizationRights authrights; /* Authorization rights */
2409 AuthorizationFlags authflags; /* Authorization flags */
2410
2411
2412 /*
2413 * Check to see if the user is allowed to perform the task...
2414 */
2415
2416 if (!con->authref)
2417 return (0);
2418
2419 authright.name = right;
2420 authright.valueLength = 0;
2421 authright.value = NULL;
2422 authright.flags = 0;
2423
2424 authrights.count = 1;
2425 authrights.items = &authright;
2426
2427 authflags = kAuthorizationFlagDefaults |
2428 kAuthorizationFlagExtendRights;
2429
2430 if ((status = AuthorizationCopyRights(con->authref, &authrights,
2431 kAuthorizationEmptyEnvironment,
2432 authflags, NULL)) != 0)
2433 {
2434 cupsdLogMessage(CUPSD_LOG_ERROR,
2435 "AuthorizationCopyRights(\"%s\") returned %d (%s)",
2436 authright.name, (int)status, cssmErrorString(status));
2437 return (0);
2438 }
2439
2440 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2441 "AuthorizationCopyRights(\"%s\") succeeded!",
2442 authright.name);
2443
2444 return (1);
2445 }
2446 #endif /* HAVE_AUTHORIZATION_H */
2447
2448
2449 /*
2450 * 'compare_locations()' - Compare two locations.
2451 */
2452
2453 static int /* O - Result of comparison */
2454 compare_locations(cupsd_location_t *a, /* I - First location */
2455 cupsd_location_t *b) /* I - Second location */
2456 {
2457 return (strcmp(b->location, a->location));
2458 }
2459
2460
2461 /*
2462 * 'copy_authmask()' - Copy function for auth masks.
2463 */
2464
2465 static cupsd_authmask_t * /* O - New auth mask */
2466 copy_authmask(cupsd_authmask_t *mask, /* I - Existing auth mask */
2467 void *data) /* I - User data (unused) */
2468 {
2469 cupsd_authmask_t *temp; /* New auth mask */
2470
2471
2472 (void)data;
2473
2474 if ((temp = malloc(sizeof(cupsd_authmask_t))) != NULL)
2475 {
2476 memcpy(temp, mask, sizeof(cupsd_authmask_t));
2477
2478 if (temp->type == CUPSD_AUTH_NAME || temp->type == CUPSD_AUTH_INTERFACE)
2479 {
2480 /*
2481 * Make a copy of the name...
2482 */
2483
2484 if ((temp->mask.name.name = _cupsStrAlloc(temp->mask.name.name)) == NULL)
2485 {
2486 /*
2487 * Failed to make copy...
2488 */
2489
2490 free(temp);
2491 temp = NULL;
2492 }
2493 }
2494 }
2495
2496 return (temp);
2497 }
2498
2499
2500 #if !HAVE_LIBPAM && !defined(HAVE_USERSEC_H)
2501 /*
2502 * 'cups_crypt()' - Encrypt the password using the DES or MD5 algorithms,
2503 * as needed.
2504 */
2505
2506 static char * /* O - Encrypted password */
2507 cups_crypt(const char *pw, /* I - Password string */
2508 const char *salt) /* I - Salt (key) string */
2509 {
2510 if (!strncmp(salt, "$1$", 3))
2511 {
2512 /*
2513 * Use MD5 passwords without the benefit of PAM; this is for
2514 * Slackware Linux, and the algorithm was taken from the
2515 * old shadow-19990827/lib/md5crypt.c source code... :(
2516 */
2517
2518 int i; /* Looping var */
2519 unsigned long n; /* Output number */
2520 int pwlen; /* Length of password string */
2521 const char *salt_end; /* End of "salt" data for MD5 */
2522 char *ptr; /* Pointer into result string */
2523 _cups_md5_state_t state; /* Primary MD5 state info */
2524 _cups_md5_state_t state2; /* Secondary MD5 state info */
2525 unsigned char digest[16]; /* MD5 digest result */
2526 static char result[120]; /* Final password string */
2527
2528
2529 /*
2530 * Get the salt data between dollar signs, e.g. $1$saltdata$md5.
2531 * Get a maximum of 8 characters of salt data after $1$...
2532 */
2533
2534 for (salt_end = salt + 3; *salt_end && (salt_end - salt) < 11; salt_end ++)
2535 if (*salt_end == '$')
2536 break;
2537
2538 /*
2539 * Compute the MD5 sum we need...
2540 */
2541
2542 pwlen = strlen(pw);
2543
2544 _cupsMD5Init(&state);
2545 _cupsMD5Append(&state, (unsigned char *)pw, pwlen);
2546 _cupsMD5Append(&state, (unsigned char *)salt, salt_end - salt);
2547
2548 _cupsMD5Init(&state2);
2549 _cupsMD5Append(&state2, (unsigned char *)pw, pwlen);
2550 _cupsMD5Append(&state2, (unsigned char *)salt + 3, salt_end - salt - 3);
2551 _cupsMD5Append(&state2, (unsigned char *)pw, pwlen);
2552 _cupsMD5Finish(&state2, digest);
2553
2554 for (i = pwlen; i > 0; i -= 16)
2555 _cupsMD5Append(&state, digest, i > 16 ? 16 : i);
2556
2557 for (i = pwlen; i > 0; i >>= 1)
2558 _cupsMD5Append(&state, (unsigned char *)((i & 1) ? "" : pw), 1);
2559
2560 _cupsMD5Finish(&state, digest);
2561
2562 for (i = 0; i < 1000; i ++)
2563 {
2564 _cupsMD5Init(&state);
2565
2566 if (i & 1)
2567 _cupsMD5Append(&state, (unsigned char *)pw, pwlen);
2568 else
2569 _cupsMD5Append(&state, digest, 16);
2570
2571 if (i % 3)
2572 _cupsMD5Append(&state, (unsigned char *)salt + 3, salt_end - salt - 3);
2573
2574 if (i % 7)
2575 _cupsMD5Append(&state, (unsigned char *)pw, pwlen);
2576
2577 if (i & 1)
2578 _cupsMD5Append(&state, digest, 16);
2579 else
2580 _cupsMD5Append(&state, (unsigned char *)pw, pwlen);
2581
2582 _cupsMD5Finish(&state, digest);
2583 }
2584
2585 /*
2586 * Copy the final sum to the result string and return...
2587 */
2588
2589 memcpy(result, salt, salt_end - salt);
2590 ptr = result + (salt_end - salt);
2591 *ptr++ = '$';
2592
2593 for (i = 0; i < 5; i ++, ptr += 4)
2594 {
2595 n = (((digest[i] << 8) | digest[i + 6]) << 8);
2596
2597 if (i < 4)
2598 n |= digest[i + 12];
2599 else
2600 n |= digest[5];
2601
2602 to64(ptr, n, 4);
2603 }
2604
2605 to64(ptr, digest[11], 2);
2606 ptr += 2;
2607 *ptr = '\0';
2608
2609 return (result);
2610 }
2611 else
2612 {
2613 /*
2614 * Use the standard crypt() function...
2615 */
2616
2617 return (crypt(pw, salt));
2618 }
2619 }
2620 #endif /* !HAVE_LIBPAM && !HAVE_USERSEC_H */
2621
2622
2623 /*
2624 * 'free_authmask()' - Free function for auth masks.
2625 */
2626
2627 static void
2628 free_authmask(cupsd_authmask_t *mask, /* I - Auth mask to free */
2629 void *data) /* I - User data (unused) */
2630 {
2631 (void)data;
2632
2633 if (mask->type == CUPSD_AUTH_NAME || mask->type == CUPSD_AUTH_INTERFACE)
2634 _cupsStrFree(mask->mask.name.name);
2635
2636 free(mask);
2637 }
2638
2639
2640 /*
2641 * 'get_md5_password()' - Get an MD5 password.
2642 */
2643
2644 static char * /* O - MD5 password string */
2645 get_md5_password(const char *username, /* I - Username */
2646 const char *group, /* I - Group */
2647 char passwd[33]) /* O - MD5 password string */
2648 {
2649 cups_file_t *fp; /* passwd.md5 file */
2650 char filename[1024], /* passwd.md5 filename */
2651 line[256], /* Line from file */
2652 tempuser[33], /* User from file */
2653 tempgroup[33]; /* Group from file */
2654
2655
2656 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2657 "get_md5_password(username=\"%s\", group=\"%s\", passwd=%p)",
2658 username, group ? group : "(null)", passwd);
2659
2660 snprintf(filename, sizeof(filename), "%s/passwd.md5", ServerRoot);
2661 if ((fp = cupsFileOpen(filename, "r")) == NULL)
2662 {
2663 if (errno != ENOENT)
2664 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open %s - %s", filename,
2665 strerror(errno));
2666
2667 return (NULL);
2668 }
2669
2670 while (cupsFileGets(fp, line, sizeof(line)) != NULL)
2671 {
2672 if (sscanf(line, "%32[^:]:%32[^:]:%32s", tempuser, tempgroup, passwd) != 3)
2673 {
2674 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad MD5 password line: %s", line);
2675 continue;
2676 }
2677
2678 if (!strcmp(username, tempuser) &&
2679 (group == NULL || !strcmp(group, tempgroup)))
2680 {
2681 /*
2682 * Found the password entry!
2683 */
2684
2685 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Found MD5 user %s, group %s...",
2686 username, tempgroup);
2687
2688 cupsFileClose(fp);
2689 return (passwd);
2690 }
2691 }
2692
2693 /*
2694 * Didn't find a password entry - return NULL!
2695 */
2696
2697 cupsFileClose(fp);
2698 return (NULL);
2699 }
2700
2701
2702 #if HAVE_LIBPAM
2703 /*
2704 * 'pam_func()' - PAM conversation function.
2705 */
2706
2707 static int /* O - Success or failure */
2708 pam_func(
2709 int num_msg, /* I - Number of messages */
2710 const struct pam_message **msg, /* I - Messages */
2711 struct pam_response **resp, /* O - Responses */
2712 void *appdata_ptr)
2713 /* I - Pointer to connection */
2714 {
2715 int i; /* Looping var */
2716 struct pam_response *replies; /* Replies */
2717 cupsd_authdata_t *data; /* Pointer to auth data */
2718
2719
2720 /*
2721 * Allocate memory for the responses...
2722 */
2723
2724 if ((replies = malloc(sizeof(struct pam_response) * num_msg)) == NULL)
2725 return (PAM_CONV_ERR);
2726
2727 /*
2728 * Answer all of the messages...
2729 */
2730
2731 DEBUG_printf(("pam_func: appdata_ptr = %p\n", appdata_ptr));
2732
2733 #ifdef __hpux
2734 /*
2735 * Apparently some versions of HP-UX 11 have a broken pam_unix security
2736 * module. This is a workaround...
2737 */
2738
2739 data = auth_data;
2740 (void)appdata_ptr;
2741 #else
2742 data = (cupsd_authdata_t *)appdata_ptr;
2743 #endif /* __hpux */
2744
2745 for (i = 0; i < num_msg; i ++)
2746 {
2747 DEBUG_printf(("pam_func: Message = \"%s\"\n", msg[i]->msg));
2748
2749 switch (msg[i]->msg_style)
2750 {
2751 case PAM_PROMPT_ECHO_ON:
2752 DEBUG_printf(("pam_func: PAM_PROMPT_ECHO_ON, returning \"%s\"...\n",
2753 data->username));
2754 replies[i].resp_retcode = PAM_SUCCESS;
2755 replies[i].resp = strdup(data->username);
2756 break;
2757
2758 case PAM_PROMPT_ECHO_OFF:
2759 DEBUG_printf(("pam_func: PAM_PROMPT_ECHO_OFF, returning \"%s\"...\n",
2760 data->password));
2761 replies[i].resp_retcode = PAM_SUCCESS;
2762 replies[i].resp = strdup(data->password);
2763 break;
2764
2765 case PAM_TEXT_INFO:
2766 DEBUG_puts("pam_func: PAM_TEXT_INFO...");
2767 replies[i].resp_retcode = PAM_SUCCESS;
2768 replies[i].resp = NULL;
2769 break;
2770
2771 case PAM_ERROR_MSG:
2772 DEBUG_puts("pam_func: PAM_ERROR_MSG...");
2773 replies[i].resp_retcode = PAM_SUCCESS;
2774 replies[i].resp = NULL;
2775 break;
2776
2777 default:
2778 DEBUG_printf(("pam_func: Unknown PAM message %d...\n",
2779 msg[i]->msg_style));
2780 free(replies);
2781 return (PAM_CONV_ERR);
2782 }
2783 }
2784
2785 /*
2786 * Return the responses back to PAM...
2787 */
2788
2789 *resp = replies;
2790
2791 return (PAM_SUCCESS);
2792 }
2793 #elif !defined(HAVE_USERSEC_H)
2794
2795
2796 /*
2797 * 'to64()' - Base64-encode an integer value...
2798 */
2799
2800 static void
2801 to64(char *s, /* O - Output string */
2802 unsigned long v, /* I - Value to encode */
2803 int n) /* I - Number of digits */
2804 {
2805 const char *itoa64 = "./0123456789"
2806 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2807 "abcdefghijklmnopqrstuvwxyz";
2808
2809
2810 for (; n > 0; n --, v >>= 6)
2811 *s++ = itoa64[v & 0x3f];
2812 }
2813 #endif /* HAVE_LIBPAM */
2814
2815
2816 /*
2817 * End of "$Id: auth.c 7830 2008-08-04 20:38:50Z mike $".
2818 */