Search in sources :

Example 71 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class Transport method serviceCall.

/**
     * Service an incoming remote call. When a message arrives on the
     * connection indicating the beginning of a remote call, the
     * threads are required to call the <I>serviceCall</I> method of
     * their transport.  The default implementation of this method
     * locates and calls the dispatcher object.  Ordinarily a
     * transport implementation will not need to override this method.
     * At the entry to <I>tr.serviceCall(conn)</I>, the connection's
     * input stream is positioned at the start of the incoming
     * message.  The <I>serviceCall</I> method processes the incoming
     * remote invocation and sends the result on the connection's
     * output stream.  If it returns "true", then the remote
     * invocation was processed without error and the transport can
     * cache the connection.  If it returns "false", a protocol error
     * occurred during the call, and the transport should destroy the
     * connection.
     */
public boolean serviceCall(final RemoteCall call) {
    try {
        /* read object id */
        final Remote impl;
        ObjID id;
        try {
            id = ObjID.read(call.getInputStream());
        } catch (java.io.IOException e) {
            throw new MarshalException("unable to read objID", e);
        }
        /* get the remote object */
        Transport transport = id.equals(dgcID) ? null : this;
        Target target = ObjectTable.getTarget(new ObjectEndpoint(id, transport));
        if (target == null || (impl = target.getImpl()) == null) {
            throw new NoSuchObjectException("no such object in table");
        }
        final Dispatcher disp = target.getDispatcher();
        target.incrementCallCount();
        try {
            /* call the dispatcher */
            transportLog.log(Log.VERBOSE, "call dispatcher");
            final AccessControlContext acc = target.getAccessControlContext();
            ClassLoader ccl = target.getContextClassLoader();
            ClassLoader savedCcl = Thread.currentThread().getContextClassLoader();
            try {
                setContextClassLoader(ccl);
                currentTransport.set(this);
                try {
                    java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<Void>() {

                        public Void run() throws IOException {
                            checkAcceptPermission(acc);
                            disp.dispatch(impl, call);
                            return null;
                        }
                    }, acc);
                } catch (java.security.PrivilegedActionException pae) {
                    throw (IOException) pae.getException();
                }
            } finally {
                setContextClassLoader(savedCcl);
                currentTransport.set(null);
            }
        } catch (IOException ex) {
            transportLog.log(Log.BRIEF, "exception thrown by dispatcher: ", ex);
            return false;
        } finally {
            target.decrementCallCount();
        }
    } catch (RemoteException e) {
        // if calls are being logged, write out exception
        if (UnicastServerRef.callLog.isLoggable(Log.BRIEF)) {
            // include client host name if possible
            String clientHost = "";
            try {
                clientHost = "[" + RemoteServer.getClientHost() + "] ";
            } catch (ServerNotActiveException ex) {
            }
            String message = clientHost + "exception: ";
            UnicastServerRef.callLog.log(Log.BRIEF, message, e);
        }
        /* We will get a RemoteException if either a) the objID is
             * not readable, b) the target is not in the object table, or
             * c) the object is in the midst of being unexported (note:
             * NoSuchObjectException is thrown by the incrementCallCount
             * method if the object is being unexported).  Here it is
             * relatively safe to marshal an exception to the client
             * since the client will not have seen a return value yet.
             */
        try {
            ObjectOutput out = call.getResultStream(false);
            UnicastServerRef.clearStackTraces(e);
            out.writeObject(e);
            call.releaseOutputStream();
        } catch (IOException ie) {
            transportLog.log(Log.BRIEF, "exception thrown marshalling exception: ", ie);
            return false;
        }
    }
    return true;
}
Also used : MarshalException(java.rmi.MarshalException) ObjectOutput(java.io.ObjectOutput) Remote(java.rmi.Remote) IOException(java.io.IOException) IOException(java.io.IOException) Dispatcher(sun.rmi.server.Dispatcher) ServerNotActiveException(java.rmi.server.ServerNotActiveException) AccessControlContext(java.security.AccessControlContext) ObjID(java.rmi.server.ObjID) NoSuchObjectException(java.rmi.NoSuchObjectException) RemoteException(java.rmi.RemoteException)

Example 72 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class ConnectionAcceptor method checkConnectPermission.

/**
     * Checks if the current caller has sufficient privilege to make
     * a connection to the remote endpoint.
     * @exception SecurityException if caller is not allowed to use this
     * Channel.
     */
private void checkConnectPermission() throws SecurityException {
    SecurityManager security = System.getSecurityManager();
    if (security == null)
        return;
    if (security != cacheSecurityManager) {
        // The security manager changed: flush the cache
        okContext = null;
        authcache = new WeakHashMap<AccessControlContext, Reference<AccessControlContext>>();
        cacheSecurityManager = security;
    }
    AccessControlContext ctx = AccessController.getContext();
    // appears in the cache, bypass the checkConnect.
    if (okContext == null || !(okContext.equals(ctx) || authcache.containsKey(ctx))) {
        security.checkConnect(ep.getHost(), ep.getPort());
        authcache.put(ctx, new SoftReference<AccessControlContext>(ctx));
    // A WeakHashMap is transformed into a SoftHashSet by making
    // each value softly refer to its own key (Peter's idea).
    }
    okContext = ctx;
}
Also used : AccessControlContext(java.security.AccessControlContext) SoftReference(java.lang.ref.SoftReference) Reference(java.lang.ref.Reference)

Example 73 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class Krb5Context method initSecContext.

/**
     * Initiator context establishment call. This method may be
     * required to be called several times. A CONTINUE_NEEDED return
     * call indicates that more calls are needed after the next token
     * is received from the peer.
     *
     * @param is contains the token received from the peer. On the
     *  first call it will be ignored.
     * @return any token required to be sent to the peer
     *    It is responsibility of the caller
     *    to send the token to its peer for processing.
     * @exception GSSException
     */
public final byte[] initSecContext(InputStream is, int mechTokenSize) throws GSSException {
    byte[] retVal = null;
    InitialToken token = null;
    int errorCode = GSSException.FAILURE;
    if (DEBUG) {
        System.out.println("Entered Krb5Context.initSecContext with " + "state=" + printState(state));
    }
    if (!isInitiator()) {
        throw new GSSException(GSSException.FAILURE, -1, "initSecContext on an acceptor " + "GSSContext");
    }
    try {
        if (state == STATE_NEW) {
            state = STATE_IN_PROCESS;
            errorCode = GSSException.NO_CRED;
            if (myCred == null) {
                myCred = Krb5InitCredential.getInstance(caller, myName, GSSCredential.DEFAULT_LIFETIME);
            } else if (!myCred.isInitiatorCredential()) {
                throw new GSSException(errorCode, -1, "No TGT available");
            }
            myName = (Krb5NameElement) myCred.getName();
            Credentials tgt;
            final Krb5ProxyCredential second;
            if (myCred instanceof Krb5InitCredential) {
                second = null;
                tgt = ((Krb5InitCredential) myCred).getKrb5Credentials();
            } else {
                second = (Krb5ProxyCredential) myCred;
                tgt = second.self.getKrb5Credentials();
            }
            checkPermission(peerName.getKrb5PrincipalName().getName(), "initiate");
            /*
                     * If useSubjectCredsonly is true then
                     * we check whether we already have the ticket
                     * for this service in the Subject and reuse it
                     */
            final AccessControlContext acc = AccessController.getContext();
            if (GSSUtil.useSubjectCredsOnly(caller)) {
                KerberosTicket kerbTicket = null;
                try {
                    // get service ticket from caller's subject
                    kerbTicket = AccessController.doPrivileged(new PrivilegedExceptionAction<KerberosTicket>() {

                        public KerberosTicket run() throws Exception {
                            // instead of Krb5Util.getTicket
                            return Krb5Util.getTicket(GSSCaller.CALLER_UNKNOWN, // don't worry about the null
                            second == null ? myName.getKrb5PrincipalName().getName() : second.getName().getKrb5PrincipalName().getName(), peerName.getKrb5PrincipalName().getName(), acc);
                        }
                    });
                } catch (PrivilegedActionException e) {
                    if (DEBUG) {
                        System.out.println("Attempt to obtain service" + " ticket from the subject failed!");
                    }
                }
                if (kerbTicket != null) {
                    if (DEBUG) {
                        System.out.println("Found service ticket in " + "the subject" + kerbTicket);
                    }
                    // convert Ticket to serviceCreds
                    // XXX Should merge these two object types
                    // avoid converting back and forth
                    serviceCreds = Krb5Util.ticketToCreds(kerbTicket);
                }
            }
            if (serviceCreds == null) {
                // Subject or useSubjectCreds is false
                if (DEBUG) {
                    System.out.println("Service ticket not found in " + "the subject");
                }
                // Get Service ticket using the Kerberos protocols
                if (second == null) {
                    serviceCreds = Credentials.acquireServiceCreds(peerName.getKrb5PrincipalName().getName(), tgt);
                } else {
                    serviceCreds = Credentials.acquireS4U2proxyCreds(peerName.getKrb5PrincipalName().getName(), second.tkt, second.getName().getKrb5PrincipalName(), tgt);
                }
                if (GSSUtil.useSubjectCredsOnly(caller)) {
                    final Subject subject = AccessController.doPrivileged(new java.security.PrivilegedAction<Subject>() {

                        public Subject run() {
                            return (Subject.getSubject(acc));
                        }
                    });
                    if (subject != null && !subject.isReadOnly()) {
                        /*
                             * Store the service credentials as
                             * javax.security.auth.kerberos.KerberosTicket in
                             * the Subject. We could wait till the context is
                             * succesfully established; however it is easier
                             * to do here and there is no harm indoing it here.
                             */
                        final KerberosTicket kt = Krb5Util.credsToTicket(serviceCreds);
                        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {

                            public Void run() {
                                subject.getPrivateCredentials().add(kt);
                                return null;
                            }
                        });
                    } else {
                        // log it for debugging purpose
                        if (DEBUG) {
                            System.out.println("Subject is " + "readOnly;Kerberos Service " + "ticket not stored");
                        }
                    }
                }
            }
            errorCode = GSSException.FAILURE;
            token = new InitSecContextToken(this, tgt, serviceCreds);
            apReq = ((InitSecContextToken) token).getKrbApReq();
            retVal = token.encode();
            myCred = null;
            if (!getMutualAuthState()) {
                state = STATE_DONE;
            }
            if (DEBUG) {
                System.out.println("Created InitSecContextToken:\n" + new HexDumpEncoder().encodeBuffer(retVal));
            }
        } else if (state == STATE_IN_PROCESS) {
            // No need to write anything;
            // just validate the incoming token
            new AcceptSecContextToken(this, serviceCreds, apReq, is);
            serviceCreds = null;
            apReq = null;
            state = STATE_DONE;
        } else {
            // XXX Use logging API?
            if (DEBUG) {
                System.out.println(state);
            }
        }
    } catch (KrbException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        GSSException gssException = new GSSException(errorCode, -1, e.getMessage());
        gssException.initCause(e);
        throw gssException;
    } catch (IOException e) {
        GSSException gssException = new GSSException(errorCode, -1, e.getMessage());
        gssException.initCause(e);
        throw gssException;
    }
    return retVal;
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) Subject(javax.security.auth.Subject) AccessControlContext(java.security.AccessControlContext) HexDumpEncoder(sun.misc.HexDumpEncoder)

Example 74 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class Krb5InitCredential method getTgt.

// XXX call to this.destroy() should destroy the locally cached copy
// of krb5Credentials and then call super.destroy().
private static KerberosTicket getTgt(GSSCaller caller, Krb5NameElement name, int initLifetime) throws GSSException {
    final String clientPrincipal;
    /*
         * Find the TGT for the realm that the client is in. If the client
         * name is not available, then use the default realm.
         */
    if (name != null) {
        clientPrincipal = (name.getKrb5PrincipalName()).getName();
    } else {
        clientPrincipal = null;
    }
    final AccessControlContext acc = AccessController.getContext();
    try {
        final GSSCaller realCaller = (caller == GSSCaller.CALLER_UNKNOWN) ? GSSCaller.CALLER_INITIATE : caller;
        return AccessController.doPrivileged(new PrivilegedExceptionAction<KerberosTicket>() {

            public KerberosTicket run() throws Exception {
                // the first ticket for a principal and we use list.
                return Krb5Util.getTicket(realCaller, clientPrincipal, null, acc);
            }
        });
    } catch (PrivilegedActionException e) {
        GSSException ge = new GSSException(GSSException.NO_CRED, -1, "Attempt to obtain new INITIATE credentials failed!" + " (" + e.getMessage() + ")");
        ge.initCause(e.getException());
        throw ge;
    }
}
Also used : AccessControlContext(java.security.AccessControlContext) PrivilegedActionException(java.security.PrivilegedActionException) GSSCaller(sun.security.jgss.GSSCaller) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException)

Example 75 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class bug6795356 method main.

public static void main(String[] args) throws Exception {
    ProtectionDomain domain = new ProtectionDomain(null, null);
    AccessController.doPrivileged(new PrivilegedAction<Object>() {

        public Object run() {
            // this initialize ProxyLazyValues
            UIManager.getLookAndFeel();
            return null;
        }
    }, new AccessControlContext(new ProtectionDomain[] { domain }));
    weakRef = new WeakReference<ProtectionDomain>(domain);
    domain = null;
    Util.generateOOME();
    if (weakRef.get() != null) {
        throw new RuntimeException("Memory leak found!");
    }
    System.out.println("Test passed");
}
Also used : ProtectionDomain(java.security.ProtectionDomain) AccessControlContext(java.security.AccessControlContext)

Aggregations

AccessControlContext (java.security.AccessControlContext)100 ProtectionDomain (java.security.ProtectionDomain)24 Subject (javax.security.auth.Subject)24 PrivilegedAction (java.security.PrivilegedAction)18 Permissions (java.security.Permissions)14 PrivilegedActionException (java.security.PrivilegedActionException)13 IOException (java.io.IOException)11 SocketPermission (java.net.SocketPermission)10 Test (org.testng.annotations.Test)8 Principal (java.security.Principal)7 CodeSource (java.security.CodeSource)6 Permission (java.security.Permission)6 DatagramSocket (java.net.DatagramSocket)5 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)5 MulticastSocket (java.net.MulticastSocket)4 Set (java.util.Set)4 ExecutorService (java.util.concurrent.ExecutorService)4 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)4 ReflectionException (javax.management.ReflectionException)4 Test (org.junit.Test)4