blob: 601bc40ba56551756d95ae4f369eb5b6f9ba9c2e [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package java.security;
27
28import java.util.ArrayList;
29import java.util.List;
30import sun.security.util.Debug;
31import sun.security.util.SecurityConstants;
32
33/**
34 * An AccessControlContext is used to make system resource access decisions
35 * based on the context it encapsulates.
36 *
37 * <p>More specifically, it encapsulates a context and
38 * has a single method, <code>checkPermission</code>,
39 * that is equivalent to the <code>checkPermission</code> method
40 * in the AccessController class, with one difference: The AccessControlContext
41 * <code>checkPermission</code> method makes access decisions based on the
42 * context it encapsulates,
43 * rather than that of the current execution thread.
44 *
45 * <p>Thus, the purpose of AccessControlContext is for those situations where
46 * a security check that should be made within a given context
47 * actually needs to be done from within a
48 * <i>different</i> context (for example, from within a worker thread).
49 *
50 * <p> An AccessControlContext is created by calling the
51 * <code>AccessController.getContext</code> method.
52 * The <code>getContext</code> method takes a "snapshot"
53 * of the current calling context, and places
54 * it in an AccessControlContext object, which it returns. A sample call is
55 * the following:
56 *
57 * <pre>
58 * AccessControlContext acc = AccessController.getContext()
59 * </pre>
60 *
61 * <p>
62 * Code within a different context can subsequently call the
63 * <code>checkPermission</code> method on the
64 * previously-saved AccessControlContext object. A sample call is the
65 * following:
66 *
67 * <pre>
68 * acc.checkPermission(permission)
69 * </pre>
70 *
71 * @see AccessController
72 *
73 * @author Roland Schemers
74 */
75
76public final class AccessControlContext {
77
78 private ProtectionDomain context[];
79 private boolean isPrivileged;
80
81 // Note: This field is directly used by the virtual machine
82 // native codes. Don't touch it.
83 private AccessControlContext privilegedContext;
84
85 private DomainCombiner combiner = null;
86
87 private static boolean debugInit = false;
88 private static Debug debug = null;
89
90 static Debug getDebug()
91 {
92 if (debugInit)
93 return debug;
94 else {
95 if (Policy.isSet()) {
96 debug = Debug.getInstance("access");
97 debugInit = true;
98 }
99 return debug;
100 }
101 }
102
103 /**
104 * Create an AccessControlContext with the given set of ProtectionDomains.
105 * Context must not be null. Duplicate domains will be removed from the
106 * context.
107 *
108 * @param context the ProtectionDomains associated with this context.
109 * The non-duplicate domains are copied from the array. Subsequent
110 * changes to the array will not affect this AccessControlContext.
111 */
112 public AccessControlContext(ProtectionDomain context[])
113 {
114 if (context.length == 0) {
115 this.context = null;
116 } else if (context.length == 1) {
117 if (context[0] != null) {
118 this.context = context.clone();
119 } else {
120 this.context = null;
121 }
122 } else {
123 List<ProtectionDomain> v = new ArrayList<ProtectionDomain>(context.length);
124 for (int i =0; i< context.length; i++) {
125 if ((context[i] != null) && (!v.contains(context[i])))
126 v.add(context[i]);
127 }
128 this.context = new ProtectionDomain[v.size()];
129 this.context = v.toArray(this.context);
130 }
131 }
132
133 /**
134 * Create a new <code>AccessControlContext</code> with the given
135 * <code>AccessControlContext</code> and <code>DomainCombiner</code>.
136 * This constructor associates the provided
137 * <code>DomainCombiner</code> with the provided
138 * <code>AccessControlContext</code>.
139 *
140 * <p>
141 *
142 * @param acc the <code>AccessControlContext</code> associated
143 * with the provided <code>DomainCombiner</code>.
144 *
145 * @param combiner the <code>DomainCombiner</code> to be associated
146 * with the provided <code>AccessControlContext</code>.
147 *
148 * @exception NullPointerException if the provided
149 * <code>context</code> is <code>null</code>.
150 *
151 * @exception SecurityException if a security manager is installed and the
152 * caller does not have the "createAccessControlContext"
153 * {@link SecurityPermission}
154 * @since 1.3
155 */
156 public AccessControlContext(AccessControlContext acc,
157 DomainCombiner combiner) {
158
159 SecurityManager sm = System.getSecurityManager();
160 if (sm != null) {
161 sm.checkPermission(SecurityConstants.CREATE_ACC_PERMISSION);
162 }
163
164 this.context = acc.context;
165
166 // we do not need to run the combine method on the
167 // provided ACC. it was already "combined" when the
168 // context was originally retrieved.
169 //
170 // at this point in time, we simply throw away the old
171 // combiner and use the newly provided one.
172 this.combiner = combiner;
173 }
174
175 /**
176 * package private for AccessController
177 */
178 AccessControlContext(ProtectionDomain context[], DomainCombiner combiner) {
179 if (context != null) {
180 this.context = context.clone();
181 }
182 this.combiner = combiner;
183 }
184
185 /**
186 * package private constructor for AccessController.getContext()
187 */
188
189 AccessControlContext(ProtectionDomain context[],
190 boolean isPrivileged)
191 {
192 this.context = context;
193 this.isPrivileged = isPrivileged;
194 }
195
196 /**
197 * Returns true if this context is privileged.
198 */
199 boolean isPrivileged()
200 {
201 return isPrivileged;
202 }
203
204 /**
205 * get the assigned combiner from the privileged or inherited context
206 */
207 DomainCombiner getAssignedCombiner() {
208 AccessControlContext acc;
209 if (isPrivileged) {
210 acc = privilegedContext;
211 } else {
212 acc = AccessController.getInheritedAccessControlContext();
213 }
214 if (acc != null) {
215 return acc.combiner;
216 }
217 return null;
218 }
219
220 /**
221 * Get the <code>DomainCombiner</code> associated with this
222 * <code>AccessControlContext</code>.
223 *
224 * <p>
225 *
226 * @return the <code>DomainCombiner</code> associated with this
227 * <code>AccessControlContext</code>, or <code>null</code>
228 * if there is none.
229 *
230 * @exception SecurityException if a security manager is installed and
231 * the caller does not have the "getDomainCombiner"
232 * {@link SecurityPermission}
233 * @since 1.3
234 */
235 public DomainCombiner getDomainCombiner() {
236
237 SecurityManager sm = System.getSecurityManager();
238 if (sm != null) {
239 sm.checkPermission(SecurityConstants.GET_COMBINER_PERMISSION);
240 }
241 return combiner;
242 }
243
244 /**
245 * Determines whether the access request indicated by the
246 * specified permission should be allowed or denied, based on
247 * the security policy currently in effect, and the context in
248 * this object. The request is allowed only if every ProtectionDomain
249 * in the context implies the permission. Otherwise the request is
250 * denied.
251 *
252 * <p>
253 * This method quietly returns if the access request
254 * is permitted, or throws a suitable AccessControlException otherwise.
255 *
256 * @param perm the requested permission.
257 *
258 * @exception AccessControlException if the specified permission
259 * is not permitted, based on the current security policy and the
260 * context encapsulated by this object.
261 * @exception NullPointerException if the permission to check for is null.
262 */
263 public void checkPermission(Permission perm)
264 throws AccessControlException
265 {
266 boolean dumpDebug = false;
267
268 if (perm == null) {
269 throw new NullPointerException("permission can't be null");
270 }
271 if (getDebug() != null) {
272 // If "codebase" is not specified, we dump the info by default.
273 dumpDebug = !Debug.isOn("codebase=");
274 if (!dumpDebug) {
275 // If "codebase" is specified, only dump if the specified code
276 // value is in the stack.
277 for (int i = 0; context != null && i < context.length; i++) {
278 if (context[i].getCodeSource() != null &&
279 context[i].getCodeSource().getLocation() != null &&
280 Debug.isOn("codebase=" + context[i].getCodeSource().getLocation().toString())) {
281 dumpDebug = true;
282 break;
283 }
284 }
285 }
286
287 dumpDebug &= !Debug.isOn("permission=") ||
288 Debug.isOn("permission=" + perm.getClass().getCanonicalName());
289
290 if (dumpDebug && Debug.isOn("stack")) {
291 Thread.currentThread().dumpStack();
292 }
293
294 if (dumpDebug && Debug.isOn("domain")) {
295 if (context == null) {
296 debug.println("domain (context is null)");
297 } else {
298 for (int i=0; i< context.length; i++) {
299 debug.println("domain "+i+" "+context[i]);
300 }
301 }
302 }
303 }
304
305 /*
306 * iterate through the ProtectionDomains in the context.
307 * Stop at the first one that doesn't allow the
308 * requested permission (throwing an exception).
309 *
310 */
311
312 /* if ctxt is null, all we had on the stack were system domains,
313 or the first domain was a Privileged system domain. This
314 is to make the common case for system code very fast */
315
316 if (context == null)
317 return;
318
319 for (int i=0; i< context.length; i++) {
320 if (context[i] != null && !context[i].implies(perm)) {
321 if (dumpDebug) {
322 debug.println("access denied " + perm);
323 }
324
325 if (Debug.isOn("failure")) {
326 // Want to make sure this is always displayed for failure,
327 // but do not want to display again if already displayed
328 // above.
329 if (!dumpDebug) {
330 debug.println("access denied " + perm);
331 }
332 Thread.currentThread().dumpStack();
333 final ProtectionDomain pd = context[i];
334 final Debug db = debug;
335 AccessController.doPrivileged (new PrivilegedAction<Void>() {
336 public Void run() {
337 db.println("domain that failed "+pd);
338 return null;
339 }
340 });
341 }
342 throw new AccessControlException("access denied "+perm, perm);
343 }
344 }
345
346 // allow if all of them allowed access
347 if (dumpDebug) {
348 debug.println("access allowed "+perm);
349 }
350
351 return;
352 }
353
354 /**
355 * Take the stack-based context (this) and combine it with the
356 * privileged or inherited context, if need be.
357 */
358 AccessControlContext optimize() {
359 // the assigned (privileged or inherited) context
360 AccessControlContext acc;
361 if (isPrivileged) {
362 acc = privilegedContext;
363 } else {
364 acc = AccessController.getInheritedAccessControlContext();
365 }
366
367 // this.context could be null if only system code is on the stack;
368 // in that case, ignore the stack context
369 boolean skipStack = (context == null);
370
371 // acc.context could be null if only system code was involved;
372 // in that case, ignore the assigned context
373 boolean skipAssigned = (acc == null || acc.context == null);
374
375 if (acc != null && acc.combiner != null) {
376 // let the assigned acc's combiner do its thing
377 return goCombiner(context, acc);
378 }
379
380 // optimization: if neither have contexts; return acc if possible
381 // rather than this, because acc might have a combiner
382 if (skipAssigned && skipStack) {
383 return this;
384 }
385
386 // optimization: if there is no stack context; there is no reason
387 // to compress the assigned context, it already is compressed
388 if (skipStack) {
389 return acc;
390 }
391
392 int slen = context.length;
393
394 // optimization: if there is no assigned context and the stack length
395 // is less then or equal to two; there is no reason to compress the
396 // stack context, it already is
397 if (skipAssigned && slen <= 2) {
398 return this;
399 }
400
401 // optimization: if there is a single stack domain and that domain
402 // is already in the assigned context; no need to combine
403 if ((slen == 1) && (context[0] == acc.context[0])) {
404 return acc;
405 }
406
407 int n = (skipAssigned) ? 0 : acc.context.length;
408
409 // now we combine both of them, and create a new context
410 ProtectionDomain pd[] = new ProtectionDomain[slen + n];
411
412 // first copy in the assigned context domains, no need to compress
413 if (!skipAssigned) {
414 System.arraycopy(acc.context, 0, pd, 0, n);
415 }
416
417 // now add the stack context domains, discarding nulls and duplicates
418 outer:
419 for (int i = 0; i < context.length; i++) {
420 ProtectionDomain sd = context[i];
421 if (sd != null) {
422 for (int j = 0; j < n; j++) {
423 if (sd == pd[j]) {
424 continue outer;
425 }
426 }
427 pd[n++] = sd;
428 }
429 }
430
431 // if length isn't equal, we need to shorten the array
432 if (n != pd.length) {
433 // optimization: if we didn't really combine anything
434 if (!skipAssigned && n == acc.context.length) {
435 return acc;
436 } else if (skipAssigned && n == slen) {
437 return this;
438 }
439 ProtectionDomain tmp[] = new ProtectionDomain[n];
440 System.arraycopy(pd, 0, tmp, 0, n);
441 pd = tmp;
442 }
443
444 // return new AccessControlContext(pd, false);
445
446 // Reuse existing ACC
447
448 this.context = pd;
449 this.combiner = null;
450 this.isPrivileged = false;
451
452 return this;
453 }
454
455 private AccessControlContext goCombiner(ProtectionDomain[] current,
456 AccessControlContext assigned) {
457
458 // the assigned ACC's combiner is not null --
459 // let the combiner do its thing
460
461 // XXX we could add optimizations to 'current' here ...
462
463 if (getDebug() != null) {
464 debug.println("AccessControlContext invoking the Combiner");
465 }
466
467 // No need to clone current and assigned.context
468 // combine() will not update them
469 ProtectionDomain[] combinedPds = assigned.combiner.combine(
470 current, assigned.context);
471
472 // return new AccessControlContext(combinedPds, assigned.combiner);
473
474 // Reuse existing ACC
475 this.context = combinedPds;
476 this.combiner = assigned.combiner;
477 this.isPrivileged = false;
478
479 return this;
480 }
481
482 /**
483 * Checks two AccessControlContext objects for equality.
484 * Checks that <i>obj</i> is
485 * an AccessControlContext and has the same set of ProtectionDomains
486 * as this context.
487 * <P>
488 * @param obj the object we are testing for equality with this object.
489 * @return true if <i>obj</i> is an AccessControlContext, and has the
490 * same set of ProtectionDomains as this context, false otherwise.
491 */
492 public boolean equals(Object obj) {
493 if (obj == this)
494 return true;
495
496 if (! (obj instanceof AccessControlContext))
497 return false;
498
499 AccessControlContext that = (AccessControlContext) obj;
500
501
502 if (context == null) {
503 return (that.context == null);
504 }
505
506 if (that.context == null)
507 return false;
508
509 if (!(this.containsAllPDs(that) && that.containsAllPDs(this)))
510 return false;
511
512 if (this.combiner == null)
513 return (that.combiner == null);
514
515 if (that.combiner == null)
516 return false;
517
518 if (!this.combiner.equals(that.combiner))
519 return false;
520
521 return true;
522 }
523
524 private boolean containsAllPDs(AccessControlContext that) {
525 boolean match = false;
526 //
527 // ProtectionDomains within an ACC currently cannot be null
528 // and this is enforced by the constructor and the various
529 // optimize methods. However, historically this logic made attempts
530 // to support the notion of a null PD and therefore this logic continues
531 // to support that notion.
532 ProtectionDomain thisPd;
533 for (int i = 0; i < context.length; i++) {
534 match = false;
535 if ((thisPd = context[i]) == null) {
536 for (int j = 0; (j < that.context.length) && !match; j++) {
537 match = (that.context[j] == null);
538 }
539 } else {
540 Class thisPdClass = thisPd.getClass();
541 ProtectionDomain thatPd;
542 for (int j = 0; (j < that.context.length) && !match; j++) {
543 thatPd = that.context[j];
544
545 // Class check required to avoid PD exposure (4285406)
546 match = (thatPd != null &&
547 thisPdClass == thatPd.getClass() && thisPd.equals(thatPd));
548 }
549 }
550 if (!match) return false;
551 }
552 return match;
553 }
554 /**
555 * Returns the hash code value for this context. The hash code
556 * is computed by exclusive or-ing the hash code of all the protection
557 * domains in the context together.
558 *
559 * @return a hash code value for this context.
560 */
561
562 public int hashCode() {
563 int hashCode = 0;
564
565 if (context == null)
566 return hashCode;
567
568 for (int i =0; i < context.length; i++) {
569 if (context[i] != null)
570 hashCode ^= context[i].hashCode();
571 }
572 return hashCode;
573 }
574}