]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/auth.c
Fix an issue with `PreserveJobHistory` and time values (Issue #5538)
[thirdparty/cups.git] / scheduler / auth.c
1 /*
2 * Authorization routines for the CUPS scheduler.
3 *
4 * Copyright © 2007-2019 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
6 *
7 * This file contains Kerberos support code, copyright 2006 by
8 * Jelmer Vernooij.
9 *
10 * Licensed under Apache License v2.0. See the file "LICENSE" for more
11 * information.
12 */
13
14 /*
15 * Include necessary headers...
16 */
17
18 #include "cupsd.h"
19 #include <grp.h>
20 #ifdef HAVE_SHADOW_H
21 # include <shadow.h>
22 #endif /* HAVE_SHADOW_H */
23 #ifdef HAVE_CRYPT_H
24 # include <crypt.h>
25 #endif /* HAVE_CRYPT_H */
26 #if HAVE_LIBPAM
27 # ifdef HAVE_PAM_PAM_APPL_H
28 # include <pam/pam_appl.h>
29 # else
30 # include <security/pam_appl.h>
31 # endif /* HAVE_PAM_PAM_APPL_H */
32 #endif /* HAVE_LIBPAM */
33 #ifdef HAVE_MEMBERSHIP_H
34 # include <membership.h>
35 #endif /* HAVE_MEMBERSHIP_H */
36 #ifdef HAVE_AUTHORIZATION_H
37 # include <Security/AuthorizationTags.h>
38 #endif /* HAVE_AUTHORIZATION_H */
39 #ifdef HAVE_SYS_PARAM_H
40 # include <sys/param.h>
41 #endif /* HAVE_SYS_PARAM_H */
42 #ifdef HAVE_SYS_UCRED_H
43 # include <sys/ucred.h>
44 typedef struct xucred cupsd_ucred_t;
45 # define CUPSD_UCRED_UID(c) (c).cr_uid
46 #else
47 # ifndef __OpenBSD__
48 typedef struct ucred cupsd_ucred_t;
49 # else
50 typedef struct sockpeercred cupsd_ucred_t;
51 # endif
52 # define CUPSD_UCRED_UID(c) (c).uid
53 #endif /* HAVE_SYS_UCRED_H */
54
55
56 /*
57 * Local functions...
58 */
59
60 #ifdef HAVE_AUTHORIZATION_H
61 static int check_authref(cupsd_client_t *con, const char *right);
62 #endif /* HAVE_AUTHORIZATION_H */
63 static int compare_locations(cupsd_location_t *a,
64 cupsd_location_t *b);
65 static cupsd_authmask_t *copy_authmask(cupsd_authmask_t *am, void *data);
66 static void free_authmask(cupsd_authmask_t *am, void *data);
67 #if HAVE_LIBPAM
68 static int pam_func(int, const struct pam_message **,
69 struct pam_response **, void *);
70 #else
71 static void to64(char *s, unsigned long v, int n);
72 #endif /* HAVE_LIBPAM */
73
74
75 /*
76 * Local structures...
77 */
78
79 #if HAVE_LIBPAM
80 typedef struct cupsd_authdata_s /**** Authentication data ****/
81 {
82 char username[HTTP_MAX_VALUE], /* Username string */
83 password[HTTP_MAX_VALUE]; /* Password string */
84 } cupsd_authdata_t;
85 #endif /* HAVE_LIBPAM */
86
87
88 /*
89 * 'cupsdAddIPMask()' - Add an IP address authorization mask.
90 */
91
92 int /* O - 1 on success, 0 on failure */
93 cupsdAddIPMask(
94 cups_array_t **masks, /* IO - Masks array (created as needed) */
95 const unsigned address[4], /* I - IP address */
96 const unsigned netmask[4]) /* I - IP netmask */
97 {
98 cupsd_authmask_t temp; /* New host/domain mask */
99
100
101 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAddIPMask(masks=%p(%p), address=%x:%x:%x:%x, netmask=%x:%x:%x:%x)", masks, *masks, address[0], address[1], address[2], address[3], netmask[0], netmask[1], netmask[2], netmask[3]);
102
103 temp.type = CUPSD_AUTH_IP;
104 memcpy(temp.mask.ip.address, address, sizeof(temp.mask.ip.address));
105 memcpy(temp.mask.ip.netmask, netmask, sizeof(temp.mask.ip.netmask));
106
107 /*
108 * Create the masks array as needed and add...
109 */
110
111 if (!*masks)
112 *masks = cupsArrayNew3(NULL, NULL, NULL, 0,
113 (cups_acopy_func_t)copy_authmask,
114 (cups_afree_func_t)free_authmask);
115
116 return (cupsArrayAdd(*masks, &temp));
117 }
118
119
120 /*
121 * 'cupsdAddLocation()' - Add a location for authorization.
122 */
123
124 void
125 cupsdAddLocation(cupsd_location_t *loc) /* I - Location to add */
126 {
127 /*
128 * Make sure the locations array is created...
129 */
130
131 if (!Locations)
132 Locations = cupsArrayNew3((cups_array_func_t)compare_locations, NULL,
133 (cups_ahash_func_t)NULL, 0,
134 (cups_acopy_func_t)NULL,
135 (cups_afree_func_t)cupsdFreeLocation);
136
137 if (Locations)
138 {
139 cupsArrayAdd(Locations, loc);
140
141 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAddLocation: Added location \"%s\"", loc->location ? loc->location : "(null)");
142 }
143 }
144
145
146 /*
147 * 'cupsdAddName()' - Add a name to a location...
148 */
149
150 void
151 cupsdAddName(cupsd_location_t *loc, /* I - Location to add to */
152 char *name) /* I - Name to add */
153 {
154 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAddName(loc=%p, name=\"%s\")", loc, name);
155
156 if (!loc->names)
157 loc->names = cupsArrayNew3(NULL, NULL, NULL, 0,
158 (cups_acopy_func_t)_cupsStrAlloc,
159 (cups_afree_func_t)_cupsStrFree);
160
161 if (!cupsArrayAdd(loc->names, name))
162 {
163 cupsdLogMessage(CUPSD_LOG_ERROR,
164 "Unable to duplicate name for location %s: %s",
165 loc->location ? loc->location : "nil", strerror(errno));
166 return;
167 }
168 }
169
170
171 /*
172 * 'cupsdAddNameMask()' - Add a host or interface name authorization mask.
173 */
174
175 int /* O - 1 on success, 0 on failure */
176 cupsdAddNameMask(cups_array_t **masks, /* IO - Masks array (created as needed) */
177 char *name) /* I - Host or interface name */
178 {
179 cupsd_authmask_t temp; /* New host/domain mask */
180 char ifname[32], /* Interface name */
181 *ifptr; /* Pointer to end of name */
182
183
184 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAddNameMask(masks=%p(%p), name=\"%s\")", masks, *masks, name);
185
186 if (!_cups_strcasecmp(name, "@LOCAL"))
187 {
188 /*
189 * Deny *interface*...
190 */
191
192 temp.type = CUPSD_AUTH_INTERFACE;
193 temp.mask.name.name = (char *)"*";
194 }
195 else if (!_cups_strncasecmp(name, "@IF(", 4))
196 {
197 /*
198 * Deny *interface*...
199 */
200
201 strlcpy(ifname, name + 4, sizeof(ifname));
202
203 ifptr = ifname + strlen(ifname) - 1;
204
205 if (ifptr >= ifname && *ifptr == ')')
206 {
207 ifptr --;
208 *ifptr = '\0';
209 }
210
211 temp.type = CUPSD_AUTH_INTERFACE;
212 temp.mask.name.name = ifname;
213 }
214 else
215 {
216 /*
217 * Deny name...
218 */
219
220 if (*name == '*')
221 name ++;
222
223 temp.type = CUPSD_AUTH_NAME;
224 temp.mask.name.name = (char *)name;
225 }
226
227 /*
228 * Set the name length...
229 */
230
231 temp.mask.name.length = strlen(temp.mask.name.name);
232
233 /*
234 * Create the masks array as needed and add...
235 */
236
237 if (!*masks)
238 *masks = cupsArrayNew3(NULL, NULL, NULL, 0,
239 (cups_acopy_func_t)copy_authmask,
240 (cups_afree_func_t)free_authmask);
241
242 return (cupsArrayAdd(*masks, &temp));
243 }
244
245
246 /*
247 * 'cupsdAuthorize()' - Validate any authorization credentials.
248 */
249
250 void
251 cupsdAuthorize(cupsd_client_t *con) /* I - Client connection */
252 {
253 int type; /* Authentication type */
254 const char *authorization; /* Pointer into Authorization string */
255 char *ptr, /* Pointer into string */
256 username[HTTP_MAX_VALUE],
257 /* Username string */
258 password[HTTP_MAX_VALUE];
259 /* Password string */
260 cupsd_cert_t *localuser; /* Certificate username */
261
262
263 /*
264 * Locate the best matching location so we know what kind of
265 * authentication to expect...
266 */
267
268 con->best = cupsdFindBest(con->uri, httpGetState(con->http));
269 con->type = CUPSD_AUTH_NONE;
270
271 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "con->uri=\"%s\", con->best=%p(%s)", con->uri, con->best, con->best ? con->best->location : "");
272
273 if (con->best && con->best->type != CUPSD_AUTH_NONE)
274 {
275 if (con->best->type == CUPSD_AUTH_DEFAULT)
276 type = cupsdDefaultAuthType();
277 else
278 type = con->best->type;
279 }
280 else
281 type = cupsdDefaultAuthType();
282
283 /*
284 * Decode the Authorization string...
285 */
286
287 authorization = httpGetField(con->http, HTTP_FIELD_AUTHORIZATION);
288
289 username[0] = '\0';
290 password[0] = '\0';
291
292 #ifdef HAVE_GSSAPI
293 con->gss_uid = 0;
294 #endif /* HAVE_GSSAPI */
295
296 #ifdef HAVE_AUTHORIZATION_H
297 if (con->authref)
298 {
299 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
300 con->authref = NULL;
301 }
302 #endif /* HAVE_AUTHORIZATION_H */
303
304 if (!*authorization)
305 {
306 /*
307 * No authorization data provided, return early...
308 */
309
310 cupsdLogClient(con, CUPSD_LOG_DEBUG, "No authentication data provided.");
311 return;
312 }
313 #ifdef HAVE_AUTHORIZATION_H
314 else if (!strncmp(authorization, "AuthRef ", 8) &&
315 httpAddrLocalhost(httpGetAddress(con->http)))
316 {
317 OSStatus status; /* Status */
318 char authdata[HTTP_MAX_VALUE];
319 /* Nonce value from client */
320 int authlen; /* Auth string length */
321 AuthorizationItemSet *authinfo; /* Authorization item set */
322
323 /*
324 * Get the Authorization Services data...
325 */
326
327 authorization += 8;
328 while (isspace(*authorization & 255))
329 authorization ++;
330
331 authlen = sizeof(authdata);
332 httpDecode64_2(authdata, &authlen, authorization);
333
334 if (authlen != kAuthorizationExternalFormLength)
335 {
336 cupsdLogClient(con, CUPSD_LOG_ERROR, "External Authorization reference size is incorrect.");
337 return;
338 }
339
340 if ((status = AuthorizationCreateFromExternalForm((AuthorizationExternalForm *)authdata, &con->authref)) != 0)
341 {
342 cupsdLogClient(con, CUPSD_LOG_ERROR, "AuthorizationCreateFromExternalForm returned %d", (int)status);
343 return;
344 }
345
346 username[0] = '\0';
347
348 if (!AuthorizationCopyInfo(con->authref, kAuthorizationEnvironmentUsername,
349 &authinfo))
350 {
351 if (authinfo->count == 1 && authinfo->items[0].value &&
352 authinfo->items[0].valueLength >= 2)
353 {
354 strlcpy(username, authinfo->items[0].value, sizeof(username));
355
356 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Authorized as \"%s\" using AuthRef.", username);
357 }
358
359 AuthorizationFreeItemSet(authinfo);
360 }
361
362 if (!username[0])
363 {
364 /*
365 * No username in AuthRef, grab username using peer credentials...
366 */
367
368 struct passwd *pwd; /* Password entry for this user */
369 cupsd_ucred_t peercred; /* Peer credentials */
370 socklen_t peersize; /* Size of peer credentials */
371
372 peersize = sizeof(peercred);
373
374 if (getsockopt(httpGetFd(con->http), 0, LOCAL_PEERCRED, &peercred, &peersize))
375 {
376 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get peer credentials - %s", strerror(errno));
377 return;
378 }
379
380 if ((pwd = getpwuid(CUPSD_UCRED_UID(peercred))) == NULL)
381 {
382 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to find UID %d for peer credentials.", (int)CUPSD_UCRED_UID(peercred));
383 return;
384 }
385
386 strlcpy(username, pwd->pw_name, sizeof(username));
387
388 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Authorized as \"%s\" using AuthRef + PeerCred.", username);
389 }
390
391 con->type = CUPSD_AUTH_BASIC;
392 }
393 #endif /* HAVE_AUTHORIZATION_H */
394 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
395 else if (!strncmp(authorization, "PeerCred ", 9) &&
396 con->http->hostaddr->addr.sa_family == AF_LOCAL && con->best)
397 {
398 /*
399 * Use peer credentials from domain socket connection...
400 */
401
402 struct passwd *pwd; /* Password entry for this user */
403 cupsd_ucred_t peercred; /* Peer credentials */
404 socklen_t peersize; /* Size of peer credentials */
405 #ifdef HAVE_AUTHORIZATION_H
406 const char *name; /* Authorizing name */
407 int no_peer = 0; /* Don't allow peer credentials? */
408
409 /*
410 * See if we should allow peer credentials...
411 */
412
413 for (name = (char *)cupsArrayFirst(con->best->names);
414 name;
415 name = (char *)cupsArrayNext(con->best->names))
416 {
417 if (!_cups_strncasecmp(name, "@AUTHKEY(", 9) ||
418 !_cups_strcasecmp(name, "@SYSTEM"))
419 {
420 /* Normally don't want peer credentials if we need an auth key... */
421 no_peer = 1;
422 }
423 else if (!_cups_strcasecmp(name, "@OWNER"))
424 {
425 /* but if @OWNER is present then we allow it... */
426 no_peer = 0;
427 break;
428 }
429 }
430
431 if (no_peer)
432 {
433 cupsdLogClient(con, CUPSD_LOG_ERROR, "PeerCred authentication not allowed for resource per AUTHKEY policy.");
434 return;
435 }
436 #endif /* HAVE_AUTHORIZATION_H */
437
438 if ((pwd = getpwnam(authorization + 9)) == NULL)
439 {
440 cupsdLogClient(con, CUPSD_LOG_ERROR, "User \"%s\" does not exist.", authorization + 9);
441 return;
442 }
443
444 peersize = sizeof(peercred);
445
446 # ifdef __APPLE__
447 if (getsockopt(httpGetFd(con->http), 0, LOCAL_PEERCRED, &peercred, &peersize))
448 # else
449 if (getsockopt(httpGetFd(con->http), SOL_SOCKET, SO_PEERCRED, &peercred, &peersize))
450 # endif /* __APPLE__ */
451 {
452 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get peer credentials - %s", strerror(errno));
453 return;
454 }
455
456 if (pwd->pw_uid != CUPSD_UCRED_UID(peercred))
457 {
458 cupsdLogClient(con, CUPSD_LOG_ERROR, "Invalid peer credentials for \"%s\" - got %d, expected %d.", authorization + 9, CUPSD_UCRED_UID(peercred), pwd->pw_uid);
459 # ifdef HAVE_SYS_UCRED_H
460 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cr_version=%d", peercred.cr_version);
461 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cr_uid=%d", peercred.cr_uid);
462 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cr_ngroups=%d", peercred.cr_ngroups);
463 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cr_groups[0]=%d", peercred.cr_groups[0]);
464 # endif /* HAVE_SYS_UCRED_H */
465 return;
466 }
467
468 strlcpy(username, authorization + 9, sizeof(username));
469
470 # ifdef HAVE_GSSAPI
471 con->gss_uid = CUPSD_UCRED_UID(peercred);
472 # endif /* HAVE_GSSAPI */
473
474 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Authorized as %s using PeerCred.", username);
475
476 con->type = CUPSD_AUTH_BASIC;
477 }
478 #endif /* SO_PEERCRED && AF_LOCAL */
479 else if (!strncmp(authorization, "Local", 5) &&
480 httpAddrLocalhost(httpGetAddress(con->http)))
481 {
482 /*
483 * Get Local certificate authentication data...
484 */
485
486 authorization += 5;
487 while (isspace(*authorization & 255))
488 authorization ++;
489
490 if ((localuser = cupsdFindCert(authorization)) == NULL)
491 {
492 cupsdLogClient(con, CUPSD_LOG_ERROR, "Local authentication certificate not found.");
493 return;
494 }
495
496 strlcpy(username, localuser->username, sizeof(username));
497 con->type = localuser->type;
498
499 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Authorized as %s using Local.", username);
500 }
501 else if (!strncmp(authorization, "Basic", 5))
502 {
503 /*
504 * Get the Basic authentication data...
505 */
506
507 int userlen; /* Username:password length */
508
509
510 authorization += 5;
511 while (isspace(*authorization & 255))
512 authorization ++;
513
514 userlen = sizeof(username);
515 httpDecode64_2(username, &userlen, authorization);
516
517 /*
518 * Pull the username and password out...
519 */
520
521 if ((ptr = strchr(username, ':')) == NULL)
522 {
523 cupsdLogClient(con, CUPSD_LOG_ERROR, "Missing Basic password.");
524 return;
525 }
526
527 *ptr++ = '\0';
528
529 if (!username[0])
530 {
531 /*
532 * Username must not be empty...
533 */
534
535 cupsdLogClient(con, CUPSD_LOG_ERROR, "Empty Basic username.");
536 return;
537 }
538
539 if (!*ptr)
540 {
541 /*
542 * Password must not be empty...
543 */
544
545 cupsdLogClient(con, CUPSD_LOG_ERROR, "Empty Basic password.");
546 return;
547 }
548
549 strlcpy(password, ptr, sizeof(password));
550
551 /*
552 * Validate the username and password...
553 */
554
555 switch (type)
556 {
557 default :
558 case CUPSD_AUTH_BASIC :
559 {
560 #if HAVE_LIBPAM
561 /*
562 * Only use PAM to do authentication. This supports MD5
563 * passwords, among other things...
564 */
565
566 pam_handle_t *pamh; /* PAM authentication handle */
567 int pamerr; /* PAM error code */
568 struct pam_conv pamdata;/* PAM conversation data */
569 cupsd_authdata_t data; /* Authentication data */
570
571
572 strlcpy(data.username, username, sizeof(data.username));
573 strlcpy(data.password, password, sizeof(data.password));
574
575 # ifdef __sun
576 pamdata.conv = (int (*)(int, struct pam_message **,
577 struct pam_response **,
578 void *))pam_func;
579 # else
580 pamdata.conv = pam_func;
581 # endif /* __sun */
582 pamdata.appdata_ptr = &data;
583
584 pamerr = pam_start("cups", username, &pamdata, &pamh);
585 if (pamerr != PAM_SUCCESS)
586 {
587 cupsdLogClient(con, CUPSD_LOG_ERROR, "pam_start() returned %d (%s)", pamerr, pam_strerror(pamh, pamerr));
588 return;
589 }
590
591 # ifdef HAVE_PAM_SET_ITEM
592 # ifdef PAM_RHOST
593 pamerr = pam_set_item(pamh, PAM_RHOST, con->http->hostname);
594 if (pamerr != PAM_SUCCESS)
595 cupsdLogClient(con, CUPSD_LOG_WARN, "pam_set_item(PAM_RHOST) returned %d (%s)", pamerr, pam_strerror(pamh, pamerr));
596 # endif /* PAM_RHOST */
597
598 # ifdef PAM_TTY
599 pamerr = pam_set_item(pamh, PAM_TTY, "cups");
600 if (pamerr != PAM_SUCCESS)
601 cupsdLogClient(con, CUPSD_LOG_WARN, "pam_set_item(PAM_TTY) returned %d (%s)", pamerr, pam_strerror(pamh, pamerr));
602 # endif /* PAM_TTY */
603 # endif /* HAVE_PAM_SET_ITEM */
604
605 pamerr = pam_authenticate(pamh, PAM_SILENT);
606 if (pamerr != PAM_SUCCESS)
607 {
608 cupsdLogClient(con, CUPSD_LOG_ERROR, "pam_authenticate() returned %d (%s)", pamerr, pam_strerror(pamh, pamerr));
609 pam_end(pamh, 0);
610 return;
611 }
612
613 # ifdef HAVE_PAM_SETCRED
614 pamerr = pam_setcred(pamh, PAM_ESTABLISH_CRED | PAM_SILENT);
615 if (pamerr != PAM_SUCCESS)
616 cupsdLogClient(con, CUPSD_LOG_WARN, "pam_setcred() returned %d (%s)", pamerr, pam_strerror(pamh, pamerr));
617 # endif /* HAVE_PAM_SETCRED */
618
619 pamerr = pam_acct_mgmt(pamh, PAM_SILENT);
620 if (pamerr != PAM_SUCCESS)
621 {
622 cupsdLogClient(con, CUPSD_LOG_ERROR, "pam_acct_mgmt() returned %d (%s)", pamerr, pam_strerror(pamh, pamerr));
623 pam_end(pamh, 0);
624 return;
625 }
626
627 pam_end(pamh, PAM_SUCCESS);
628
629 #else
630 /*
631 * Use normal UNIX password file-based authentication...
632 */
633
634 char *pass; /* Encrypted password */
635 struct passwd *pw; /* User password data */
636 # ifdef HAVE_SHADOW_H
637 struct spwd *spw; /* Shadow password data */
638 # endif /* HAVE_SHADOW_H */
639
640
641 pw = getpwnam(username); /* Get the current password */
642 endpwent(); /* Close the password file */
643
644 if (!pw)
645 {
646 /*
647 * No such user...
648 */
649
650 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unknown username \"%s\".", username);
651 return;
652 }
653
654 # ifdef HAVE_SHADOW_H
655 spw = getspnam(username);
656 endspent();
657
658 if (!spw && !strcmp(pw->pw_passwd, "x"))
659 {
660 /*
661 * Don't allow blank passwords!
662 */
663
664 cupsdLogClient(con, CUPSD_LOG_ERROR, "Username \"%s\" has no shadow password.", username);
665 return;
666 }
667
668 if (spw && !spw->sp_pwdp[0] && !pw->pw_passwd[0])
669 # else
670 if (!pw->pw_passwd[0])
671 # endif /* HAVE_SHADOW_H */
672 {
673 /*
674 * Don't allow blank passwords!
675 */
676
677 cupsdLogClient(con, CUPSD_LOG_ERROR, "Username \"%s\" has no password.", username);
678 return;
679 }
680
681 /*
682 * OK, the password isn't blank, so compare with what came from the
683 * client...
684 */
685
686 pass = crypt(password, pw->pw_passwd);
687
688 if (!pass || strcmp(pw->pw_passwd, pass))
689 {
690 # ifdef HAVE_SHADOW_H
691 if (spw)
692 {
693 pass = crypt(password, spw->sp_pwdp);
694
695 if (pass == NULL || strcmp(spw->sp_pwdp, pass))
696 {
697 cupsdLogClient(con, CUPSD_LOG_ERROR, "Authentication failed for user \"%s\".", username);
698 return;
699 }
700 }
701 else
702 # endif /* HAVE_SHADOW_H */
703 {
704 cupsdLogClient(con, CUPSD_LOG_ERROR, "Authentication failed for user \"%s\".", username);
705 return;
706 }
707 }
708 #endif /* HAVE_LIBPAM */
709 }
710
711 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Authorized as \"%s\" using Basic.", username);
712 break;
713 }
714
715 con->type = type;
716 }
717 #ifdef HAVE_GSSAPI
718 else if (!strncmp(authorization, "Negotiate", 9))
719 {
720 int len; /* Length of authorization string */
721 gss_ctx_id_t context; /* Authorization context */
722 OM_uint32 major_status, /* Major status code */
723 minor_status; /* Minor status code */
724 gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER,
725 /* Input token from string */
726 output_token = GSS_C_EMPTY_BUFFER;
727 /* Output token for username */
728 gss_name_t client_name; /* Client name */
729
730
731 # ifdef __APPLE__
732 /*
733 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
734 * to use it...
735 */
736
737 if (&gss_init_sec_context == NULL)
738 {
739 cupsdLogClient(con, CUPSD_LOG_WARN, "GSSAPI/Kerberos authentication failed because the Kerberos framework is not present.");
740 return;
741 }
742 # endif /* __APPLE__ */
743
744 /*
745 * Find the start of the Kerberos input token...
746 */
747
748 authorization += 9;
749 while (isspace(*authorization & 255))
750 authorization ++;
751
752 if (!*authorization)
753 {
754 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "No authentication data specified.");
755 return;
756 }
757
758 /*
759 * Decode the authorization string to get the input token...
760 */
761
762 len = (int)strlen(authorization);
763 input_token.value = malloc((size_t)len);
764 input_token.value = httpDecode64_2(input_token.value, &len,
765 authorization);
766 input_token.length = (size_t)len;
767
768 /*
769 * Accept the input token to get the authorization info...
770 */
771
772 context = GSS_C_NO_CONTEXT;
773 client_name = GSS_C_NO_NAME;
774 major_status = gss_accept_sec_context(&minor_status,
775 &context,
776 ServerCreds,
777 &input_token,
778 GSS_C_NO_CHANNEL_BINDINGS,
779 &client_name,
780 NULL,
781 &output_token,
782 NULL,
783 NULL,
784 NULL);
785
786 if (output_token.length > 0)
787 gss_release_buffer(&minor_status, &output_token);
788
789 if (GSS_ERROR(major_status))
790 {
791 cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status, "[Client %d] Error accepting GSSAPI security context.", con->number);
792
793 if (context != GSS_C_NO_CONTEXT)
794 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
795 return;
796 }
797
798 con->have_gss = 1;
799
800 /*
801 * Get the username associated with the client's credentials...
802 */
803
804 if (major_status == GSS_S_CONTINUE_NEEDED)
805 cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status, "[Client %d] Credentials not complete.", con->number);
806 else if (major_status == GSS_S_COMPLETE)
807 {
808 major_status = gss_display_name(&minor_status, client_name,
809 &output_token, NULL);
810
811 if (GSS_ERROR(major_status))
812 {
813 cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status, "[Client %d] Error getting username.", con->number);
814 gss_release_name(&minor_status, &client_name);
815 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
816 return;
817 }
818
819 strlcpy(username, output_token.value, sizeof(username));
820
821 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Authorized as \"%s\" using Negotiate.", username);
822
823 gss_release_name(&minor_status, &client_name);
824 gss_release_buffer(&minor_status, &output_token);
825
826 con->type = CUPSD_AUTH_NEGOTIATE;
827 }
828
829 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
830
831 # if defined(SO_PEERCRED) && defined(AF_LOCAL)
832 /*
833 * Get the client's UID if we are printing locally - that allows a backend
834 * to run as the correct user to get Kerberos credentials of its own.
835 */
836
837 if (httpAddrFamily(con->http->hostaddr) == AF_LOCAL)
838 {
839 cupsd_ucred_t peercred; /* Peer credentials */
840 socklen_t peersize; /* Size of peer credentials */
841
842 peersize = sizeof(peercred);
843
844 # ifdef __APPLE__
845 if (getsockopt(httpGetFd(con->http), 0, LOCAL_PEERCRED, &peercred, &peersize))
846 # else
847 if (getsockopt(httpGetFd(con->http), SOL_SOCKET, SO_PEERCRED, &peercred,
848 &peersize))
849 # endif /* __APPLE__ */
850 {
851 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get peer credentials - %s", strerror(errno));
852 }
853 else
854 {
855 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Using credentials for UID %d.", CUPSD_UCRED_UID(peercred));
856 con->gss_uid = CUPSD_UCRED_UID(peercred);
857 }
858 }
859 # endif /* SO_PEERCRED && AF_LOCAL */
860 }
861 #endif /* HAVE_GSSAPI */
862 else
863 {
864 char scheme[256]; /* Auth scheme... */
865
866
867 if (sscanf(authorization, "%255s", scheme) != 1)
868 strlcpy(scheme, "UNKNOWN", sizeof(scheme));
869
870 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad authentication data \"%s ...\".", scheme);
871 return;
872 }
873
874 /*
875 * If we get here, then we were able to validate the username and
876 * password - copy the validated username and password to the client
877 * data and return...
878 */
879
880 strlcpy(con->username, username, sizeof(con->username));
881 strlcpy(con->password, password, sizeof(con->password));
882 }
883
884
885 /*
886 * 'cupsdCheckAccess()' - Check whether the given address is allowed to
887 * access a location.
888 */
889
890 int /* O - 1 if allowed, 0 otherwise */
891 cupsdCheckAccess(
892 unsigned ip[4], /* I - Client address */
893 const char *name, /* I - Client hostname */
894 size_t namelen, /* I - Length of hostname */
895 cupsd_location_t *loc) /* I - Location to check */
896 {
897 int allow; /* 1 if allowed, 0 otherwise */
898
899
900 if (!_cups_strcasecmp(name, "localhost"))
901 {
902 /*
903 * Access from localhost (127.0.0.1 or ::1) is always allowed...
904 */
905
906 return (1);
907 }
908 else
909 {
910 /*
911 * Do authorization checks on the domain/address...
912 */
913
914 switch (loc->order_type)
915 {
916 default :
917 allow = 0; /* anti-compiler-warning-code */
918 break;
919
920 case CUPSD_AUTH_ALLOW : /* Order Deny,Allow */
921 allow = 1;
922
923 if (cupsdCheckAuth(ip, name, namelen, loc->deny))
924 allow = 0;
925
926 if (cupsdCheckAuth(ip, name, namelen, loc->allow))
927 allow = 1;
928 break;
929
930 case CUPSD_AUTH_DENY : /* Order Allow,Deny */
931 allow = 0;
932
933 if (cupsdCheckAuth(ip, name, namelen, loc->allow))
934 allow = 1;
935
936 if (cupsdCheckAuth(ip, name, namelen, loc->deny))
937 allow = 0;
938 break;
939 }
940 }
941
942 return (allow);
943 }
944
945
946 /*
947 * 'cupsdCheckAuth()' - Check authorization masks.
948 */
949
950 int /* O - 1 if mask matches, 0 otherwise */
951 cupsdCheckAuth(unsigned ip[4], /* I - Client address */
952 const char *name, /* I - Client hostname */
953 size_t name_len, /* I - Length of hostname */
954 cups_array_t *masks) /* I - Masks */
955 {
956 int i; /* Looping var */
957 cupsd_authmask_t *mask; /* Current mask */
958 cupsd_netif_t *iface; /* Network interface */
959 unsigned netip4; /* IPv4 network address */
960 #ifdef AF_INET6
961 unsigned netip6[4]; /* IPv6 network address */
962 #endif /* AF_INET6 */
963
964
965 for (mask = (cupsd_authmask_t *)cupsArrayFirst(masks);
966 mask;
967 mask = (cupsd_authmask_t *)cupsArrayNext(masks))
968 {
969 switch (mask->type)
970 {
971 case CUPSD_AUTH_INTERFACE :
972 /*
973 * Check for a match with a network interface...
974 */
975
976 netip4 = htonl(ip[3]);
977
978 #ifdef AF_INET6
979 netip6[0] = htonl(ip[0]);
980 netip6[1] = htonl(ip[1]);
981 netip6[2] = htonl(ip[2]);
982 netip6[3] = htonl(ip[3]);
983 #endif /* AF_INET6 */
984
985 cupsdNetIFUpdate();
986
987 if (!strcmp(mask->mask.name.name, "*"))
988 {
989 #ifdef __APPLE__
990 /*
991 * Allow Back-to-My-Mac addresses...
992 */
993
994 if ((ip[0] & 0xff000000) == 0xfd000000)
995 return (1);
996 #endif /* __APPLE__ */
997
998 /*
999 * Check against all local interfaces...
1000 */
1001
1002 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
1003 iface;
1004 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
1005 {
1006 /*
1007 * Only check local interfaces...
1008 */
1009
1010 if (!iface->is_local)
1011 continue;
1012
1013 if (iface->address.addr.sa_family == AF_INET)
1014 {
1015 /*
1016 * Check IPv4 address...
1017 */
1018
1019 if ((netip4 & iface->mask.ipv4.sin_addr.s_addr) ==
1020 (iface->address.ipv4.sin_addr.s_addr &
1021 iface->mask.ipv4.sin_addr.s_addr))
1022 return (1);
1023 }
1024 #ifdef AF_INET6
1025 else
1026 {
1027 /*
1028 * Check IPv6 address...
1029 */
1030
1031 for (i = 0; i < 4; i ++)
1032 if ((netip6[i] & iface->mask.ipv6.sin6_addr.s6_addr32[i]) !=
1033 (iface->address.ipv6.sin6_addr.s6_addr32[i] &
1034 iface->mask.ipv6.sin6_addr.s6_addr32[i]))
1035 break;
1036
1037 if (i == 4)
1038 return (1);
1039 }
1040 #endif /* AF_INET6 */
1041 }
1042 }
1043 else
1044 {
1045 /*
1046 * Check the named interface...
1047 */
1048
1049 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
1050 iface;
1051 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
1052 {
1053 if (strcmp(mask->mask.name.name, iface->name))
1054 continue;
1055
1056 if (iface->address.addr.sa_family == AF_INET)
1057 {
1058 /*
1059 * Check IPv4 address...
1060 */
1061
1062 if ((netip4 & iface->mask.ipv4.sin_addr.s_addr) ==
1063 (iface->address.ipv4.sin_addr.s_addr &
1064 iface->mask.ipv4.sin_addr.s_addr))
1065 return (1);
1066 }
1067 #ifdef AF_INET6
1068 else
1069 {
1070 /*
1071 * Check IPv6 address...
1072 */
1073
1074 for (i = 0; i < 4; i ++)
1075 if ((netip6[i] & iface->mask.ipv6.sin6_addr.s6_addr32[i]) !=
1076 (iface->address.ipv6.sin6_addr.s6_addr32[i] &
1077 iface->mask.ipv6.sin6_addr.s6_addr32[i]))
1078 break;
1079
1080 if (i == 4)
1081 return (1);
1082 }
1083 #endif /* AF_INET6 */
1084 }
1085 }
1086 break;
1087
1088 case CUPSD_AUTH_NAME :
1089 /*
1090 * Check for exact name match...
1091 */
1092
1093 if (!_cups_strcasecmp(name, mask->mask.name.name))
1094 return (1);
1095
1096 /*
1097 * Check for domain match...
1098 */
1099
1100 if (name_len >= mask->mask.name.length &&
1101 mask->mask.name.name[0] == '.' &&
1102 !_cups_strcasecmp(name + name_len - mask->mask.name.length,
1103 mask->mask.name.name))
1104 return (1);
1105 break;
1106
1107 case CUPSD_AUTH_IP :
1108 /*
1109 * Check for IP/network address match...
1110 */
1111
1112 for (i = 0; i < 4; i ++)
1113 if ((ip[i] & mask->mask.ip.netmask[i]) !=
1114 mask->mask.ip.address[i])
1115 break;
1116
1117 if (i == 4)
1118 return (1);
1119 break;
1120 }
1121 }
1122
1123 return (0);
1124 }
1125
1126
1127 /*
1128 * 'cupsdCheckGroup()' - Check for a user's group membership.
1129 */
1130
1131 int /* O - 1 if user is a member, 0 otherwise */
1132 cupsdCheckGroup(
1133 const char *username, /* I - User name */
1134 struct passwd *user, /* I - System user info */
1135 const char *groupname) /* I - Group name */
1136 {
1137 int i; /* Looping var */
1138 struct group *group; /* Group info */
1139 gid_t groupid; /* ID of named group */
1140 #ifdef HAVE_MBR_UID_TO_UUID
1141 uuid_t useruuid, /* UUID for username */
1142 groupuuid; /* UUID for groupname */
1143 int is_member; /* True if user is a member of group */
1144 #endif /* HAVE_MBR_UID_TO_UUID */
1145
1146
1147 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCheckGroup(username=\"%s\", user=%p, groupname=\"%s\")", username, user, groupname);
1148
1149 /*
1150 * Validate input...
1151 */
1152
1153 if (!username || !groupname)
1154 return (0);
1155
1156 /*
1157 * Check to see if the user is a member of the named group...
1158 */
1159
1160 group = getgrnam(groupname);
1161 endgrent();
1162
1163 if (group != NULL)
1164 {
1165 /*
1166 * Group exists, check it...
1167 */
1168
1169 groupid = group->gr_gid;
1170
1171 #ifdef HAVE_GETGROUPLIST
1172 if (user)
1173 {
1174 int ngroups; /* Number of groups */
1175 # ifdef __APPLE__
1176 int groups[2048]; /* Groups that user belongs to */
1177 # else
1178 gid_t groups[2048]; /* Groups that user belongs to */
1179 # endif /* __APPLE__ */
1180
1181 ngroups = (int)(sizeof(groups) / sizeof(groups[0]));
1182 # ifdef __APPLE__
1183 getgrouplist(username, (int)user->pw_gid, groups, &ngroups);
1184 # else
1185 getgrouplist(username, user->pw_gid, groups, &ngroups);
1186 #endif /* __APPLE__ */
1187
1188 for (i = 0; i < ngroups; i ++)
1189 if ((int)groupid == (int)groups[i])
1190 return (1);
1191 }
1192
1193 #else
1194 for (i = 0; group->gr_mem[i]; i ++)
1195 {
1196 if (!_cups_strcasecmp(username, group->gr_mem[i]))
1197 return (1);
1198 }
1199 #endif /* HAVE_GETGROUPLIST */
1200 }
1201 else
1202 groupid = (gid_t)-1;
1203
1204 /*
1205 * Group doesn't exist or user not in group list, check the group ID
1206 * against the user's group ID...
1207 */
1208
1209 if (user && groupid == user->pw_gid)
1210 return (1);
1211
1212 #ifdef HAVE_MBR_UID_TO_UUID
1213 /*
1214 * Check group membership through macOS membership API...
1215 */
1216
1217 if (user && !mbr_uid_to_uuid(user->pw_uid, useruuid))
1218 {
1219 if (groupid != (gid_t)-1)
1220 {
1221 /*
1222 * Map group name to UUID and check membership...
1223 */
1224
1225 if (!mbr_gid_to_uuid(groupid, groupuuid))
1226 if (!mbr_check_membership(useruuid, groupuuid, &is_member))
1227 if (is_member)
1228 return (1);
1229 }
1230 else if (groupname[0] == '#')
1231 {
1232 /*
1233 * Use UUID directly and check for equality (user UUID) and
1234 * membership (group UUID)...
1235 */
1236
1237 if (!uuid_parse((char *)groupname + 1, groupuuid))
1238 {
1239 if (!uuid_compare(useruuid, groupuuid))
1240 return (1);
1241 else if (!mbr_check_membership(useruuid, groupuuid, &is_member))
1242 if (is_member)
1243 return (1);
1244 }
1245
1246 return (0);
1247 }
1248 }
1249 else if (groupname[0] == '#')
1250 return (0);
1251 #endif /* HAVE_MBR_UID_TO_UUID */
1252
1253 /*
1254 * If we get this far, then the user isn't part of the named group...
1255 */
1256
1257 return (0);
1258 }
1259
1260
1261 /*
1262 * 'cupsdCopyLocation()' - Make a copy of a location...
1263 */
1264
1265 cupsd_location_t * /* O - New location */
1266 cupsdCopyLocation(
1267 cupsd_location_t *loc) /* I - Original location */
1268 {
1269 cupsd_location_t *temp; /* New location */
1270
1271
1272 /*
1273 * Make a copy of the original location...
1274 */
1275
1276 if ((temp = calloc(1, sizeof(cupsd_location_t))) == NULL)
1277 return (NULL);
1278
1279 /*
1280 * Copy the information from the original location to the new one.
1281 */
1282
1283 if (!loc)
1284 return (temp);
1285
1286 if (loc->location)
1287 temp->location = _cupsStrAlloc(loc->location);
1288
1289 temp->length = loc->length;
1290 temp->limit = loc->limit;
1291 temp->order_type = loc->order_type;
1292 temp->type = loc->type;
1293 temp->level = loc->level;
1294 temp->satisfy = loc->satisfy;
1295 temp->encryption = loc->encryption;
1296
1297 if (loc->names)
1298 {
1299 if ((temp->names = cupsArrayDup(loc->names)) == NULL)
1300 {
1301 cupsdLogMessage(CUPSD_LOG_ERROR,
1302 "Unable to allocate memory for %d names: %s",
1303 cupsArrayCount(loc->names), strerror(errno));
1304
1305 cupsdFreeLocation(temp);
1306 return (NULL);
1307 }
1308 }
1309
1310 if (loc->allow)
1311 {
1312 /*
1313 * Copy allow rules...
1314 */
1315
1316 if ((temp->allow = cupsArrayDup(loc->allow)) == NULL)
1317 {
1318 cupsdLogMessage(CUPSD_LOG_ERROR,
1319 "Unable to allocate memory for %d allow rules: %s",
1320 cupsArrayCount(loc->allow), strerror(errno));
1321 cupsdFreeLocation(temp);
1322 return (NULL);
1323 }
1324 }
1325
1326 if (loc->deny)
1327 {
1328 /*
1329 * Copy deny rules...
1330 */
1331
1332 if ((temp->deny = cupsArrayDup(loc->deny)) == NULL)
1333 {
1334 cupsdLogMessage(CUPSD_LOG_ERROR,
1335 "Unable to allocate memory for %d deny rules: %s",
1336 cupsArrayCount(loc->deny), strerror(errno));
1337 cupsdFreeLocation(temp);
1338 return (NULL);
1339 }
1340 }
1341
1342 return (temp);
1343 }
1344
1345
1346 /*
1347 * 'cupsdDeleteAllLocations()' - Free all memory used for location authorization.
1348 */
1349
1350 void
1351 cupsdDeleteAllLocations(void)
1352 {
1353 /*
1354 * Free the location array, which will free all of the locations...
1355 */
1356
1357 cupsArrayDelete(Locations);
1358 Locations = NULL;
1359 }
1360
1361
1362 /*
1363 * 'cupsdFindBest()' - Find the location entry that best matches the resource.
1364 */
1365
1366 cupsd_location_t * /* O - Location that matches */
1367 cupsdFindBest(const char *path, /* I - Resource path */
1368 http_state_t state) /* I - HTTP state/request */
1369 {
1370 char uri[HTTP_MAX_URI],
1371 /* URI in request... */
1372 *uriptr; /* Pointer into URI */
1373 cupsd_location_t *loc, /* Current location */
1374 *best; /* Best match for location so far */
1375 size_t bestlen; /* Length of best match */
1376 int limit; /* Limit field */
1377 static const int limits[] = /* Map http_status_t to CUPSD_AUTH_LIMIT_xyz */
1378 {
1379 CUPSD_AUTH_LIMIT_ALL,
1380 CUPSD_AUTH_LIMIT_OPTIONS,
1381 CUPSD_AUTH_LIMIT_GET,
1382 CUPSD_AUTH_LIMIT_GET,
1383 CUPSD_AUTH_LIMIT_HEAD,
1384 CUPSD_AUTH_LIMIT_POST,
1385 CUPSD_AUTH_LIMIT_POST,
1386 CUPSD_AUTH_LIMIT_POST,
1387 CUPSD_AUTH_LIMIT_PUT,
1388 CUPSD_AUTH_LIMIT_PUT,
1389 CUPSD_AUTH_LIMIT_DELETE,
1390 CUPSD_AUTH_LIMIT_TRACE,
1391 CUPSD_AUTH_LIMIT_ALL,
1392 CUPSD_AUTH_LIMIT_ALL,
1393 CUPSD_AUTH_LIMIT_ALL,
1394 CUPSD_AUTH_LIMIT_ALL
1395 };
1396
1397
1398 /*
1399 * First copy the connection URI to a local string so we have drop
1400 * any .ppd extension from the pathname in /printers or /classes
1401 * URIs...
1402 */
1403
1404 strlcpy(uri, path, sizeof(uri));
1405
1406 if ((uriptr = strchr(uri, '?')) != NULL)
1407 *uriptr = '\0'; /* Drop trailing query string */
1408
1409 if ((uriptr = uri + strlen(uri) - 1) > uri && *uriptr == '/')
1410 *uriptr = '\0'; /* Remove trailing '/' */
1411
1412 if (!strncmp(uri, "/printers/", 10) ||
1413 !strncmp(uri, "/classes/", 9))
1414 {
1415 /*
1416 * Check if the URI has .ppd on the end...
1417 */
1418
1419 uriptr = uri + strlen(uri) - 4; /* len > 4 if we get here... */
1420
1421 if (!strcmp(uriptr, ".ppd"))
1422 *uriptr = '\0';
1423 }
1424
1425 /*
1426 * Loop through the list of locations to find a match...
1427 */
1428
1429 limit = limits[state];
1430 best = NULL;
1431 bestlen = 0;
1432
1433 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFindBest: uri=\"%s\", limit=%x...", uri, limit);
1434
1435
1436 for (loc = (cupsd_location_t *)cupsArrayFirst(Locations);
1437 loc;
1438 loc = (cupsd_location_t *)cupsArrayNext(Locations))
1439 {
1440 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFindBest: Location %s(%d) Limit %x", loc->location ? loc->location : "(null)", (int)loc->length, loc->limit);
1441
1442 if (!strncmp(uri, "/printers/", 10) || !strncmp(uri, "/classes/", 9))
1443 {
1444 /*
1445 * Use case-insensitive comparison for queue names...
1446 */
1447
1448 if (loc->length > bestlen && loc->location &&
1449 !_cups_strncasecmp(uri, loc->location, loc->length) &&
1450 loc->location[0] == '/' &&
1451 (limit & loc->limit) != 0)
1452 {
1453 best = loc;
1454 bestlen = loc->length;
1455 }
1456 }
1457 else
1458 {
1459 /*
1460 * Use case-sensitive comparison for other URIs...
1461 */
1462
1463 if (loc->length > bestlen && loc->location &&
1464 !strncmp(uri, loc->location, loc->length) &&
1465 loc->location[0] == '/' &&
1466 (limit & loc->limit) != 0)
1467 {
1468 best = loc;
1469 bestlen = loc->length;
1470 }
1471 }
1472 }
1473
1474 /*
1475 * Return the match, if any...
1476 */
1477
1478 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFindBest: best=%s", best ? best->location : "NONE");
1479
1480 return (best);
1481 }
1482
1483
1484 /*
1485 * 'cupsdFindLocation()' - Find the named location.
1486 */
1487
1488 cupsd_location_t * /* O - Location that matches */
1489 cupsdFindLocation(const char *location) /* I - Connection */
1490 {
1491 cupsd_location_t key; /* Search key */
1492
1493
1494 key.location = (char *)location;
1495
1496 return ((cupsd_location_t *)cupsArrayFind(Locations, &key));
1497 }
1498
1499
1500 /*
1501 * 'cupsdFreeLocation()' - Free all memory used by a location.
1502 */
1503
1504 void
1505 cupsdFreeLocation(cupsd_location_t *loc)/* I - Location to free */
1506 {
1507 cupsArrayDelete(loc->names);
1508 cupsArrayDelete(loc->allow);
1509 cupsArrayDelete(loc->deny);
1510
1511 _cupsStrFree(loc->location);
1512 free(loc);
1513 }
1514
1515
1516 /*
1517 * 'cupsdIsAuthorized()' - Check to see if the user is authorized...
1518 */
1519
1520 http_status_t /* O - HTTP_OK if authorized or error code */
1521 cupsdIsAuthorized(cupsd_client_t *con, /* I - Connection */
1522 const char *owner)/* I - Owner of object */
1523 {
1524 int i, /* Looping vars */
1525 auth, /* Authorization status */
1526 type; /* Type of authentication */
1527 http_addr_t *hostaddr = httpGetAddress(con->http);
1528 /* Client address */
1529 const char *hostname = httpGetHostname(con->http, NULL, 0);
1530 /* Client hostname */
1531 unsigned address[4]; /* Authorization address */
1532 cupsd_location_t *best; /* Best match for location so far */
1533 size_t hostlen; /* Length of hostname */
1534 char *name, /* Current username */
1535 username[256], /* Username to authorize */
1536 ownername[256], /* Owner name to authorize */
1537 *ptr; /* Pointer into username */
1538 struct passwd *pw; /* User password data */
1539 static const char * const levels[] = /* Auth levels */
1540 {
1541 "ANON",
1542 "USER",
1543 "GROUP"
1544 };
1545 static const char * const types[] = /* Auth types */
1546 {
1547 "None",
1548 "Basic",
1549 "Negotiate"
1550 };
1551
1552
1553 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: con->uri=\"%s\", con->best=%p(%s)", con->uri, con->best, con->best ? con->best->location ? con->best->location : "(null)" : "");
1554 if (owner)
1555 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: owner=\"%s\"", owner);
1556
1557 /*
1558 * If there is no "best" authentication rule for this request, then
1559 * access is allowed from the local system and denied from other
1560 * addresses...
1561 */
1562
1563 if (!con->best)
1564 {
1565 if (httpAddrLocalhost(httpGetAddress(con->http)) ||
1566 !strcmp(hostname, ServerName) ||
1567 cupsArrayFind(ServerAlias, (void *)hostname))
1568 return (HTTP_OK);
1569 else
1570 return (HTTP_FORBIDDEN);
1571 }
1572
1573 best = con->best;
1574
1575 if ((type = best->type) == CUPSD_AUTH_DEFAULT)
1576 type = cupsdDefaultAuthType();
1577
1578 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: level=CUPSD_AUTH_%s, type=%s, satisfy=CUPSD_AUTH_SATISFY_%s, num_names=%d", levels[best->level], types[type], best->satisfy ? "ANY" : "ALL", cupsArrayCount(best->names));
1579
1580 if (best->limit == CUPSD_AUTH_LIMIT_IPP)
1581 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: op=%x(%s)", best->op, ippOpString(best->op));
1582
1583 /*
1584 * Check host/ip-based accesses...
1585 */
1586
1587 #ifdef AF_INET6
1588 if (httpAddrFamily(hostaddr) == AF_INET6)
1589 {
1590 /*
1591 * Copy IPv6 address...
1592 */
1593
1594 address[0] = ntohl(hostaddr->ipv6.sin6_addr.s6_addr32[0]);
1595 address[1] = ntohl(hostaddr->ipv6.sin6_addr.s6_addr32[1]);
1596 address[2] = ntohl(hostaddr->ipv6.sin6_addr.s6_addr32[2]);
1597 address[3] = ntohl(hostaddr->ipv6.sin6_addr.s6_addr32[3]);
1598 }
1599 else
1600 #endif /* AF_INET6 */
1601 if (con->http->hostaddr->addr.sa_family == AF_INET)
1602 {
1603 /*
1604 * Copy IPv4 address...
1605 */
1606
1607 address[0] = 0;
1608 address[1] = 0;
1609 address[2] = 0;
1610 address[3] = ntohl(hostaddr->ipv4.sin_addr.s_addr);
1611 }
1612 else
1613 memset(address, 0, sizeof(address));
1614
1615 hostlen = strlen(hostname);
1616
1617 auth = cupsdCheckAccess(address, hostname, hostlen, best)
1618 ? CUPSD_AUTH_ALLOW : CUPSD_AUTH_DENY;
1619
1620 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: auth=CUPSD_AUTH_%s...", auth ? "DENY" : "ALLOW");
1621
1622 if (auth == CUPSD_AUTH_DENY && best->satisfy == CUPSD_AUTH_SATISFY_ALL)
1623 return (HTTP_FORBIDDEN);
1624
1625 #ifdef HAVE_SSL
1626 /*
1627 * See if encryption is required...
1628 */
1629
1630 if ((best->encryption >= HTTP_ENCRYPT_REQUIRED && !con->http->tls &&
1631 _cups_strcasecmp(hostname, "localhost") &&
1632 !httpAddrLocalhost(hostaddr) &&
1633 best->satisfy == CUPSD_AUTH_SATISFY_ALL) &&
1634 !(type == CUPSD_AUTH_NEGOTIATE ||
1635 (type == CUPSD_AUTH_NONE &&
1636 cupsdDefaultAuthType() == CUPSD_AUTH_NEGOTIATE)))
1637 {
1638 cupsdLogMessage(CUPSD_LOG_DEBUG,
1639 "cupsdIsAuthorized: Need upgrade to TLS...");
1640 return (HTTP_UPGRADE_REQUIRED);
1641 }
1642 #endif /* HAVE_SSL */
1643
1644 /*
1645 * Now see what access level is required...
1646 */
1647
1648 if (best->level == CUPSD_AUTH_ANON || /* Anonymous access - allow it */
1649 (type == CUPSD_AUTH_NONE && cupsArrayCount(best->names) == 0))
1650 return (HTTP_OK);
1651
1652 if (!con->username[0] && type == CUPSD_AUTH_NONE &&
1653 best->limit == CUPSD_AUTH_LIMIT_IPP)
1654 {
1655 /*
1656 * Check for unauthenticated username...
1657 */
1658
1659 ipp_attribute_t *attr; /* requesting-user-name attribute */
1660
1661
1662 attr = ippFindAttribute(con->request, "requesting-user-name", IPP_TAG_NAME);
1663 if (attr)
1664 {
1665 cupsdLogMessage(CUPSD_LOG_DEBUG,
1666 "cupsdIsAuthorized: requesting-user-name=\"%s\"",
1667 attr->values[0].string.text);
1668 strlcpy(username, attr->values[0].string.text, sizeof(username));
1669 }
1670 else if (best->satisfy == CUPSD_AUTH_SATISFY_ALL || auth == CUPSD_AUTH_DENY)
1671 return (HTTP_UNAUTHORIZED); /* Non-anonymous needs user/pass */
1672 else
1673 return (HTTP_OK); /* unless overridden with Satisfy */
1674 }
1675 else
1676 {
1677 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdIsAuthorized: username=\"%s\"",
1678 con->username);
1679
1680 #ifdef HAVE_AUTHORIZATION_H
1681 if (!con->username[0] && !con->authref)
1682 #else
1683 if (!con->username[0])
1684 #endif /* HAVE_AUTHORIZATION_H */
1685 {
1686 if (best->satisfy == CUPSD_AUTH_SATISFY_ALL || auth == CUPSD_AUTH_DENY)
1687 return (HTTP_UNAUTHORIZED); /* Non-anonymous needs user/pass */
1688 else
1689 return (HTTP_OK); /* unless overridden with Satisfy */
1690 }
1691
1692
1693 if (con->type != type && type != CUPSD_AUTH_NONE &&
1694 #ifdef HAVE_GSSAPI
1695 (type != CUPSD_AUTH_NEGOTIATE || con->gss_uid <= 0) &&
1696 #endif /* HAVE_GSSAPI */
1697 con->type != CUPSD_AUTH_BASIC)
1698 {
1699 cupsdLogMessage(CUPSD_LOG_ERROR, "Authorized using %s, expected %s.",
1700 types[con->type], types[type]);
1701
1702 return (HTTP_UNAUTHORIZED);
1703 }
1704
1705 strlcpy(username, con->username, sizeof(username));
1706 }
1707
1708 /*
1709 * OK, got a username. See if we need normal user access, or group
1710 * access... (root always matches)
1711 */
1712
1713 if (!strcmp(username, "root"))
1714 return (HTTP_OK);
1715
1716 /*
1717 * Strip any @domain or @KDC from the username and owner...
1718 */
1719
1720 if ((ptr = strchr(username, '@')) != NULL)
1721 *ptr = '\0';
1722
1723 if (owner)
1724 {
1725 strlcpy(ownername, owner, sizeof(ownername));
1726
1727 if ((ptr = strchr(ownername, '@')) != NULL)
1728 *ptr = '\0';
1729 }
1730 else
1731 ownername[0] = '\0';
1732
1733 /*
1734 * Get the user info...
1735 */
1736
1737 if (username[0])
1738 {
1739 pw = getpwnam(username);
1740 endpwent();
1741 }
1742 else
1743 pw = NULL;
1744
1745 if (best->level == CUPSD_AUTH_USER)
1746 {
1747 /*
1748 * If there are no names associated with this location, then
1749 * any valid user is OK...
1750 */
1751
1752 if (cupsArrayCount(best->names) == 0)
1753 return (HTTP_OK);
1754
1755 /*
1756 * Otherwise check the user list and return OK if this user is
1757 * allowed...
1758 */
1759
1760 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: Checking user membership...");
1761
1762 #ifdef HAVE_AUTHORIZATION_H
1763 /*
1764 * If an authorization reference was supplied it must match a right name...
1765 */
1766
1767 if (con->authref)
1768 {
1769 for (name = (char *)cupsArrayFirst(best->names);
1770 name;
1771 name = (char *)cupsArrayNext(best->names))
1772 {
1773 if (!_cups_strncasecmp(name, "@AUTHKEY(", 9) && check_authref(con, name + 9))
1774 return (HTTP_OK);
1775 else if (!_cups_strcasecmp(name, "@SYSTEM") && SystemGroupAuthKey &&
1776 check_authref(con, SystemGroupAuthKey))
1777 return (HTTP_OK);
1778 }
1779
1780 return (HTTP_FORBIDDEN);
1781 }
1782 #endif /* HAVE_AUTHORIZATION_H */
1783
1784 for (name = (char *)cupsArrayFirst(best->names);
1785 name;
1786 name = (char *)cupsArrayNext(best->names))
1787 {
1788 if (!_cups_strcasecmp(name, "@OWNER") && owner &&
1789 !_cups_strcasecmp(username, ownername))
1790 return (HTTP_OK);
1791 else if (!_cups_strcasecmp(name, "@SYSTEM"))
1792 {
1793 for (i = 0; i < NumSystemGroups; i ++)
1794 if (cupsdCheckGroup(username, pw, SystemGroups[i]))
1795 return (HTTP_OK);
1796 }
1797 else if (name[0] == '@')
1798 {
1799 if (cupsdCheckGroup(username, pw, name + 1))
1800 return (HTTP_OK);
1801 }
1802 else if (!_cups_strcasecmp(username, name))
1803 return (HTTP_OK);
1804 }
1805
1806 return (con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED);
1807 }
1808
1809 /*
1810 * Check to see if this user is in any of the named groups...
1811 */
1812
1813 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: Checking group membership...");
1814
1815 /*
1816 * Check to see if this user is in any of the named groups...
1817 */
1818
1819 for (name = (char *)cupsArrayFirst(best->names);
1820 name;
1821 name = (char *)cupsArrayNext(best->names))
1822 {
1823 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsAuthorized: Checking group \"%s\" membership...", name);
1824
1825 if (!_cups_strcasecmp(name, "@SYSTEM"))
1826 {
1827 for (i = 0; i < NumSystemGroups; i ++)
1828 if (cupsdCheckGroup(username, pw, SystemGroups[i]))
1829 return (HTTP_OK);
1830 }
1831 else if (cupsdCheckGroup(username, pw, name))
1832 return (HTTP_OK);
1833 }
1834
1835 /*
1836 * The user isn't part of the specified group, so deny access...
1837 */
1838
1839 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdIsAuthorized: User not in group(s).");
1840
1841 return (con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED);
1842 }
1843
1844
1845 /*
1846 * 'cupsdNewLocation()' - Create a new location for authorization.
1847 *
1848 * Note: Still need to call cupsdAddLocation() to add it to the list of global
1849 * locations.
1850 */
1851
1852 cupsd_location_t * /* O - Pointer to new location record */
1853 cupsdNewLocation(const char *location) /* I - Location path */
1854 {
1855 cupsd_location_t *temp; /* New location */
1856
1857
1858 /*
1859 * Try to allocate memory for the new location.
1860 */
1861
1862 if ((temp = calloc(1, sizeof(cupsd_location_t))) == NULL)
1863 return (NULL);
1864
1865 /*
1866 * Initialize the record and copy the name over...
1867 */
1868
1869 if ((temp->location = _cupsStrAlloc(location)) == NULL)
1870 {
1871 free(temp);
1872 return (NULL);
1873 }
1874
1875 temp->length = strlen(temp->location);
1876
1877 /*
1878 * Return the new record...
1879 */
1880
1881 return (temp);
1882 }
1883
1884
1885 #ifdef HAVE_AUTHORIZATION_H
1886 /*
1887 * 'check_authref()' - Check if an authorization services reference has the
1888 * supplied right.
1889 */
1890
1891 static int /* O - 1 if right is valid, 0 otherwise */
1892 check_authref(cupsd_client_t *con, /* I - Connection */
1893 const char *right) /* I - Right name */
1894 {
1895 OSStatus status; /* OS Status */
1896 AuthorizationItem authright; /* Authorization right */
1897 AuthorizationRights authrights; /* Authorization rights */
1898 AuthorizationFlags authflags; /* Authorization flags */
1899
1900
1901 /*
1902 * Check to see if the user is allowed to perform the task...
1903 */
1904
1905 if (!con->authref)
1906 return (0);
1907
1908 authright.name = right;
1909 authright.valueLength = 0;
1910 authright.value = NULL;
1911 authright.flags = 0;
1912
1913 authrights.count = 1;
1914 authrights.items = &authright;
1915
1916 authflags = kAuthorizationFlagDefaults |
1917 kAuthorizationFlagExtendRights;
1918
1919 if ((status = AuthorizationCopyRights(con->authref, &authrights,
1920 kAuthorizationEmptyEnvironment,
1921 authflags, NULL)) != 0)
1922 {
1923 cupsdLogMessage(CUPSD_LOG_ERROR, "AuthorizationCopyRights(\"%s\") returned %d", authright.name, (int)status);
1924 return (0);
1925 }
1926
1927 cupsdLogMessage(CUPSD_LOG_DEBUG2, "AuthorizationCopyRights(\"%s\") succeeded.", authright.name);
1928
1929 return (1);
1930 }
1931 #endif /* HAVE_AUTHORIZATION_H */
1932
1933
1934 /*
1935 * 'compare_locations()' - Compare two locations.
1936 */
1937
1938 static int /* O - Result of comparison */
1939 compare_locations(cupsd_location_t *a, /* I - First location */
1940 cupsd_location_t *b) /* I - Second location */
1941 {
1942 return (strcmp(b->location, a->location));
1943 }
1944
1945
1946 /*
1947 * 'copy_authmask()' - Copy function for auth masks.
1948 */
1949
1950 static cupsd_authmask_t * /* O - New auth mask */
1951 copy_authmask(cupsd_authmask_t *mask, /* I - Existing auth mask */
1952 void *data) /* I - User data (unused) */
1953 {
1954 cupsd_authmask_t *temp; /* New auth mask */
1955
1956
1957 (void)data;
1958
1959 if ((temp = malloc(sizeof(cupsd_authmask_t))) != NULL)
1960 {
1961 memcpy(temp, mask, sizeof(cupsd_authmask_t));
1962
1963 if (temp->type == CUPSD_AUTH_NAME || temp->type == CUPSD_AUTH_INTERFACE)
1964 {
1965 /*
1966 * Make a copy of the name...
1967 */
1968
1969 if ((temp->mask.name.name = _cupsStrAlloc(temp->mask.name.name)) == NULL)
1970 {
1971 /*
1972 * Failed to make copy...
1973 */
1974
1975 free(temp);
1976 temp = NULL;
1977 }
1978 }
1979 }
1980
1981 return (temp);
1982 }
1983
1984
1985 /*
1986 * 'free_authmask()' - Free function for auth masks.
1987 */
1988
1989 static void
1990 free_authmask(cupsd_authmask_t *mask, /* I - Auth mask to free */
1991 void *data) /* I - User data (unused) */
1992 {
1993 (void)data;
1994
1995 if (mask->type == CUPSD_AUTH_NAME || mask->type == CUPSD_AUTH_INTERFACE)
1996 _cupsStrFree(mask->mask.name.name);
1997
1998 free(mask);
1999 }
2000
2001
2002 #if HAVE_LIBPAM
2003 /*
2004 * 'pam_func()' - PAM conversation function.
2005 */
2006
2007 static int /* O - Success or failure */
2008 pam_func(
2009 int num_msg, /* I - Number of messages */
2010 const struct pam_message **msg, /* I - Messages */
2011 struct pam_response **resp, /* O - Responses */
2012 void *appdata_ptr)
2013 /* I - Pointer to connection */
2014 {
2015 int i; /* Looping var */
2016 struct pam_response *replies; /* Replies */
2017 cupsd_authdata_t *data; /* Pointer to auth data */
2018
2019
2020 /*
2021 * Allocate memory for the responses...
2022 */
2023
2024 if ((replies = malloc(sizeof(struct pam_response) * (size_t)num_msg)) == NULL)
2025 return (PAM_CONV_ERR);
2026
2027 /*
2028 * Answer all of the messages...
2029 */
2030
2031 data = (cupsd_authdata_t *)appdata_ptr;
2032
2033 for (i = 0; i < num_msg; i ++)
2034 {
2035 switch (msg[i]->msg_style)
2036 {
2037 case PAM_PROMPT_ECHO_ON:
2038 replies[i].resp_retcode = PAM_SUCCESS;
2039 replies[i].resp = strdup(data->username);
2040 break;
2041
2042 case PAM_PROMPT_ECHO_OFF:
2043 replies[i].resp_retcode = PAM_SUCCESS;
2044 replies[i].resp = strdup(data->password);
2045 break;
2046
2047 case PAM_TEXT_INFO:
2048 replies[i].resp_retcode = PAM_SUCCESS;
2049 replies[i].resp = NULL;
2050 break;
2051
2052 case PAM_ERROR_MSG:
2053 replies[i].resp_retcode = PAM_SUCCESS;
2054 replies[i].resp = NULL;
2055 break;
2056
2057 default:
2058 free(replies);
2059 return (PAM_CONV_ERR);
2060 }
2061 }
2062
2063 /*
2064 * Return the responses back to PAM...
2065 */
2066
2067 *resp = replies;
2068
2069 return (PAM_SUCCESS);
2070 }
2071 #else
2072
2073
2074 /*
2075 * 'to64()' - Base64-encode an integer value...
2076 */
2077
2078 static void
2079 to64(char *s, /* O - Output string */
2080 unsigned long v, /* I - Value to encode */
2081 int n) /* I - Number of digits */
2082 {
2083 const char *itoa64 = "./0123456789"
2084 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2085 "abcdefghijklmnopqrstuvwxyz";
2086
2087
2088 for (; n > 0; n --, v >>= 6)
2089 *s++ = itoa64[v & 0x3f];
2090 }
2091 #endif /* HAVE_LIBPAM */