       1 /*
       2  * Copyright (c) 1998, 2020, Oracle and/or its affiliates. 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.  Oracle designates this
       8  * particular file as subject to the "Classpath" exception as provided
       9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
      22  * or visit www.oracle.com if you need additional information or have any
      23  * questions.
      24  */
      25
      26 package javax.security.auth;
      27
      28 import java.util.*;
      29 import java.io.*;
      30 import java.lang.reflect.*;
      31 import java.text.MessageFormat;
      32 import java.security.AccessController;
      33 import java.security.AccessControlContext;
      34 import java.security.DomainCombiner;
      35 import java.security.Permission;
      36 import java.security.PermissionCollection;
      37 import java.security.Principal;
      38 import java.security.PrivilegedAction;
      39 import java.security.PrivilegedExceptionAction;
      40 import java.security.PrivilegedActionException;
      41 import java.security.ProtectionDomain;
      42 import sun.security.util.ResourcesMgr;
      43
      44 /**
      45  * <p> A {@code Subject} represents a grouping of related information
      46  * for a single entity, such as a person.
      47  * Such information includes the Subject's identities as well as
      48  * its security-related attributes
      49  * (passwords and cryptographic keys, for example).
      50  *
      51  * <p> Subjects may potentially have multiple identities.
      52  * Each identity is represented as a {@code Principal}
      53  * within the {@code Subject}.  Principals simply bind names to a
      54  * {@code Subject}.  For example, a {@code Subject} that happens
      55  * to be a person, Alice, might have two Principals:
      56  * one which binds "Alice Bar", the name on her driver license,
      57  * to the {@code Subject}, and another which binds,
      58  * "999-99-9999", the number on her student identification card,
      59  * to the {@code Subject}.  Both Principals refer to the same
      60  * {@code Subject} even though each has a different name.
      61  *
      62  * <p> A {@code Subject} may also own security-related attributes,
      63  * which are referred to as credentials.
      64  * Sensitive credentials that require special protection, such as
      65  * private cryptographic keys, are stored within a private credential
      66  * {@code Set}.  Credentials intended to be shared, such as
      67  * public key certificates or Kerberos server tickets are stored
      68  * within a public credential {@code Set}.  Different permissions
      69  * are required to access and modify the different credential Sets.
      70  *
      71  * <p> To retrieve all the Principals associated with a {@code Subject},
      72  * invoke the {@code getPrincipals} method.  To retrieve
      73  * all the public or private credentials belonging to a {@code Subject},
      74  * invoke the {@code getPublicCredentials} method or
      75  * {@code getPrivateCredentials} method, respectively.
      76  * To modify the returned {@code Set} of Principals and credentials,
      77  * use the methods defined in the {@code Set} class.
      78  * For example:
      79  * <pre>
      80  *      Subject subject;
      81  *      Principal principal;
      82  *      Object credential;
      83  *
      84  *      // add a Principal and credential to the Subject
      85  *      subject.getPrincipals().add(principal);
      86  *      subject.getPublicCredentials().add(credential);
      87  * </pre>
      88  *
      89  * <p> This {@code Subject} class implements {@code Serializable}.
      90  * While the Principals associated with the {@code Subject} are serialized,
      91  * the credentials associated with the {@code Subject} are not.
      92  * Note that the {@code java.security.Principal} class
      93  * does not implement {@code Serializable}.  Therefore all concrete
      94  * {@code Principal} implementations associated with Subjects
      95  * must implement {@code Serializable}.
      96  *
      97  * @since 1.4
      98  * @see java.security.Principal
      99  * @see java.security.DomainCombiner
     100  */
     101 public final class Subject implements java.io.Serializable {
     102
     103     @java.io.Serial
     104     private static final long serialVersionUID = -8308522755600156056L;
     105
     106     /**
     107      * A {@code Set} that provides a view of all of this
     108      * Subject's Principals
     109      *
     110      * @serial Each element in this set is a
     111      *          {@code java.security.Principal}.
     112      *          The set is a {@code Subject.SecureSet}.
     113      */
     114     @SuppressWarnings("serial") // Not statically typed as Serializable
     115     Set<Principal> principals;
     116
     117     /**
     118      * Sets that provide a view of all of this
     119      * Subject's Credentials
     120      */
     121     transient Set<Object> pubCredentials;
     122     transient Set<Object> privCredentials;
     123
     124     /**
     125      * Whether this Subject is read-only
     126      *
     127      * @serial
     128      */
     129     private volatile boolean readOnly;
     130
     131     private static final int PRINCIPAL_SET = 1;
     132     private static final int PUB_CREDENTIAL_SET = 2;
     133     private static final int PRIV_CREDENTIAL_SET = 3;
     134
     135     private static final ProtectionDomain[] NULL_PD_ARRAY
     136         = new ProtectionDomain[0];
     137
     138     /**
     139      * Create an instance of a {@code Subject}
     140      * with an empty {@code Set} of Principals and empty
     141      * Sets of public and private credentials.
     142      *
     143      * <p> The newly constructed Sets check whether this {@code Subject}
     144      * has been set read-only before permitting subsequent modifications.
     145      * The newly created Sets also prevent illegal modifications
     146      * by ensuring that callers have sufficient permissions.  These Sets
     147      * also prohibit null elements, and attempts to add or query a null
     148      * element will result in a {@code NullPointerException}.
     149      *
     150      * <p> To modify the Principals Set, the caller must have
     151      * {@code AuthPermission("modifyPrincipals")}.
     152      * To modify the public credential Set, the caller must have
     153      * {@code AuthPermission("modifyPublicCredentials")}.
     154      * To modify the private credential Set, the caller must have
     155      * {@code AuthPermission("modifyPrivateCredentials")}.
     156      */
     157     public Subject() {
     158
     159         this.principals = Collections.synchronizedSet
     160                         (new SecureSet<>(this, PRINCIPAL_SET));
     161         this.pubCredentials = Collections.synchronizedSet
     162                         (new SecureSet<>(this, PUB_CREDENTIAL_SET));
     163         this.privCredentials = Collections.synchronizedSet
     164                         (new SecureSet<>(this, PRIV_CREDENTIAL_SET));
     165     }
     166
     167     /**
     168      * Create an instance of a {@code Subject} with
     169      * Principals and credentials.
     170      *
     171      * <p> The Principals and credentials from the specified Sets
     172      * are copied into newly constructed Sets.
     173      * These newly created Sets check whether this {@code Subject}
     174      * has been set read-only before permitting subsequent modifications.
     175      * The newly created Sets also prevent illegal modifications
     176      * by ensuring that callers have sufficient permissions.  These Sets
     177      * also prohibit null elements, and attempts to add or query a null
     178      * element will result in a {@code NullPointerException}.
     179      *
     180      * <p> To modify the Principals Set, the caller must have
     181      * {@code AuthPermission("modifyPrincipals")}.
     182      * To modify the public credential Set, the caller must have
     183      * {@code AuthPermission("modifyPublicCredentials")}.
     184      * To modify the private credential Set, the caller must have
     185      * {@code AuthPermission("modifyPrivateCredentials")}.
     186      *
     187      * @param readOnly true if the {@code Subject} is to be read-only,
     188      *          and false otherwise.
     189      *
     190      * @param principals the {@code Set} of Principals
     191      *          to be associated with this {@code Subject}.
     192      *
     193      * @param pubCredentials the {@code Set} of public credentials
     194      *          to be associated with this {@code Subject}.
     195      *
     196      * @param privCredentials the {@code Set} of private credentials
     197      *          to be associated with this {@code Subject}.
     198      *
     199      * @throws NullPointerException if the specified
     200      *          {@code principals}, {@code pubCredentials},
     201      *          or {@code privCredentials} are {@code null},
     202      *          or a null value exists within any of these three
     203      *          Sets.
     204      */
     205     public Subject(boolean readOnly, Set<? extends Principal> principals,
     206                    Set<?> pubCredentials, Set<?> privCredentials) {
     207         LinkedList<Principal> principalList
     208                 = collectionNullClean(principals);
     209         LinkedList<Object> pubCredsList
     210                 = collectionNullClean(pubCredentials);
     211         LinkedList<Object> privCredsList
     212                 = collectionNullClean(privCredentials);
     213
     214         this.principals = Collections.synchronizedSet(
     215                 new SecureSet<>(this, PRINCIPAL_SET, principalList));
     216         this.pubCredentials = Collections.synchronizedSet(
     217                 new SecureSet<>(this, PUB_CREDENTIAL_SET, pubCredsList));
     218         this.privCredentials = Collections.synchronizedSet(
     219                 new SecureSet<>(this, PRIV_CREDENTIAL_SET, privCredsList));
     220         this.readOnly = readOnly;
     221     }
     222
     223     /**
     224      * Set this {@code Subject} to be read-only.
     225      *
     226      * <p> Modifications (additions and removals) to this Subject's
     227      * {@code Principal} {@code Set} and
     228      * credential Sets will be disallowed.
     229      * The {@code destroy} operation on this Subject's credentials will
     230      * still be permitted.
     231      *
     232      * <p> Subsequent attempts to modify the Subject's {@code Principal}
     233      * and credential Sets will result in an
     234      * {@code IllegalStateException} being thrown.
     235      * Also, once a {@code Subject} is read-only,
     236      * it can not be reset to being writable again.
     237      *
     238      * @throws SecurityException if a security manager is installed and the
     239      *         caller does not have an
     240      *         {@link AuthPermission#AuthPermission(String)
     241      *         AuthPermission("setReadOnly")} permission to set this
     242      *         {@code Subject} to be read-only.
     243      */
     244     public void setReadOnly() {
     245         java.lang.SecurityManager sm = System.getSecurityManager();
     246         if (sm != null) {
     247             sm.checkPermission(AuthPermissionHolder.SET_READ_ONLY_PERMISSION);
     248         }
     249
     250         this.readOnly = true;
     251     }
     252
     253     /**
     254      * Query whether this {@code Subject} is read-only.
     255      *
     256      * @return true if this {@code Subject} is read-only, false otherwise.
     257      */
     258     public boolean isReadOnly() {
     259         return this.readOnly;
     260     }
     261
     262     /**
     263      * Get the {@code Subject} associated with the provided
     264      * {@code AccessControlContext}.
     265      *
     266      * <p> The {@code AccessControlContext} may contain many
     267      * Subjects (from nested {@code doAs} calls).
     268      * In this situation, the most recent {@code Subject} associated
     269      * with the {@code AccessControlContext} is returned.
     270      *
     271      * @param  acc the {@code AccessControlContext} from which to retrieve
     272      *          the {@code Subject}.
     273      *
     274      * @return  the {@code Subject} associated with the provided
     275      *          {@code AccessControlContext}, or {@code null}
     276      *          if no {@code Subject} is associated
     277      *          with the provided {@code AccessControlContext}.
     278      *
     279      * @throws SecurityException if a security manager is installed and the
     280      *          caller does not have an
     281      *          {@link AuthPermission#AuthPermission(String)
     282      *          AuthPermission("getSubject")} permission to get the
     283      *          {@code Subject}.
     284      *
     285      * @throws NullPointerException if the provided
     286      *          {@code AccessControlContext} is {@code null}.
     287      */
     288     public static Subject getSubject(final AccessControlContext acc) {
     289
     290         java.lang.SecurityManager sm = System.getSecurityManager();
     291         if (sm != null) {
     292             sm.checkPermission(AuthPermissionHolder.GET_SUBJECT_PERMISSION);
     293         }
     294
     295         Objects.requireNonNull(acc, ResourcesMgr.getString
     296                 ("invalid.null.AccessControlContext.provided"));
     297
     298         // return the Subject from the DomainCombiner of the provided context
     299         return AccessController.doPrivileged
     300             (new java.security.PrivilegedAction<>() {
     301             public Subject run() {
     302                 DomainCombiner dc = acc.getDomainCombiner();
     303                 if (!(dc instanceof SubjectDomainCombiner)) {
     304                     return null;
     305                 }
     306                 SubjectDomainCombiner sdc = (SubjectDomainCombiner)dc;
     307                 return sdc.getSubject();
     308             }
     309         });
     310     }
     311
     312     /**
     313      * Perform work as a particular {@code Subject}.
     314      *
     315      * <p> This method first retrieves the current Thread's
     316      * {@code AccessControlContext} via
     317      * {@code AccessController.getContext},
     318      * and then instantiates a new {@code AccessControlContext}
     319      * using the retrieved context along with a new
     320      * {@code SubjectDomainCombiner} (constructed using
     321      * the provided {@code Subject}).
     322      * Finally, this method invokes {@code AccessController.doPrivileged},
     323      * passing it the provided {@code PrivilegedAction},
     324      * as well as the newly constructed {@code AccessControlContext}.
     325      *
     326      * @param subject the {@code Subject} that the specified
     327      *                  {@code action} will run as.  This parameter
     328      *                  may be {@code null}.
     329      *
     330      * @param <T> the type of the value returned by the PrivilegedAction's
     331      *                  {@code run} method.
     332      *
     333      * @param action the code to be run as the specified
     334      *                  {@code Subject}.
     335      *
     336      * @return the value returned by the PrivilegedAction's
     337      *                  {@code run} method.
     338      *
     339      * @throws NullPointerException if the {@code PrivilegedAction}
     340      *                  is {@code null}.
     341      *
     342      * @throws SecurityException if a security manager is installed and the
     343      *                  caller does not have an
     344      *                  {@link AuthPermission#AuthPermission(String)
     345      *                  AuthPermission("doAs")} permission to invoke this
     346      *                  method.
     347      */
     348     public static <T> T doAs(final Subject subject,
     349                         final java.security.PrivilegedAction<T> action) {
     350
     351         java.lang.SecurityManager sm = System.getSecurityManager();
     352         if (sm != null) {
     353             sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
     354         }
     355
     356         Objects.requireNonNull(action,
     357                 ResourcesMgr.getString("invalid.null.action.provided"));
     358
     359         // set up the new Subject-based AccessControlContext
     360         // for doPrivileged
     361         final AccessControlContext currentAcc = AccessController.getContext();
     362
     363         // call doPrivileged and push this new context on the stack
     364         return java.security.AccessController.doPrivileged
     365                                         (action,
     366                                         createContext(subject, currentAcc));
     367     }
     368
     369     /**
     370      * Perform work as a particular {@code Subject}.
     371      *
     372      * <p> This method first retrieves the current Thread's
     373      * {@code AccessControlContext} via
     374      * {@code AccessController.getContext},
     375      * and then instantiates a new {@code AccessControlContext}
     376      * using the retrieved context along with a new
     377      * {@code SubjectDomainCombiner} (constructed using
     378      * the provided {@code Subject}).
     379      * Finally, this method invokes {@code AccessController.doPrivileged},
     380      * passing it the provided {@code PrivilegedExceptionAction},
     381      * as well as the newly constructed {@code AccessControlContext}.
     382      *
     383      * @param subject the {@code Subject} that the specified
     384      *                  {@code action} will run as.  This parameter
     385      *                  may be {@code null}.
     386      *
     387      * @param <T> the type of the value returned by the
     388      *                  PrivilegedExceptionAction's {@code run} method.
     389      *
     390      * @param action the code to be run as the specified
     391      *                  {@code Subject}.
     392      *
     393      * @return the value returned by the
     394      *                  PrivilegedExceptionAction's {@code run} method.
     395      *
     396      * @throws PrivilegedActionException if the
     397      *                  {@code PrivilegedExceptionAction.run}
     398      *                  method throws a checked exception.
     399      *
     400      * @throws NullPointerException if the specified
     401      *                  {@code PrivilegedExceptionAction} is
     402      *                  {@code null}.
     403      *
     404      * @throws SecurityException if a security manager is installed and the
     405      *                  caller does not have an
     406      *                  {@link AuthPermission#AuthPermission(String)
     407      *                  AuthPermission("doAs")} permission to invoke this
     408      *                  method.
     409      */
     410     public static <T> T doAs(final Subject subject,
     411                         final java.security.PrivilegedExceptionAction<T> action)
     412                         throws java.security.PrivilegedActionException {
     413
     414         java.lang.SecurityManager sm = System.getSecurityManager();
     415         if (sm != null) {
     416             sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
     417         }
     418
     419         Objects.requireNonNull(action,
     420                 ResourcesMgr.getString("invalid.null.action.provided"));
     421
     422         // set up the new Subject-based AccessControlContext for doPrivileged
     423         final AccessControlContext currentAcc = AccessController.getContext();
     424
     425         // call doPrivileged and push this new context on the stack
     426         return java.security.AccessController.doPrivileged
     427                                         (action,
     428                                         createContext(subject, currentAcc));
     429     }
     430
     431     /**
     432      * Perform privileged work as a particular {@code Subject}.
     433      *
     434      * <p> This method behaves exactly as {@code Subject.doAs},
     435      * except that instead of retrieving the current Thread's
     436      * {@code AccessControlContext}, it uses the provided
     437      * {@code AccessControlContext}.  If the provided
     438      * {@code AccessControlContext} is {@code null},
     439      * this method instantiates a new {@code AccessControlContext}
     440      * with an empty collection of ProtectionDomains.
     441      *
     442      * @param subject the {@code Subject} that the specified
     443      *                  {@code action} will run as.  This parameter
     444      *                  may be {@code null}.
     445      *
     446      * @param <T> the type of the value returned by the PrivilegedAction's
     447      *                  {@code run} method.
     448      *
     449      * @param action the code to be run as the specified
     450      *                  {@code Subject}.
     451      *
     452      * @param acc the {@code AccessControlContext} to be tied to the
     453      *                  specified <i>subject</i> and <i>action</i>.
     454      *
     455      * @return the value returned by the PrivilegedAction's
     456      *                  {@code run} method.
     457      *
     458      * @throws NullPointerException if the {@code PrivilegedAction}
     459      *                  is {@code null}.
     460      *
     461      * @throws SecurityException if a security manager is installed and the
     462      *                  caller does not have a
     463      *                  {@link AuthPermission#AuthPermission(String)
     464      *                  AuthPermission("doAsPrivileged")} permission to invoke
     465      *                  this method.
     466      */
     467     public static <T> T doAsPrivileged(final Subject subject,
     468                         final java.security.PrivilegedAction<T> action,
     469                         final java.security.AccessControlContext acc) {
     470
     471         java.lang.SecurityManager sm = System.getSecurityManager();
     472         if (sm != null) {
     473             sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION);
     474         }
     475
     476         Objects.requireNonNull(action,
     477                 ResourcesMgr.getString("invalid.null.action.provided"));
     478
     479         // set up the new Subject-based AccessControlContext
     480         // for doPrivileged
     481         final AccessControlContext callerAcc =
     482                 (acc == null ?
     483                 new AccessControlContext(NULL_PD_ARRAY) :
     484                 acc);
     485
     486         // call doPrivileged and push this new context on the stack
     487         return java.security.AccessController.doPrivileged
     488                                         (action,
     489                                         createContext(subject, callerAcc));
     490     }
     491
     492     /**
     493      * Perform privileged work as a particular {@code Subject}.
     494      *
     495      * <p> This method behaves exactly as {@code Subject.doAs},
     496      * except that instead of retrieving the current Thread's
     497      * {@code AccessControlContext}, it uses the provided
     498      * {@code AccessControlContext}.  If the provided
     499      * {@code AccessControlContext} is {@code null},
     500      * this method instantiates a new {@code AccessControlContext}
     501      * with an empty collection of ProtectionDomains.
     502      *
     503      * @param subject the {@code Subject} that the specified
     504      *                  {@code action} will run as.  This parameter
     505      *                  may be {@code null}.
     506      *
     507      * @param <T> the type of the value returned by the
     508      *                  PrivilegedExceptionAction's {@code run} method.
     509      *
     510      * @param action the code to be run as the specified
     511      *                  {@code Subject}.
     512      *
     513      * @param acc the {@code AccessControlContext} to be tied to the
     514      *                  specified <i>subject</i> and <i>action</i>.
     515      *
     516      * @return the value returned by the
     517      *                  PrivilegedExceptionAction's {@code run} method.
     518      *
     519      * @throws PrivilegedActionException if the
     520      *                  {@code PrivilegedExceptionAction.run}
     521      *                  method throws a checked exception.
     522      *
     523      * @throws NullPointerException if the specified
     524      *                  {@code PrivilegedExceptionAction} is
     525      *                  {@code null}.
     526      *
     527      * @throws SecurityException if a security manager is installed and the
     528      *                  caller does not have a
     529      *                  {@link AuthPermission#AuthPermission(String)
     530      *                  AuthPermission("doAsPrivileged")} permission to invoke
     531      *                  this method.
     532      */
     533     public static <T> T doAsPrivileged(final Subject subject,
     534                         final java.security.PrivilegedExceptionAction<T> action,
     535                         final java.security.AccessControlContext acc)
     536                         throws java.security.PrivilegedActionException {
     537
     538         java.lang.SecurityManager sm = System.getSecurityManager();
     539         if (sm != null) {
     540             sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION);
     541         }
     542
     543         Objects.requireNonNull(action,
     544                 ResourcesMgr.getString("invalid.null.action.provided"));
     545
     546         // set up the new Subject-based AccessControlContext for doPrivileged
     547         final AccessControlContext callerAcc =
     548                 (acc == null ?
     549                 new AccessControlContext(NULL_PD_ARRAY) :
     550                 acc);
     551
     552         // call doPrivileged and push this new context on the stack
     553         return java.security.AccessController.doPrivileged
     554                                         (action,
     555                                         createContext(subject, callerAcc));
     556     }
     557
     558     private static AccessControlContext createContext(final Subject subject,
     559                                         final AccessControlContext acc) {
     560
     561
     562         return java.security.AccessController.doPrivileged
     563             (new java.security.PrivilegedAction<>() {
     564             public AccessControlContext run() {
     565                 if (subject == null) {
     566                     return new AccessControlContext(acc, null);
     567                 } else {
     568                     return new AccessControlContext
     569                                         (acc,
     570                                         new SubjectDomainCombiner(subject));
     571             }
     572             }
     573         });
     574     }
     575
     576     /**
     577      * Return the {@code Set} of Principals associated with this
     578      * {@code Subject}.  Each {@code Principal} represents
     579      * an identity for this {@code Subject}.
     580      *
     581      * <p> The returned {@code Set} is backed by this Subject's
     582      * internal {@code Principal} {@code Set}.  Any modification
     583      * to the returned {@code Set} affects the internal
     584      * {@code Principal} {@code Set} as well.
     585      *
     586      * <p> If a security manager is installed, the caller must have a
     587      * {@link AuthPermission#AuthPermission(String)
     588      * AuthPermission("modifyPrincipals")} permission to modify
     589      * the returned set, or a {@code SecurityException} will be thrown.
     590      *
     591      * @return  the {@code Set} of Principals associated with this
     592      *          {@code Subject}.
     593      */
     594     public Set<Principal> getPrincipals() {
     595
     596         // always return an empty Set instead of null
     597         // so LoginModules can add to the Set if necessary
     598         return principals;
     599     }
     600
     601     /**
     602      * Return a {@code Set} of Principals associated with this
     603      * {@code Subject} that are instances or subclasses of the specified
     604      * {@code Class}.
     605      *
     606      * <p> The returned {@code Set} is not backed by this Subject's
     607      * internal {@code Principal} {@code Set}.  A new
     608      * {@code Set} is created and returned for each method invocation.
     609      * Modifications to the returned {@code Set}
     610      * will not affect the internal {@code Principal} {@code Set}.
     611      *
     612      * @param <T> the type of the class modeled by {@code c}
     613      *
     614      * @param c the returned {@code Set} of Principals will all be
     615      *          instances of this class.
     616      *
     617      * @return a {@code Set} of Principals that are instances of the
     618      *          specified {@code Class}.
     619      *
     620      * @throws NullPointerException if the specified {@code Class}
     621      *          is {@code null}.
     622      */
     623     public <T extends Principal> Set<T> getPrincipals(Class<T> c) {
     624
     625         Objects.requireNonNull(c,
     626                 ResourcesMgr.getString("invalid.null.Class.provided"));
     627
     628         // always return an empty Set instead of null
     629         // so LoginModules can add to the Set if necessary
     630         return new ClassSet<T>(PRINCIPAL_SET, c);
     631     }
     632
     633     /**
     634      * Return the {@code Set} of public credentials held by this
     635      * {@code Subject}.
     636      *
     637      * <p> The returned {@code Set} is backed by this Subject's
     638      * internal public Credential {@code Set}.  Any modification
     639      * to the returned {@code Set} affects the internal public
     640      * Credential {@code Set} as well.
     641      *
     642      * <p> If a security manager is installed, the caller must have a
     643      * {@link AuthPermission#AuthPermission(String)
     644      * AuthPermission("modifyPublicCredentials")} permission to modify
     645      * the returned set, or a {@code SecurityException} will be thrown.
     646      *
     647      * @return  a {@code Set} of public credentials held by this
     648      *          {@code Subject}.
     649      */
     650     public Set<Object> getPublicCredentials() {
     651
     652         // always return an empty Set instead of null
     653         // so LoginModules can add to the Set if necessary
     654         return pubCredentials;
     655     }
     656
     657     /**
     658      * Return the {@code Set} of private credentials held by this
     659      * {@code Subject}.
     660      *
     661      * <p> The returned {@code Set} is backed by this Subject's
     662      * internal private Credential {@code Set}.  Any modification
     663      * to the returned {@code Set} affects the internal private
     664      * Credential {@code Set} as well.
     665      *
     666      * <p> If a security manager is installed, the caller must have a
     667      * {@link AuthPermission#AuthPermission(String)
     668      * AuthPermission("modifyPrivateCredentials")} permission to modify
     669      * the returned set, or a {@code SecurityException} will be thrown.
     670      *
     671      * <p> While iterating through the {@code Set},
     672      * a {@code SecurityException} is thrown if a security manager is installed
     673      * and the caller does not have a {@link PrivateCredentialPermission}
     674      * to access a particular Credential.  The {@code Iterator}
     675      * is nevertheless advanced to the next element in the {@code Set}.
     676      *
     677      * @return  a {@code Set} of private credentials held by this
     678      *          {@code Subject}.
     679      */
     680     public Set<Object> getPrivateCredentials() {
     681
     682         // XXX
     683         // we do not need a security check for
     684         // AuthPermission(getPrivateCredentials)
     685         // because we already restrict access to private credentials
     686         // via the PrivateCredentialPermission.  all the extra AuthPermission
     687         // would do is protect the set operations themselves
     688         // (like size()), which don't seem security-sensitive.
     689
     690         // always return an empty Set instead of null
     691         // so LoginModules can add to the Set if necessary
     692         return privCredentials;
     693     }
     694
     695     /**
     696      * Return a {@code Set} of public credentials associated with this
     697      * {@code Subject} that are instances or subclasses of the specified
     698      * {@code Class}.
     699      *
     700      * <p> The returned {@code Set} is not backed by this Subject's
     701      * internal public Credential {@code Set}.  A new
     702      * {@code Set} is created and returned for each method invocation.
     703      * Modifications to the returned {@code Set}
     704      * will not affect the internal public Credential {@code Set}.
     705      *
     706      * @param <T> the type of the class modeled by {@code c}
     707      *
     708      * @param c the returned {@code Set} of public credentials will all be
     709      *          instances of this class.
     710      *
     711      * @return a {@code Set} of public credentials that are instances
     712      *          of the  specified {@code Class}.
     713      *
     714      * @throws NullPointerException if the specified {@code Class}
     715      *          is {@code null}.
     716      */
     717     public <T> Set<T> getPublicCredentials(Class<T> c) {
     718
     719         Objects.requireNonNull(c,
     720                 ResourcesMgr.getString("invalid.null.Class.provided"));
     721
     722         // always return an empty Set instead of null
     723         // so LoginModules can add to the Set if necessary
     724         return new ClassSet<T>(PUB_CREDENTIAL_SET, c);
     725     }
     726
     727     /**
     728      * Return a {@code Set} of private credentials associated with this
     729      * {@code Subject} that are instances or subclasses of the specified
     730      * {@code Class}.
     731      *
     732      * <p> If a security manager is installed, the caller must have a
     733      * {@link PrivateCredentialPermission} to access all of the requested
     734      * Credentials, or a {@code SecurityException} will be thrown.
     735      *
     736      * <p> The returned {@code Set} is not backed by this Subject's
     737      * internal private Credential {@code Set}.  A new
     738      * {@code Set} is created and returned for each method invocation.
     739      * Modifications to the returned {@code Set}
     740      * will not affect the internal private Credential {@code Set}.
     741      *
     742      * @param <T> the type of the class modeled by {@code c}
     743      *
     744      * @param c the returned {@code Set} of private credentials will all be
     745      *          instances of this class.
     746      *
     747      * @return a {@code Set} of private credentials that are instances
     748      *          of the  specified {@code Class}.
     749      *
     750      * @throws NullPointerException if the specified {@code Class}
     751      *          is {@code null}.
     752      */
     753     public <T> Set<T> getPrivateCredentials(Class<T> c) {
     754
     755         // XXX
     756         // we do not need a security check for
     757         // AuthPermission(getPrivateCredentials)
     758         // because we already restrict access to private credentials
     759         // via the PrivateCredentialPermission.  all the extra AuthPermission
     760         // would do is protect the set operations themselves
     761         // (like size()), which don't seem security-sensitive.
     762
     763         Objects.requireNonNull(c,
     764                 ResourcesMgr.getString("invalid.null.Class.provided"));
     765
     766         // always return an empty Set instead of null
     767         // so LoginModules can add to the Set if necessary
     768         return new ClassSet<T>(PRIV_CREDENTIAL_SET, c);
     769     }
     770
     771     /**
     772      * Compares the specified Object with this {@code Subject}
     773      * for equality.  Returns true if the given object is also a Subject
     774      * and the two {@code Subject} instances are equivalent.
     775      * More formally, two {@code Subject} instances are
     776      * equal if their {@code Principal} and {@code Credential}
     777      * Sets are equal.
     778      *
     779      * @param o Object to be compared for equality with this
     780      *          {@code Subject}.
     781      *
     782      * @return true if the specified Object is equal to this
     783      *          {@code Subject}.
     784      *
     785      * @throws SecurityException if a security manager is installed and the
     786      *         caller does not have a {@link PrivateCredentialPermission}
     787      *         permission to access the private credentials for this
     788      *         {@code Subject} or the provided {@code Subject}.
     789      */
     790     @Override
     791     public boolean equals(Object o) {
     792
     793         if (o == null) {
     794             return false;
     795         }
     796
     797         if (this == o) {
     798             return true;
     799         }
     800
     801         if (o instanceof Subject) {
     802
     803             final Subject that = (Subject)o;
     804
     805             // check the principal and credential sets
     806             Set<Principal> thatPrincipals;
     807             synchronized(that.principals) {
     808                 // avoid deadlock from dual locks
     809                 thatPrincipals = new HashSet<>(that.principals);
     810             }
     811             if (!principals.equals(thatPrincipals)) {
     812                 return false;
     813             }
     814
     815             Set<Object> thatPubCredentials;
     816             synchronized(that.pubCredentials) {
     817                 // avoid deadlock from dual locks
     818                 thatPubCredentials = new HashSet<>(that.pubCredentials);
     819             }
     820             if (!pubCredentials.equals(thatPubCredentials)) {
     821                 return false;
     822             }
     823
     824             Set<Object> thatPrivCredentials;
     825             synchronized(that.privCredentials) {
     826                 // avoid deadlock from dual locks
     827                 thatPrivCredentials = new HashSet<>(that.privCredentials);
     828             }
     829             if (!privCredentials.equals(thatPrivCredentials)) {
     830                 return false;
     831             }
     832             return true;
     833         }
     834         return false;
     835     }
     836
     837     /**
     838      * Return the String representation of this {@code Subject}.
     839      *
     840      * @return the String representation of this {@code Subject}.
     841      */
     842     @Override
     843     public String toString() {
     844         return toString(true);
     845     }
     846
     847     /**
     848      * package private convenience method to print out the Subject
     849      * without firing off a security check when trying to access
     850      * the Private Credentials
     851      */
     852     String toString(boolean includePrivateCredentials) {
     853
     854         String s = ResourcesMgr.getString("Subject.");
     855         String suffix = "";
     856
     857         synchronized(principals) {
     858             Iterator<Principal> pI = principals.iterator();
     859             while (pI.hasNext()) {
     860                 Principal p = pI.next();
     861                 suffix = suffix + ResourcesMgr.getString(".Principal.") +
     862                         p.toString() + ResourcesMgr.getString("NEWLINE");
     863             }
     864         }
     865
     866         synchronized(pubCredentials) {
     867             Iterator<Object> pI = pubCredentials.iterator();
     868             while (pI.hasNext()) {
     869                 Object o = pI.next();
     870                 suffix = suffix +
     871                         ResourcesMgr.getString(".Public.Credential.") +
     872                         o.toString() + ResourcesMgr.getString("NEWLINE");
     873             }
     874         }
     875
     876         if (includePrivateCredentials) {
     877             synchronized(privCredentials) {
     878                 Iterator<Object> pI = privCredentials.iterator();
     879                 while (pI.hasNext()) {
     880                     try {
     881                         Object o = pI.next();
     882                         suffix += ResourcesMgr.getString
     883                                         (".Private.Credential.") +
     884                                         o.toString() +
     885                                         ResourcesMgr.getString("NEWLINE");
     886                     } catch (SecurityException se) {
     887                         suffix += ResourcesMgr.getString
     888                                 (".Private.Credential.inaccessible.");
     889                         break;
     890                     }
     891                 }
     892             }
     893         }
     894         return s + suffix;
     895     }
     896
     897     /**
     898      * Returns a hashcode for this {@code Subject}.
     899      *
     900      * @return a hashcode for this {@code Subject}.
     901      *
     902      * @throws SecurityException if a security manager is installed and the
     903      *         caller does not have a {@link PrivateCredentialPermission}
     904      *         permission to access this Subject's private credentials.
     905      */
     906     @Override
     907     public int hashCode() {
     908
     909         /**
     910          * The hashcode is derived exclusive or-ing the
     911          * hashcodes of this Subject's Principals and credentials.
     912          *
     913          * If a particular credential was destroyed
     914          * ({@code credential.hashCode()} throws an
     915          * {@code IllegalStateException}),
     916          * the hashcode for that credential is derived via:
     917          * {@code credential.getClass().toString().hashCode()}.
     918          */
     919
     920         int hashCode = 0;
     921
     922         synchronized(principals) {
     923             Iterator<Principal> pIterator = principals.iterator();
     924             while (pIterator.hasNext()) {
     925                 Principal p = pIterator.next();
     926                 hashCode ^= p.hashCode();
     927             }
     928         }
     929
     930         synchronized(pubCredentials) {
     931             Iterator<Object> pubCIterator = pubCredentials.iterator();
     932             while (pubCIterator.hasNext()) {
     933                 hashCode ^= getCredHashCode(pubCIterator.next());
     934             }
     935         }
     936         return hashCode;
     937     }
     938
     939     /**
     940      * get a credential's hashcode
     941      */
     942     private int getCredHashCode(Object o) {
     943         try {
     944             return o.hashCode();
     945         } catch (IllegalStateException ise) {
     946             return o.getClass().toString().hashCode();
     947         }
     948     }
     949
     950     /**
     951      * Writes this object out to a stream (i.e., serializes it).
     952      */
     953     @java.io.Serial
     954     private void writeObject(java.io.ObjectOutputStream oos)
     955                 throws java.io.IOException {
     956         synchronized(principals) {
     957             oos.defaultWriteObject();
     958         }
     959     }
     960
     961     /**
     962      * Reads this object from a stream (i.e., deserializes it)
     963      */
     964     @SuppressWarnings("unchecked")
     965     @java.io.Serial
     966     private void readObject(java.io.ObjectInputStream s)
     967                 throws java.io.IOException, ClassNotFoundException {
     968
     969         ObjectInputStream.GetField gf = s.readFields();
     970
     971         readOnly = gf.get("readOnly", false);
     972
     973         Set<Principal> inputPrincs = (Set<Principal>)gf.get("principals", null);
     974
     975         Objects.requireNonNull(inputPrincs,
     976                 ResourcesMgr.getString("invalid.null.input.s."));
     977
     978         // Rewrap the principals into a SecureSet
     979         try {
     980             LinkedList<Principal> principalList = collectionNullClean(inputPrincs);
     981             principals = Collections.synchronizedSet(new SecureSet<>
     982                                 (this, PRINCIPAL_SET, principalList));
     983         } catch (NullPointerException npe) {
     984             // Sometimes people deserialize the principals set only.
     985             // Subject is not accessible, so just don't fail.
     986             principals = Collections.synchronizedSet
     987                         (new SecureSet<>(this, PRINCIPAL_SET));
     988         }
     989
     990         // The Credential {@code Set} is not serialized, but we do not
     991         // want the default deserialization routine to set it to null.
     992         this.pubCredentials = Collections.synchronizedSet
     993                         (new SecureSet<>(this, PUB_CREDENTIAL_SET));
     994         this.privCredentials = Collections.synchronizedSet
     995                         (new SecureSet<>(this, PRIV_CREDENTIAL_SET));
     996     }
     997
     998     /**
     999      * Tests for null-clean collections (both non-null reference and
    1000      * no null elements)
    1001      *
    1002      * @param coll A {@code Collection} to be tested for null references
    1003      *
    1004      * @throws NullPointerException if the specified collection is either
    1005      *            {@code null} or contains a {@code null} element
    1006      */
    1007     private static <E> LinkedList<E> collectionNullClean(
    1008             Collection<? extends E> coll) {
    1009
    1010         Objects.requireNonNull(coll,
    1011                 ResourcesMgr.getString("invalid.null.input.s."));
    1012
    1013         LinkedList<E> output = new LinkedList<>();
    1014         for (E e : coll) {
    1015             output.add(Objects.requireNonNull(e,
    1016                     ResourcesMgr.getString("invalid.null.input.s.")));
    1017         }
    1018         return output;
    1019     }
    1020
    1021     /**
    1022      * Prevent modifications unless caller has permission.
    1023      *
    1024      * @serial include
    1025      */
    1026     private static class SecureSet<E>
    1027         implements Set<E>, java.io.Serializable {
    1028
    1029         @java.io.Serial
    1030         private static final long serialVersionUID = 7911754171111800359L;
    1031
    1032         /**
    1033          * @serialField this$0 Subject The outer Subject instance.
    1034          * @serialField elements LinkedList The elements in this set.
    1035          */
    1036         @java.io.Serial
    1037         private static final ObjectStreamField[] serialPersistentFields = {
    1038             new ObjectStreamField("this$0", Subject.class),
    1039             new ObjectStreamField("elements", LinkedList.class),
    1040             new ObjectStreamField("which", int.class)
    1041         };
    1042
    1043         Subject subject;
    1044         LinkedList<E> elements;
    1045
    1046         /**
    1047          * @serial An integer identifying the type of objects contained
    1048          *      in this set.  If {@code which == 1},
    1049          *      this is a Principal set and all the elements are
    1050          *      of type {@code java.security.Principal}.
    1051          *      If {@code which == 2}, this is a public credential
    1052          *      set and all the elements are of type {@code Object}.
    1053          *      If {@code which == 3}, this is a private credential
    1054          *      set and all the elements are of type {@code Object}.
    1055          */
    1056         private int which;
    1057
    1058         SecureSet(Subject subject, int which) {
    1059             this.subject = subject;
    1060             this.which = which;
    1061             this.elements = new LinkedList<E>();
    1062         }
    1063
    1064         SecureSet(Subject subject, int which, LinkedList<E> list) {
    1065             this.subject = subject;
    1066             this.which = which;
    1067             this.elements = list;
    1068         }
    1069
    1070         public int size() {
    1071             return elements.size();
    1072         }
    1073
    1074         public Iterator<E> iterator() {
    1075             final LinkedList<E> list = elements;
    1076             return new Iterator<E>() {
    1077                 ListIterator<E> i = list.listIterator(0);
    1078
    1079                 public boolean hasNext() {return i.hasNext();}
    1080
    1081                 public E next() {
    1082                     if (which != Subject.PRIV_CREDENTIAL_SET) {
    1083                         return i.next();
    1084                     }
    1085
    1086                     SecurityManager sm = System.getSecurityManager();
    1087                     if (sm != null) {
    1088                         try {
    1089                             sm.checkPermission(new PrivateCredentialPermission
    1090                                 (list.get(i.nextIndex()).getClass().getName(),
    1091                                 subject.getPrincipals()));
    1092                         } catch (SecurityException se) {
    1093                             i.next();
    1094                             throw (se);
    1095                         }
    1096                     }
    1097                     return i.next();
    1098                 }
    1099
    1100                 public void remove() {
    1101
    1102                     if (subject.isReadOnly()) {
    1103                         throw new IllegalStateException(ResourcesMgr.getString
    1104                                 ("Subject.is.read.only"));
    1105                     }
    1106
    1107                     java.lang.SecurityManager sm = System.getSecurityManager();
    1108                     if (sm != null) {
    1109                         switch (which) {
    1110                         case Subject.PRINCIPAL_SET:
    1111                             sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION);
    1112                             break;
    1113                         case Subject.PUB_CREDENTIAL_SET:
    1114                             sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION);
    1115                             break;
    1116                         default:
    1117                             sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION);
    1118                             break;
    1119                         }
    1120                     }
    1121                     i.remove();
    1122                 }
    1123             };
    1124         }
    1125
    1126         public boolean add(E o) {
    1127
    1128             Objects.requireNonNull(o,
    1129                     ResourcesMgr.getString("invalid.null.input.s."));
    1130
    1131             if (subject.isReadOnly()) {
    1132                 throw new IllegalStateException
    1133                         (ResourcesMgr.getString("Subject.is.read.only"));
    1134             }
    1135
    1136             java.lang.SecurityManager sm = System.getSecurityManager();
    1137             if (sm != null) {
    1138                 switch (which) {
    1139                 case Subject.PRINCIPAL_SET:
    1140                     sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION);
    1141                     break;
    1142                 case Subject.PUB_CREDENTIAL_SET:
    1143                     sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION);
    1144                     break;
    1145                 default:
    1146                     sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION);
    1147                     break;
    1148                 }
    1149             }
    1150
    1151             switch (which) {
    1152             case Subject.PRINCIPAL_SET:
    1153                 if (!(o instanceof Principal)) {
    1154                     throw new SecurityException(ResourcesMgr.getString
    1155                         ("attempting.to.add.an.object.which.is.not.an.instance.of.java.security.Principal.to.a.Subject.s.Principal.Set"));
    1156                 }
    1157                 break;
    1158             default:
    1159                 // ok to add Objects of any kind to credential sets
    1160                 break;
    1161             }
    1162
    1163             // check for duplicates
    1164             if (!elements.contains(o))
    1165                 return elements.add(o);
    1166             else {
    1167                 return false;
    1168         }
    1169         }
    1170
    1171         public boolean remove(Object o) {
    1172
    1173             Objects.requireNonNull(o,
    1174                     ResourcesMgr.getString("invalid.null.input.s."));
    1175
    1176             final Iterator<E> e = iterator();
    1177             while (e.hasNext()) {
    1178                 E next;
    1179                 if (which != Subject.PRIV_CREDENTIAL_SET) {
    1180                     next = e.next();
    1181                 } else {
    1182                     next = java.security.AccessController.doPrivileged
    1183                         (new java.security.PrivilegedAction<E>() {
    1184                         public E run() {
    1185                             return e.next();
    1186                         }
    1187                     });
    1188                 }
    1189
    1190                 if (next.equals(o)) {
    1191                     e.remove();
    1192                     return true;
    1193                 }
    1194             }
    1195             return false;
    1196         }
    1197
    1198         public boolean contains(Object o) {
    1199
    1200             Objects.requireNonNull(o,
    1201                     ResourcesMgr.getString("invalid.null.input.s."));
    1202
    1203             final Iterator<E> e = iterator();
    1204             while (e.hasNext()) {
    1205                 E next;
    1206                 if (which != Subject.PRIV_CREDENTIAL_SET) {
    1207                     next = e.next();
    1208                 } else {
    1209
    1210                     // For private credentials:
    1211                     // If the caller does not have read permission for
    1212                     // for o.getClass(), we throw a SecurityException.
    1213                     // Otherwise we check the private cred set to see whether
    1214                     // it contains the Object
    1215
    1216                     SecurityManager sm = System.getSecurityManager();
    1217                     if (sm != null) {
    1218                         sm.checkPermission(new PrivateCredentialPermission
    1219                                                 (o.getClass().getName(),
    1220                                                 subject.getPrincipals()));
    1221                     }
    1222                     next = java.security.AccessController.doPrivileged
    1223                         (new java.security.PrivilegedAction<E>() {
    1224                         public E run() {
    1225                             return e.next();
    1226                         }
    1227                     });
    1228                 }
    1229
    1230                 if (next.equals(o)) {
    1231                     return true;
    1232                 }
    1233             }
    1234             return false;
    1235         }
    1236
    1237         public boolean addAll(Collection<? extends E> c) {
    1238             boolean result = false;
    1239
    1240             c = collectionNullClean(c);
    1241
    1242             for (E item : c) {
    1243                 result |= this.add(item);
    1244             }
    1245
    1246             return result;
    1247         }
    1248
    1249         public boolean removeAll(Collection<?> c) {
    1250             c = collectionNullClean(c);
    1251
    1252             boolean modified = false;
    1253             final Iterator<E> e = iterator();
    1254             while (e.hasNext()) {
    1255                 E next;
    1256                 if (which != Subject.PRIV_CREDENTIAL_SET) {
    1257                     next = e.next();
    1258                 } else {
    1259                     next = java.security.AccessController.doPrivileged
    1260                         (new java.security.PrivilegedAction<E>() {
    1261                         public E run() {
    1262                             return e.next();
    1263                         }
    1264                     });
    1265                 }
    1266
    1267                 Iterator<?> ce = c.iterator();
    1268                 while (ce.hasNext()) {
    1269                     if (next.equals(ce.next())) {
    1270                             e.remove();
    1271                             modified = true;
    1272                             break;
    1273                         }
    1274                 }
    1275             }
    1276             return modified;
    1277         }
    1278
    1279         public boolean containsAll(Collection<?> c) {
    1280             c = collectionNullClean(c);
    1281
    1282             for (Object item : c) {
    1283                 if (this.contains(item) == false) {
    1284                     return false;
    1285                 }
    1286             }
    1287
    1288             return true;
    1289         }
    1290
    1291         public boolean retainAll(Collection<?> c) {
    1292             c = collectionNullClean(c);
    1293
    1294             boolean modified = false;
    1295             final Iterator<E> e = iterator();
    1296             while (e.hasNext()) {
    1297                 E next;
    1298                 if (which != Subject.PRIV_CREDENTIAL_SET) {
    1299                     next = e.next();
    1300                 } else {
    1301                     next = java.security.AccessController.doPrivileged
    1302                         (new java.security.PrivilegedAction<E>() {
    1303                         public E run() {
    1304                             return e.next();
    1305                         }
    1306                     });
    1307                 }
    1308
    1309                 if (c.contains(next) == false) {
    1310                     e.remove();
    1311                     modified = true;
    1312                 }
    1313             }
    1314
    1315             return modified;
    1316         }
    1317
    1318         public void clear() {
    1319             final Iterator<E> e = iterator();
    1320             while (e.hasNext()) {
    1321                 E next;
    1322                 if (which != Subject.PRIV_CREDENTIAL_SET) {
    1323                     next = e.next();
    1324                 } else {
    1325                     next = java.security.AccessController.doPrivileged
    1326                         (new java.security.PrivilegedAction<E>() {
    1327                         public E run() {
    1328                             return e.next();
    1329                         }
    1330                     });
    1331                 }
    1332                 e.remove();
    1333             }
    1334         }
    1335
    1336         public boolean isEmpty() {
    1337             return elements.isEmpty();
    1338         }
    1339
    1340         public Object[] toArray() {
    1341             final Iterator<E> e = iterator();
    1342             while (e.hasNext()) {
    1343                 // The next() method performs a security manager check
    1344                 // on each element in the SecureSet.  If we make it all
    1345                 // the way through we should be able to simply return
    1346                 // element's toArray results.  Otherwise we'll let
    1347                 // the SecurityException pass up the call stack.
    1348                 e.next();
    1349             }
    1350
    1351             return elements.toArray();
    1352         }
    1353
    1354         public <T> T[] toArray(T[] a) {
    1355             final Iterator<E> e = iterator();
    1356             while (e.hasNext()) {
    1357                 // The next() method performs a security manager check
    1358                 // on each element in the SecureSet.  If we make it all
    1359                 // the way through we should be able to simply return
    1360                 // element's toArray results.  Otherwise we'll let
    1361                 // the SecurityException pass up the call stack.
    1362                 e.next();
    1363             }
    1364
    1365             return elements.toArray(a);
    1366         }
    1367
    1368         public boolean equals(Object o) {
    1369             if (o == this) {
    1370                 return true;
    1371             }
    1372
    1373             if (!(o instanceof Set)) {
    1374                 return false;
    1375             }
    1376
    1377             Collection<?> c = (Collection<?>) o;
    1378             if (c.size() != size()) {
    1379                 return false;
    1380             }
    1381
    1382             try {
    1383                 return containsAll(c);
    1384             } catch (ClassCastException unused)   {
    1385                 return false;
    1386             } catch (NullPointerException unused) {
    1387                 return false;
    1388             }
    1389         }
    1390
    1391         public int hashCode() {
    1392             int h = 0;
    1393             Iterator<E> i = iterator();
    1394             while (i.hasNext()) {
    1395                 E obj = i.next();
    1396                 if (obj != null) {
    1397                     h += obj.hashCode();
    1398                 }
    1399             }
    1400             return h;
    1401         }
    1402
    1403         /**
    1404          * Writes this object out to a stream (i.e., serializes it).
    1405          *
    1406          * @serialData If this is a private credential set,
    1407          *      a security check is performed to ensure that
    1408          *      the caller has permission to access each credential
    1409          *      in the set.  If the security check passes,
    1410          *      the set is serialized.
    1411          */
    1412         @java.io.Serial
    1413         private void writeObject(java.io.ObjectOutputStream oos)
    1414                 throws java.io.IOException {
    1415
    1416             if (which == Subject.PRIV_CREDENTIAL_SET) {
    1417                 // check permissions before serializing
    1418                 Iterator<E> i = iterator();
    1419                 while (i.hasNext()) {
    1420                     i.next();
    1421                 }
    1422             }
    1423             ObjectOutputStream.PutField fields = oos.putFields();
    1424             fields.put("this$0", subject);
    1425             fields.put("elements", elements);
    1426             fields.put("which", which);
    1427             oos.writeFields();
    1428         }
    1429
    1430         @SuppressWarnings("unchecked")
    1431         @java.io.Serial
    1432         private void readObject(ObjectInputStream ois)
    1433             throws IOException, ClassNotFoundException
    1434         {
    1435             ObjectInputStream.GetField fields = ois.readFields();
    1436             subject = (Subject) fields.get("this$0", null);
    1437             which = fields.get("which", 0);
    1438
    1439             LinkedList<E> tmp = (LinkedList<E>) fields.get("elements", null);
    1440
    1441             elements = Subject.collectionNullClean(tmp);
    1442         }
    1443
    1444     }
    1445
    1446     /**
    1447      * This class implements a {@code Set} which returns only
    1448      * members that are an instance of a specified Class.
    1449      */
    1450     private class ClassSet<T> extends AbstractSet<T> {
    1451
    1452         private int which;
    1453         private Class<T> c;
    1454         private Set<T> set;
    1455
    1456         ClassSet(int which, Class<T> c) {
    1457             this.which = which;
    1458             this.c = c;
    1459             set = new HashSet<T>();
    1460
    1461             switch (which) {
    1462             case Subject.PRINCIPAL_SET:
    1463                 synchronized(principals) { populateSet(); }
    1464                 break;
    1465             case Subject.PUB_CREDENTIAL_SET:
    1466                 synchronized(pubCredentials) { populateSet(); }
    1467                 break;
    1468             default:
    1469                 synchronized(privCredentials) { populateSet(); }
    1470                 break;
    1471             }
    1472         }
    1473
    1474         @SuppressWarnings("unchecked")     /*To suppress warning from line 1374*/
    1475         private void populateSet() {
    1476             final Iterator<?> iterator;
    1477             switch(which) {
    1478             case Subject.PRINCIPAL_SET:
    1479                 iterator = Subject.this.principals.iterator();
    1480                 break;
    1481             case Subject.PUB_CREDENTIAL_SET:
    1482                 iterator = Subject.this.pubCredentials.iterator();
    1483                 break;
    1484             default:
    1485                 iterator = Subject.this.privCredentials.iterator();
    1486                 break;
    1487             }
    1488
    1489             // Check whether the caller has permisson to get
    1490             // credentials of Class c
    1491
    1492             while (iterator.hasNext()) {
    1493                 Object next;
    1494                 if (which == Subject.PRIV_CREDENTIAL_SET) {
    1495                     next = java.security.AccessController.doPrivileged
    1496                         (new java.security.PrivilegedAction<>() {
    1497                         public Object run() {
    1498                             return iterator.next();
    1499                         }
    1500                     });
    1501                 } else {
    1502                     next = iterator.next();
    1503                 }
    1504                 if (c.isAssignableFrom(next.getClass())) {
    1505                     if (which != Subject.PRIV_CREDENTIAL_SET) {
    1506                         set.add((T)next);
    1507                     } else {
    1508                         // Check permission for private creds
    1509                         SecurityManager sm = System.getSecurityManager();
    1510                         if (sm != null) {
    1511                             sm.checkPermission(new PrivateCredentialPermission
    1512                                                 (next.getClass().getName(),
    1513                                                 Subject.this.getPrincipals()));
    1514                         }
    1515                         set.add((T)next);
    1516                     }
    1517                 }
    1518             }
    1519         }
    1520
    1521         @Override
    1522         public int size() {
    1523             return set.size();
    1524         }
    1525
    1526         @Override
    1527         public Iterator<T> iterator() {
    1528             return set.iterator();
    1529         }
    1530
    1531         @Override
    1532         public boolean add(T o) {
    1533
    1534             if (!c.isAssignableFrom(o.getClass())) {
    1535                 MessageFormat form = new MessageFormat(ResourcesMgr.getString
    1536                         ("attempting.to.add.an.object.which.is.not.an.instance.of.class"));
    1537                 Object[] source = {c.toString()};
    1538                 throw new SecurityException(form.format(source));
    1539             }
    1540
    1541             return set.add(o);
    1542         }
    1543     }
    1544
    1545     static final class AuthPermissionHolder {
    1546         static final AuthPermission DO_AS_PERMISSION =
    1547             new AuthPermission("doAs");
    1548
    1549         static final AuthPermission DO_AS_PRIVILEGED_PERMISSION =
    1550             new AuthPermission("doAsPrivileged");
    1551
    1552         static final AuthPermission SET_READ_ONLY_PERMISSION =
    1553             new AuthPermission("setReadOnly");
    1554
    1555         static final AuthPermission GET_SUBJECT_PERMISSION =
    1556             new AuthPermission("getSubject");
    1557
    1558         static final AuthPermission MODIFY_PRINCIPALS_PERMISSION =
    1559             new AuthPermission("modifyPrincipals");
    1560
    1561         static final AuthPermission MODIFY_PUBLIC_CREDENTIALS_PERMISSION =
    1562             new AuthPermission("modifyPublicCredentials");
    1563
    1564         static final AuthPermission MODIFY_PRIVATE_CREDENTIALS_PERMISSION =
    1565             new AuthPermission("modifyPrivateCredentials");
    1566     }
    1567 }