Search in sources :

Example 1 with FailedLoginException

use of com.sun.messaging.jmq.auth.api.FailedLoginException in project openmq by eclipse-ee4j.

the class AuthHandler method handle.

/**
 * Method to handle Authentication messages
 */
@Override
public boolean handle(IMQConnection con, Packet msg) throws BrokerException {
    byte[] resp = null;
    ByteBuffer bbuf = msg.getMessageBodyByteBuffer();
    int size = bbuf.remaining();
    resp = new byte[size];
    bbuf.get(resp);
    String reason = null;
    AccessController ac = con.getAccessController();
    boolean isIndemp = msg.getIndempotent();
    byte[] req = null;
    int status = Status.ERROR;
    String username = null;
    if (con.isAuthenticated()) {
        if (!isIndemp) {
            // already authenticated
            reason = "already authenticated";
            logger.log(Logger.WARNING, "Received unexpected authentication " + con.getRemoteConnectionString() + ":" + con.getConnectionUID());
            status = Status.ERROR;
        } else {
            status = Status.OK;
        }
        resp = null;
    } else if (!con.setConnectionState(Connection.STATE_AUTH_RESPONSED)) {
        reason = "bad connection state";
        status = Status.UNAVAILABLE;
        resp = null;
    }
    if (resp != null) {
        try {
            req = ac.handleResponse(resp, msg.getSequence());
            status = Status.OK;
            // audit logging for successful authentication
            Globals.getAuditSession().authentication(con.getUserName(), con.remoteHostString(), true);
            if (req == null) {
                IMQService s = (IMQService) con.getService();
                String stype = ServiceType.getServiceTypeString(s.getServiceType());
                try {
                    AuthCacheData acd = s.getAuthCacheData();
                    acd.setCacheData(ac.getCacheData());
                    ac.checkConnectionPermission(s.getName(), stype);
                    // audit logging for connection authorization
                    Globals.getAuditSession().connectionAuth(con.getUserName(), con.remoteHostString(), stype, s.getName(), true);
                } catch (AccessControlException e) {
                    reason = "Forbidden";
                    status = Status.FORBIDDEN;
                    ac.logout();
                    logger.log(Logger.WARNING, Globals.getBrokerResources().getKString(BrokerResources.W_SERVICE_ACCESS_DENIED, s.getName(), stype) + " - " + e.getMessage(), e);
                    // audit logging for authentication failure
                    Globals.getAuditSession().connectionAuth(con.getUserName(), con.remoteHostString(), stype, s.getName(), false);
                    username = con.getUserName();
                }
            }
        } catch (FailedLoginException e) {
            // IMQService s = (IMQService)con.getService();
            Globals.getAuditSession().authentication(e.getUser(), con.remoteHostString(), false);
            username = e.getUser();
            status = Status.INVALID_LOGIN;
            reason = e.getMessage();
            logger.log(Logger.WARNING, BrokerResources.W_LOGIN_FAILED, e);
        } catch (OutOfMemoryError err) {
            // re-processed
            throw err;
        } catch (Throwable w) {
            status = Status.FORBIDDEN;
            reason = w.getMessage();
            logger.log(Logger.ERROR, w.getMessage(), w);
        }
    }
    // XXX - for now simple returns granted authenticate reply
    Packet pkt = new Packet(con.useDirectBuffers());
    pkt.setConsumerID(msg.getConsumerID());
    Hashtable hash = new Hashtable();
    if (reason != null) {
        hash.put("JMQReason", reason);
    }
    if (resp == null) {
        pkt.setPacketType(PacketType.AUTHENTICATE_REPLY);
        hash.put("JMQStatus", Integer.valueOf(status));
        pkt.setProperties(hash);
    } else {
        if (req != null) {
            if (!con.setConnectionState(Connection.STATE_AUTH_REQUESTED)) {
                status = Status.UNAVAILABLE;
                req = null;
            }
        }
        if (req == null) {
            if (status == Status.OK) {
                if (!con.setConnectionState(Connection.STATE_AUTHENTICATED)) {
                    status = Status.UNAVAILABLE;
                }
            }
            pkt.setPacketType(PacketType.AUTHENTICATE_REPLY);
            hash.put("JMQStatus", Integer.valueOf(status));
            if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
                hash.put("JMQReqID", msg.getSysMessageID().toString());
            }
            pkt.setProperties(hash);
        } else {
            pkt.setPacketType(PacketType.AUTHENTICATE_REQUEST);
            hash.put("JMQAuthType", ac.getAuthType());
            hash.put("JMQChallenge", Boolean.FALSE);
            if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
                hash.put("JMQReqID", msg.getSysMessageID().toString());
            }
            pkt.setProperties(hash);
            pkt.setMessageBody(req);
        }
    }
    con.sendControlMessage(pkt);
    if (status != Status.OK) {
        IMQService s = (IMQService) con.getService();
        Agent agent = Globals.getAgent();
        if (agent != null) {
            agent.notifyConnectionReject(s.getName(), username, con.remoteHostString());
        }
        con.closeConnection(true, GoodbyeReason.CON_FATAL_ERROR, Globals.getBrokerResources().getKString(BrokerResources.M_AUTH_FAIL_CLOSE));
    } else {
        Agent agent = Globals.getAgent();
        if (agent != null) {
            agent.registerConnection(con.getConnectionUID().longValue());
            agent.notifyConnectionOpen(con.getConnectionUID().longValue());
        }
    }
    return true;
}
Also used : Agent(com.sun.messaging.jmq.jmsserver.management.agent.Agent) AccessControlException(java.security.AccessControlException) IMQService(com.sun.messaging.jmq.jmsserver.service.imq.IMQService) AccessController(com.sun.messaging.jmq.jmsserver.auth.AccessController) AuthCacheData(com.sun.messaging.jmq.jmsserver.auth.AuthCacheData) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException)

Example 2 with FailedLoginException

use of com.sun.messaging.jmq.auth.api.FailedLoginException in project openmq by eclipse-ee4j.

the class HelloHandler method handle.

/**
 * Method to handle HELLO messages
 */
@Override
public boolean handle(IMQConnection con, Packet msg) throws BrokerException {
    if (DEBUG) {
        logger.log(Logger.DEBUGHIGH, "HelloHandler: handle() [ Received Hello Message]");
    }
    String reason = null;
    Hashtable hello_props = null;
    try {
        hello_props = msg.getProperties();
    } catch (Exception ex) {
        logger.logStack(Logger.WARNING, "HELLO Packet.getProperties()", ex);
        hello_props = new Hashtable();
    }
    boolean alreadyStarted = con.isStarted();
    boolean alreadyAuthenticated = con.isAuthenticated();
    int requestedProtocol = 0;
    int highestProtocol = con.getHighestSupportedProtocol();
    int lowestProtocol = PacketType.VERSION1;
    String expectedClusterID = null;
    UID expectedSessionID = null;
    ConnectionUID oldCID = null;
    Integer bufsize = null;
    String destprov = null;
    if (hello_props != null) {
        Integer level = (Integer) hello_props.get("JMQProtocolLevel");
        String clientv = (String) hello_props.get("JMQVersion");
        if (DEBUG) {
            logger.log(logger.INFO, "HelloHandler.handle(): Client[" + clientv + ", " + level + "] " + con);
        }
        if (level == null) {
            requestedProtocol = PacketType.VERSION1;
        } else {
            requestedProtocol = level.intValue();
        }
        bufsize = (Integer) hello_props.get("JMQSize");
        if (bufsize == null) {
            // XXX try old protocol
            bufsize = (Integer) hello_props.get("JMQRBufferSize");
        }
        // Retrieve HA related properties
        Long longUID = (Long) hello_props.get("JMQStoreSession");
        if (longUID != null) {
            expectedSessionID = new UID(longUID.longValue());
        }
        expectedClusterID = (String) hello_props.get("JMQClusterID");
        Boolean reconnectable = (Boolean) hello_props.get("JMQReconnectable");
        Boolean haclient = (Boolean) hello_props.get("JMQHAClient");
        if (Globals.getHAEnabled() && haclient != null && haclient.booleanValue()) {
            reconnectable = haclient;
        }
        String s = (String) hello_props.get("JMQUserAgent");
        if (s != null) {
            con.addClientData(IMQConnection.USER_AGENT, s);
        }
        // currently private property
        destprov = (String) hello_props.get("JMQDestinationProvider");
        longUID = (Long) hello_props.get("JMQConnectionID");
        if (longUID != null) {
            logger.log(Logger.DEBUG, "Have old connectionUID");
            oldCID = new ConnectionUID(longUID.longValue());
            logger.log(Logger.INFO, BrokerResources.I_RECONNECTING, oldCID);
            logger.log(Logger.DEBUG, "Checking for active connection");
            Connection oldcon = Globals.getConnectionManager().getConnection(oldCID);
            DUMP("Before connection Destroy");
            if (oldcon != null) {
                logger.log(Logger.DEBUG, "Destroying old connection " + oldCID);
                oldcon.destroyConnection(true, GoodbyeReason.ADMIN_KILLED_CON, "Destroying old connection with same connectionUID " + oldCID + " - reconnect is happening before connection was reaped");
            }
            /*
                 * LKS DUMP();
                 *
                 * logger.log(Logger.DEBUG,"Updating connection in id list " + "["+oldcid + "," + uid + "]"); // old code
                 * con.setConnectionUID(oldcid); Globals.getConnectionManager().updateConnectionUID( oldcid, uid);
                 * //Globals.getConnectionManager().updateConnectionUID( // uid, oldcid);
                 */
            DUMP("After Connection Destroy");
        }
        con.getConnectionUID().setCanReconnect(reconnectable != null && reconnectable.booleanValue());
        Long interval = (Long) hello_props.get("JMQInterval");
        // LKS - XXX just override for testing
        long itime = (interval == null ? ConnectionManager.DEFAULT_RECONNECT_INTERVAL : interval.longValue());
        con.setReconnectInterval(itime);
    } else {
        requestedProtocol = PacketType.VERSION1;
    }
    int supportedProtocol = 0;
    if (requestedProtocol > highestProtocol) {
        supportedProtocol = highestProtocol;
    } else if (requestedProtocol < lowestProtocol) {
        supportedProtocol = lowestProtocol;
    } else {
        supportedProtocol = requestedProtocol;
    }
    con.setClientProtocolVersion(supportedProtocol);
    if (bufsize != null) {
        logger.log(Logger.DEBUG, "Received JMQRBufferSize -" + bufsize);
        con.setFlowCount(bufsize.intValue());
    }
    Packet pkt = new Packet(con.useDirectBuffers());
    pkt.setPacketType(PacketType.HELLO_REPLY);
    pkt.setConsumerID(msg.getConsumerID());
    Hashtable hash = new Hashtable();
    reason = "unavailable";
    int status = Status.UNAVAILABLE;
    // protocol, then use the IP in the message packet.
    if (con.getRemoteIP() == null) {
        con.setRemoteIP(msg.getIP());
    }
    if ((alreadyAuthenticated || alreadyStarted) && !msg.getIndempotent()) {
        // handle ibit
        status = Status.ERROR;
        reason = "Connection reuse not allowed";
        if (alreadyAuthenticated) {
            logger.log(Logger.WARNING, "Internal Error: " + " received HELLO on already authenticated connection " + con.getRemoteConnectionString() + " " + con.getConnectionUID());
        } else {
            logger.log(Logger.WARNING, "Internal Error: " + " received HELLO on already started connection " + con.getRemoteConnectionString() + " " + con.getConnectionUID());
        }
    } else if (requestedProtocol != supportedProtocol) {
        // Bad protocol level.
        logger.log(Logger.WARNING, rb.W_BAD_PROTO_VERSION, Integer.toString(requestedProtocol), Integer.toString(supportedProtocol));
        reason = "bad version";
        status = Status.BAD_VERSION;
    } else if (con.getConnectionState() != Connection.STATE_UNAVAILABLE) {
        /**
         * connection may not be able to be created e.g: licensing, being destroyed (e.g due to timeout)
         */
        if (con.setConnectionState(Connection.STATE_INITIALIZED)) {
            reason = null;
            status = Status.OK;
        } else {
            status = Status.UNAVAILABLE;
        }
    } else {
        status = Status.UNAVAILABLE;
    }
    if (status == Status.OK && destprov != null) {
        if (((IMQService) con.getService()).getServiceType() == ServiceType.ADMIN) {
            status = Status.BAD_REQUEST;
            reason = "JMQDestinationProvider not supported on ADMIN service";
            logger.log(logger.WARNING, reason);
        } else if (!destprov.equals(CoreLifecycleSpi.GFMQ) && !destprov.equals(CoreLifecycleSpi.CHMP)) {
            status = Status.UNSUPPORTED_TYPE;
            reason = "Unsupported JMQDestinationProvider " + destprov;
            logger.log(logger.WARNING, reason);
        } else if (destprov.equals(CoreLifecycleSpi.CHMP) && Globals.getCorePlugin(destprov) == null) {
            status = Status.UNSUPPORTED_TYPE;
            reason = destprov + " not enabled";
            logger.log(logger.WARNING, reason);
        }
    }
    UID brokerSessionID = Globals.getBrokerSessionID();
    if (brokerSessionID != null) {
        hash.put("JMQBrokerSessionID", Long.valueOf(brokerSessionID.longValue()));
    }
    // OK, handle the HA properties HERE
    String clusterID = null;
    UID sessionUID = null;
    ClusterManager cfg = Globals.getClusterManager();
    if (cfg != null) {
        clusterID = cfg.getClusterId();
        sessionUID = cfg.getStoreSessionUID();
        hash.put("JMQHA", Boolean.valueOf(cfg.isHA()));
        if (clusterID != null) {
            hash.put("JMQClusterID", clusterID);
        }
        if (sessionUID != null && !Globals.getDestinationList().isPartitionMode()) {
            hash.put("JMQStoreSession", Long.valueOf(sessionUID.longValue()));
        }
        String list = null;
        Iterator itr = null;
        if (((IMQService) con.getService()).getServiceType() != ServiceType.ADMIN) {
            itr = cfg.getKnownBrokers(false);
        } else {
            itr = cfg.getKnownBrokers(true);
        }
        Set s = new HashSet();
        // ok get rid of dups
        while (itr.hasNext()) {
            ClusteredBroker cb = (ClusteredBroker) itr.next();
            s.add(cb.getBrokerURL().toString());
        }
        // OK .. now convert to a string
        itr = s.iterator();
        while (itr.hasNext()) {
            if (list == null) {
                list = itr.next().toString();
            } else {
                list += "," + itr.next().toString();
            }
        }
        if (list != null) {
            hash.put("JMQBrokerList", list);
        }
    }
    HAMonitorService hamonitor = Globals.getHAMonitorService();
    if (hamonitor != null && hamonitor.inTakeover()) {
        if (((IMQService) con.getService()).getServiceType() != ServiceType.ADMIN) {
            status = Status.TIMEOUT;
            if (oldCID != null) {
                logger.log(logger.INFO, BrokerResources.W_IN_TAKEOVER_RECONNECT_LATER, oldCID);
            } else {
                logger.log(logger.INFO, BrokerResources.W_IN_TAKEOVER_RECONNECT_LATER, con.getConnectionUID());
            }
        }
    }
    // first we want to deal with a bad clusterid
    if (clusterID != null && expectedClusterID != null && !clusterID.equals(expectedClusterID)) {
        status = Status.BAD_REQUEST;
    } else if (expectedSessionID != null && sessionUID != null && expectedSessionID.equals(sessionUID)) {
    // cool we connected to the right broker
    // we already have the right owner
    } else if (expectedSessionID != null) {
        if (cfg == null) {
            // not running any cluster config
            logger.log(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR, "Internal Error: Received session on" + " non-clustered broker");
            status = Status.NOT_FOUND;
        } else {
            // OK, if we are here, we need to locate the right
            // broker for the session
            // 
            // Here are the steps we need to check:
            // 1. does this broker support the sessionUID
            // if not
            // 2. can we locate another broker with the sessionUID
            // 
            ClusteredBroker owner = null;
            // 
            // OK, see if this was a session UID we took over at some
            // point in the past
            Set s = cfg.getSupportedStoreSessionUIDs();
            if (s.contains(expectedSessionID)) {
                // yep, we took it over
                owner = cfg.getLocalBroker();
            }
            if (owner == null) {
                // this broker isnt supprting the session
                // see if the database indicates someone else has it
                String ownerString = cfg.lookupStoreSessionOwner(expectedSessionID);
                if (ownerString != null) {
                    owner = cfg.getBroker(ownerString);
                }
            }
            try {
                if (owner != null) {
                    ClusteredBroker creator = null;
                    String creatorString = cfg.getStoreSessionCreator(expectedSessionID);
                    if (creatorString != null) {
                        creator = cfg.getBroker(creatorString);
                    }
                    int stat = owner.getStatus();
                    if (BrokerStatus.getBrokerInDoubt(stat) || !BrokerStatus.getBrokerLinkIsUp(stat) || owner.getState() == BrokerState.FAILOVER_STARTED) {
                        status = Status.TIMEOUT;
                        logger.log(logger.INFO, Globals.getBrokerResources().getKString(BrokerResources.I_RECONNECT_OWNER_INDOUBT, expectedSessionID, owner));
                    } else if (!owner.isLocalBroker()) {
                        status = Status.MOVED_PERMANENTLY;
                        hash.put("JMQStoreOwner", owner.getBrokerURL().toString());
                        logger.log(logger.INFO, Globals.getBrokerResources().getKString(BrokerResources.I_RECONNECT_OWNER_NOTME, expectedSessionID, owner));
                    } else if (creator == null) {
                        // XXX
                        status = Status.NOT_FOUND;
                        logger.log(logger.INFO, Globals.getBrokerResources().getKString(BrokerResources.I_RECONNECT_NOCREATOR, expectedSessionID));
                    } else if (creator.getState() == BrokerState.FAILOVER_STARTED) {
                        status = Status.TIMEOUT;
                        logger.log(logger.INFO, Globals.getBrokerResources().getKString(BrokerResources.I_RECONNECT_INTAKEOVER, expectedSessionID));
                    } else {
                        // local broker owns us - set owner for debugging only
                        // not required for protocol
                        hash.put("JMQStoreOwner", owner.getBrokerURL().toString());
                    }
                } else {
                    // didnt find owner
                    status = Status.NOT_FOUND;
                    logger.log(logger.INFO, Globals.getBrokerResources().getKString(BrokerResources.I_RECONNECT_OWNER_NOTFOUND, expectedSessionID));
                }
            } catch (Exception ex) {
                logger.log(Logger.WARNING, BrokerResources.W_RECONNECT_ERROR, expectedSessionID.toString(), ex);
                status = Status.NOT_FOUND;
            }
        }
    }
    if (!con.isAdminConnection() && Globals.getMemManager() != null) {
        hash.put("JMQSize", Integer.valueOf(Globals.getMemManager().getJMQSize()));
        hash.put("JMQBytes", Long.valueOf(Globals.getMemManager().getJMQBytes()));
        hash.put("JMQMaxMsgBytes", Long.valueOf(Globals.getMemManager().getJMQMaxMsgBytes()));
    }
    hash.put("JMQService", con.getService().getName());
    hash.put("JMQConnectionID", Long.valueOf(con.getConnectionUID().longValue()));
    hash.put("JMQProtocolLevel", Integer.valueOf(supportedProtocol));
    hash.put("JMQVersion", Globals.getVersion().getProductVersion());
    if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
        hash.put("JMQReqID", msg.getSysMessageID().toString());
    }
    try {
        sessionUID = con.attachStorePartition(expectedSessionID);
        if (Globals.getDestinationList().isPartitionMode()) {
            hash.put("JMQStoreSession", Long.valueOf(sessionUID.longValue()));
        }
    } catch (BrokerException e) {
        status = e.getStatusCode();
        reason = e.getMessage();
        if (status == Status.NOT_FOUND) {
            logger.log(logger.INFO, e.getMessage());
        } else {
            logger.logStack(logger.ERROR, e.getMessage(), e);
        }
    }
    hash.put("JMQStatus", Integer.valueOf(status));
    if (reason != null) {
        hash.put("JMQReason", reason);
    }
    pkt.setProperties(hash);
    con.sendControlMessage(pkt);
    // OK .. valid status messages are
    if (status != Status.OK && status != Status.MOVED_PERMANENTLY && status != Status.NOT_FOUND && status != Status.TIMEOUT) {
        // destroy the connection !!! (should be ok if destroy twice)
        con.closeConnection(true, GoodbyeReason.CON_FATAL_ERROR, Globals.getBrokerResources().getKString(BrokerResources.M_INIT_FAIL_CLOSE));
        connectionList.removeConnection(con.getConnectionUID(), false, GoodbyeReason.CON_FATAL_ERROR, Globals.getBrokerResources().getKString(BrokerResources.M_INIT_FAIL_CLOSE));
        return true;
    }
    status = Status.UNAVAILABLE;
    String authType = null;
    if (hello_props != null) {
        authType = (String) hello_props.get("JMQAuthType");
    }
    AccessController ac = con.getAccessController();
    pkt = new Packet(con.useDirectBuffers());
    pkt.setPacketType(PacketType.AUTHENTICATE_REQUEST);
    pkt.setConsumerID(msg.getConsumerID());
    hash = new Hashtable();
    hash.put("JMQSequence", Integer.valueOf(msg.getSequence()));
    hash.put("JMQChallenge", Boolean.TRUE);
    Properties props = new Properties();
    props.setProperty(Globals.IMQ + ".clientIP", msg.getIPString());
    props.setProperty(Globals.IMQ + ".connectionID", con.getConnectionUID().toString());
    byte[] req = null;
    try {
        AuthCacheData acd = ((IMQService) con.getService()).getAuthCacheData();
        req = ac.getChallenge(msg.getSequence(), props, acd.getCacheData(), authType);
        hash.put("JMQAuthType", ac.getAuthType());
        if (con.setConnectionState(Connection.STATE_AUTH_REQUESTED)) {
            status = Status.OK;
        }
    } catch (FailedLoginException e) {
        logger.log(Logger.WARNING, e.getMessage(), e);
        status = Status.FORBIDDEN;
    } catch (OutOfMemoryError err) {
        // packet is re-processed
        throw err;
    } catch (Throwable w) {
        logger.log(Logger.ERROR, Globals.getBrokerResources().getKString(BrokerResources.E_GET_CHALLENGE_FAILED) + " - " + w.getMessage(), w);
        status = Status.FORBIDDEN;
    }
    try {
        if (destprov != null && !destprov.equals(CoreLifecycleSpi.GFMQ)) {
            CoreLifecycleSpi clc = Globals.getCorePlugin(destprov);
            ((IMQBasicConnection) con).setPacketRouter(clc.getPacketRouter());
            con.setCoreLifecycle(clc);
        }
    } catch (Exception e) {
        status = Status.ERROR;
        logger.logStack(logger.ERROR, e.getMessage(), e);
    }
    hash.put("JMQStatus", Integer.valueOf(status));
    if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
        hash.put("JMQReqID", msg.getSysMessageID().toString());
    }
    pkt.setProperties(hash);
    if (req != null) {
        pkt.setMessageBody(req);
    }
    con.sendControlMessage(pkt);
    if (DEBUG) {
        logger.log(Logger.DEBUG, "HelloHandler: handle() [ sent challenge ]" + ":status=" + Status.getString(status));
    }
    if (status != Status.OK && status != Status.MOVED_PERMANENTLY && status != Status.NOT_FOUND && status != Status.TIMEOUT) {
        // destroy the connection !!! (should be ok if destroy twice)
        con.closeConnection(true, GoodbyeReason.CON_FATAL_ERROR, Globals.getBrokerResources().getKString(BrokerResources.M_INIT_FAIL_CLOSE));
        connectionList.removeConnection(con.getConnectionUID(), false, GoodbyeReason.CON_FATAL_ERROR, Globals.getBrokerResources().getKString(BrokerResources.M_INIT_FAIL_CLOSE));
    }
    return true;
}
Also used : BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) CoreLifecycleSpi(com.sun.messaging.jmq.jmsserver.plugin.spi.CoreLifecycleSpi) IMQService(com.sun.messaging.jmq.jmsserver.service.imq.IMQService) IMQBasicConnection(com.sun.messaging.jmq.jmsserver.service.imq.IMQBasicConnection) HAMonitorService(com.sun.messaging.jmq.jmsserver.cluster.api.ha.HAMonitorService) IMQBasicConnection(com.sun.messaging.jmq.jmsserver.service.imq.IMQBasicConnection) Connection(com.sun.messaging.jmq.jmsserver.service.Connection) IMQConnection(com.sun.messaging.jmq.jmsserver.service.imq.IMQConnection) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) ConnectionUID(com.sun.messaging.jmq.jmsserver.service.ConnectionUID) UID(com.sun.messaging.jmq.util.UID) AccessController(com.sun.messaging.jmq.jmsserver.auth.AccessController) AuthCacheData(com.sun.messaging.jmq.jmsserver.auth.AuthCacheData) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) ConnectionUID(com.sun.messaging.jmq.jmsserver.service.ConnectionUID)

Example 3 with FailedLoginException

use of com.sun.messaging.jmq.auth.api.FailedLoginException in project openmq by eclipse-ee4j.

the class JMQDigestAuthenticationHandler method handleResponse.

/**
 * @param authResponse the authentication response data. This is the AUTHENCATE packet body.
 * @param sequence packet sequence number
 *
 * @return next request data if any; null if no more request. The request data will be sent as packet body in
 * AUTHENTICATE_REQUEST
 */
@Override
public byte[] handleResponse(byte[] authResponse, int sequence) throws LoginException {
    Subject subject = null;
    ByteArrayInputStream bis = new ByteArrayInputStream(authResponse);
    DataInputStream dis = new DataInputStream(bis);
    try {
        String username = dis.readUTF();
        String credential = dis.readUTF();
        dis.close();
        String rep = authProps.getProperty(AccessController.PROP_AUTHENTICATION_PREFIX + getType() + AccessController.PROP_USER_REPOSITORY_SUFFIX);
        if (rep == null || rep.trim().equals("")) {
            throw new LoginException(Globals.getBrokerResources().getKString(BrokerResources.X_USER_REPOSITORY_NOT_DEFINED, getType()));
        }
        String cn = authProps.getProperty(AccessController.PROP_USER_REPOSITORY_PREFIX + rep + ".class");
        if (cn == null) {
            throw new LoginException(Globals.getBrokerResources().getKString(BrokerResources.X_USER_REPOSITORY_CLASS_NOT_DEFINED, rep, getType()));
        }
        UserRepository repository = (UserRepository) Class.forName(cn).getDeclaredConstructor().newInstance();
        repository.open(getType(), authProps, cacheData);
        subject = repository.findMatch(username, credential, nonce, getMatchType());
        cacheData = repository.getCacheData();
        repository.close();
        if (subject == null) {
            FailedLoginException ex = new FailedLoginException(Globals.getBrokerResources().getKString(BrokerResources.X_FORBIDDEN, username));
            ex.setUser(username);
            throw ex;
        }
        acc = new JMQAccessControlContext(new MQUser(username), subject, authProps);
        return null;
    } catch (ClassNotFoundException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "ClassNotFoundException: " + e.getMessage()));
    } catch (IOException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "IOException: " + e.getMessage()));
    } catch (InstantiationException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "InstantiationException: " + e.getMessage()));
    } catch (IllegalAccessException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "IllegalAccessException: " + e.getMessage()));
    } catch (ClassCastException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "cLassCastException: " + e.getMessage()));
    } catch (NoSuchMethodException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "NoSuchMethodException: " + e.getMessage()));
    } catch (InvocationTargetException e) {
        throw new LoginException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "InvocationTargetException: " + e.getMessage()));
    }
}
Also used : MQUser(com.sun.messaging.jmq.auth.jaas.MQUser) Subject(javax.security.auth.Subject) InvocationTargetException(java.lang.reflect.InvocationTargetException) UserRepository(com.sun.messaging.jmq.auth.api.server.model.UserRepository) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) LoginException(javax.security.auth.login.LoginException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException)

Example 4 with FailedLoginException

use of com.sun.messaging.jmq.auth.api.FailedLoginException in project openmq by eclipse-ee4j.

the class LdapUserRepository method jmqbasicFindMatch.

private Subject jmqbasicFindMatch(String user, String userpwd) throws LoginException {
    if (DEBUG) {
        logger.log(Logger.INFO, "Authenticate[basic] " + user + ":" + userpwd + ((usrformat == null) ? ":" : ":usrformat=" + usrformat));
    }
    /*
         * LDAP requires the password to be nonempty for simple authentication. otherwise it automatically converts the
         * authentication to "none"
         */
    if (userpwd == null || userpwd.trim().equals("")) {
        throw new LoginException(Globals.getBrokerResources().getKString(BrokerResources.X_PASSWORD_NOT_PROVIDED, user));
    }
    if (user == null || user.trim().equals("")) {
        throw new LoginException(Globals.getBrokerResources().getKString(BrokerResources.X_USERNAME_NOT_PROVIDED, user));
    }
    String url = server;
    if (DEBUG) {
        logger.log(Logger.INFO, "LDAP server: " + url);
    }
    Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    // see JNDI doc
    env.put(Context.REFERRAL, "follow");
    if (sslprotocol) {
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        if (sslfactory != null) {
            env.put("java.naming.ldap.factory.socket", sslfactory);
        }
    }
    String dnName = null;
    boolean dnformat = false;
    if (usrformat != null && usrformat.equals(DN_USRFORMAT)) {
        dnformat = true;
        dnName = user;
        user = handleDNusrformat(user);
    } else {
        dnName = searchDN(user, env);
    }
    DirContext ctx = null;
    try {
        if (!dnformat) {
            logger.log(Logger.INFO, br.getKString(BrokerResources.I_AUTHENTICATE_USER_AS, user, dnName));
        } else {
            logger.log(Logger.INFO, br.getKString(BrokerResources.I_AUTHENTICATE_AS_USER, dnName, user));
        }
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, dnName);
        env.put(Context.SECURITY_CREDENTIALS, userpwd);
        try {
            ctx = new InitialDirContext(env);
            ctx.close();
            Subject subject = new Subject();
            subject.getPrincipals().add(new MQUser(user));
            try {
                findGroups(dnName, subject);
            } catch (NamingException e) {
                String emsg = Globals.getBrokerResources().getKString(BrokerResources.X_LDAP_GROUP_SEARCH_ERROR, user + " [" + dnName + "]");
                logger.logStack(Logger.ERROR, emsg, e);
                throw new LoginException(emsg + ":" + e.getMessage());
            }
            return subject;
        } catch (javax.naming.AuthenticationException e) {
            if (DEBUG) {
                logger.log(Logger.INFO, e.getMessage(), e);
            }
            throw new FailedLoginException(e.getMessage());
        }
    } catch (Exception e) {
        if (e instanceof FailedLoginException) {
            throw (FailedLoginException) e;
        }
        if (e instanceof LoginException) {
            throw (LoginException) e;
        }
        String emsg = null;
        if (e instanceof NamingException) {
            emsg = ((NamingException) e).toString(true);
        } else {
            emsg = e.toString();
        }
        logger.logStack(Logger.ERROR, emsg, e);
        throw new LoginException(emsg);
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException ne) {
        /* ignore */
        }
    }
}
Also used : InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) MQUser(com.sun.messaging.jmq.auth.jaas.MQUser) Subject(javax.security.auth.Subject) LoginException(javax.security.auth.login.LoginException) NamingException(javax.naming.NamingException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) LoginException(javax.security.auth.login.LoginException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) NamingException(javax.naming.NamingException)

Example 5 with FailedLoginException

use of com.sun.messaging.jmq.auth.api.FailedLoginException in project openmq by eclipse-ee4j.

the class LdapUserRepository method searchDN.

private String searchDN(String user, Hashtable env) throws LoginException {
    if (bindDN != null && bindPW != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, bindDN);
        env.put(Context.SECURITY_CREDENTIALS, bindPW);
    }
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[] { uidattr });
        // 
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setTimeLimit(timelimitMillis);
        String filter = uidattr + "=" + user;
        if (usrfilter != null) {
            filter = "(&(" + usrfilter + ")(" + filter + "))";
        }
        if (DEBUG) {
            logger.log(Logger.INFO, "filter:" + filter + ":");
        }
        NamingEnumeration enm = ctx.search(base, filter, ctls);
        int count = 0;
        String dnName = null;
        while (enm.hasMore()) {
            if (count != 0) {
                enm.close();
                throw new NamingException(Globals.getBrokerResources().getKString(BrokerResources.X_NOT_UNIQUE_USER, user, repository));
            }
            SearchResult sr = (SearchResult) enm.next();
            if (!sr.isRelative()) {
                // XXX ???
                throw new NamingException(Globals.getBrokerResources().getKString(BrokerResources.X_LDAP_SEARCH_RESULT_NOT_RELATIVE, sr.getName()));
            }
            Attributes attrs = sr.getAttributes();
            if (attrs == null) {
                throw new NamingException(Globals.getBrokerResources().getKString(BrokerResources.X_DN_NOT_FOUND, user, repository) + "[SearchResult.getAttributes()=" + null + "]");
            }
            Attribute attr = attrs.get(uidattr);
            if (attr == null) {
                throw new NamingException(Globals.getBrokerResources().getKString(BrokerResources.X_DN_NOT_FOUND, user, repository) + "[Attribute.get(" + uidattr + ")=" + null + "]");
            }
            if (!user.equals(attr.get())) {
                throw new FailedLoginException(Globals.getBrokerResources().getKString(BrokerResources.X_DN_NOT_FOUND, user, repository) + "[Attribute.get(" + uidattr + ")=" + attr + "]");
            }
            dnName = sr.getName() + ", " + base;
            count++;
        }
        ctx.close();
        if (dnName == null) {
            throw new FailedLoginException(Globals.getBrokerResources().getKString(BrokerResources.X_DN_NOT_FOUND, user, repository));
        }
        if (DEBUG) {
            logger.log(Logger.INFO, "dn=" + dnName);
        }
        return dnName;
    } catch (Exception e) {
        if (e instanceof FailedLoginException) {
            throw (FailedLoginException) e;
        }
        String emsg = null;
        if (e instanceof NamingException) {
            emsg = ((NamingException) e).toString(true);
        } else {
            emsg = e.toString();
        }
        logger.logStack(Logger.ERROR, emsg, e);
        throw new LoginException(emsg);
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException ne) {
        /* ignore */
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) LoginException(javax.security.auth.login.LoginException) NamingException(javax.naming.NamingException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) LoginException(javax.security.auth.login.LoginException) FailedLoginException(com.sun.messaging.jmq.auth.api.FailedLoginException) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException)

Aggregations

FailedLoginException (com.sun.messaging.jmq.auth.api.FailedLoginException)7 LoginException (javax.security.auth.login.LoginException)5 MQUser (com.sun.messaging.jmq.auth.jaas.MQUser)4 Subject (javax.security.auth.Subject)4 AccessController (com.sun.messaging.jmq.jmsserver.auth.AccessController)2 AuthCacheData (com.sun.messaging.jmq.jmsserver.auth.AuthCacheData)2 IMQService (com.sun.messaging.jmq.jmsserver.service.imq.IMQService)2 BASE64Decoder (com.sun.messaging.jmq.util.BASE64Decoder)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 NamingException (javax.naming.NamingException)2 DirContext (javax.naming.directory.DirContext)2 InitialDirContext (javax.naming.directory.InitialDirContext)2 UserRepository (com.sun.messaging.jmq.auth.api.server.model.UserRepository)1 MQAdminGroup (com.sun.messaging.jmq.auth.jaas.MQAdminGroup)1 HAMonitorService (com.sun.messaging.jmq.jmsserver.cluster.api.ha.HAMonitorService)1 Agent (com.sun.messaging.jmq.jmsserver.management.agent.Agent)1 CoreLifecycleSpi (com.sun.messaging.jmq.jmsserver.plugin.spi.CoreLifecycleSpi)1 Connection (com.sun.messaging.jmq.jmsserver.service.Connection)1 ConnectionUID (com.sun.messaging.jmq.jmsserver.service.ConnectionUID)1 IMQBasicConnection (com.sun.messaging.jmq.jmsserver.service.imq.IMQBasicConnection)1