Search in sources :

Example 31 with SocketException

use of java.net.SocketException in project OpenAM by OpenRock.

the class RADIUS method process.

/**
     * Takes an array of submitted <code>Callback</code>, process them and decide the order of next state to go. Return
     * STATE_SUCCEED if the login is successful, return STATE_FAILED if the LoginModule should be ignored.
     *
     * @param callbacks
     *            an array of <code>Callback</code> for this Login state
     * @param state
     *            order of state. State order starts with 1.
     * @return int order of next state. Return STATE_SUCCEED if authentication is successful, return STATE_FAILED if the
     *         LoginModule should be ignored.
     * @throws AuthLoginException if the user fails authentication or some anomalous condition occurs
     */
@Override
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    String tmpPasswd = null;
    String sState;
    switch(state) {
        case ISAuthConstants.LOGIN_START:
            try {
                radiusConn = new RadiusConn(primaryServers, secondaryServers, sharedSecret, iTimeOut, healthCheckInterval);
            } catch (SocketException se) {
                debug.error("RADIUS login failure; Socket Exception se == ", se);
                shutdown();
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusNoServer", null);
            } catch (Exception e) {
                debug.error("RADIUS login failure; Can't connect to RADIUS server", e);
                shutdown();
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusNoServer", null);
            }
            if (callbacks != null && callbacks.length == 0) {
                username = (String) sharedState.get(getUserKey());
                tmpPasswd = (String) sharedState.get(getPwdKey());
                if (username == null || tmpPasswd == null) {
                    return ISAuthConstants.LOGIN_START;
                }
                getCredentialsFromSharedState = true;
            } else {
                username = ((NameCallback) callbacks[0]).getName();
                tmpPasswd = charToString(((PasswordCallback) callbacks[1]).getPassword(), callbacks[1]);
                if (debug.messageEnabled()) {
                    debug.message("username: " + username);
                }
            }
            storeUsernamePasswd(username, tmpPasswd);
            try {
                succeeded = false;
                radiusConn.authenticate(username, tmpPasswd);
            } catch (RejectException re) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                if (debug.messageEnabled()) {
                    debug.message("Radius login request rejected", re);
                }
                shutdown();
                setFailureID(username);
                throw new InvalidPasswordException(AM_AUTH_RADIUS, "RadiusLoginFailed", null, username, re);
            } catch (IOException ioe) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                debug.error("Radius request IOException", ioe);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (java.security.NoSuchAlgorithmException ne) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                debug.error("Radius No Such Algorithm Exception", ne);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (ChallengeException ce) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                cException = ce;
                sState = ce.getState();
                if (sState == null) {
                    debug.error("Radius failure - no state returned in challenge");
                    shutdown();
                    setFailureID(username);
                    throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusAuth", null);
                }
                challengeID = ce.getReplyMessage();
                if (debug.messageEnabled()) {
                    debug.message("Server challenge with " + "challengeID: " + challengeID);
                }
                setDynamicText(2);
                return ISAuthConstants.LOGIN_CHALLENGE;
            } catch (Exception e) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null, e);
            }
            succeeded = true;
            break;
        case ISAuthConstants.LOGIN_CHALLENGE:
            String passwd = getChallengePassword(callbacks);
            if (debug.messageEnabled()) {
                debug.message("reply to challenge--username: " + username);
            }
            try {
                succeeded = false;
                radiusConn.replyChallenge(username, passwd, cException);
            } catch (ChallengeException ce) {
                sState = ce.getState();
                if (sState == null) {
                    debug.error("handle Challenge failure - no state returned");
                    shutdown();
                    setFailureID(username);
                    throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
                }
                resetCallback(2, 0);
                challengeID = ce.getReplyMessage();
                if (debug.messageEnabled()) {
                    debug.message("Server challenge again with challengeID: " + challengeID);
                }
                // save it for next replyChallenge
                cException = ce;
                setDynamicText(2);
                return ISAuthConstants.LOGIN_CHALLENGE;
            } catch (RejectException ex) {
                debug.error("Radius challenge response rejected", ex);
                shutdown();
                setFailureID(username);
                throw new InvalidPasswordException(AM_AUTH_RADIUS, "RadiusLoginFailed", null, username, ex);
            } catch (IOException ioe) {
                debug.error("Radius challenge IOException", ioe);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (java.security.NoSuchAlgorithmException ex) {
                debug.error("Radius No Such Algorithm Exception", ex);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (Exception e) {
                debug.error("RADIUS challenge Authentication Failed ", e);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            }
            succeeded = true;
            break;
        default:
            debug.error("RADIUS Authentication Failed - invalid state" + state);
            shutdown();
            succeeded = false;
            setFailureID(username);
            throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
    }
    if (succeeded) {
        if (debug.messageEnabled()) {
            debug.message("RADIUS authentication successful");
        }
        if (username != null) {
            StringTokenizer usernameToken = new StringTokenizer(username, ",");
            userTokenId = usernameToken.nextToken();
        }
        if (debug.messageEnabled()) {
            debug.message("userTokenID: " + userTokenId);
        }
        shutdown();
        return ISAuthConstants.LOGIN_SUCCEED;
    } else {
        if (debug.messageEnabled()) {
            debug.message("RADIUS authentication to be ignored");
        }
        return ISAuthConstants.LOGIN_IGNORE;
    }
}
Also used : SocketException(java.net.SocketException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) RejectException(com.sun.identity.authentication.modules.radius.client.RejectException) IOException(java.io.IOException) RadiusConn(com.sun.identity.authentication.modules.radius.client.RadiusConn) IOException(java.io.IOException) ChallengeException(com.sun.identity.authentication.modules.radius.client.ChallengeException) SocketException(java.net.SocketException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) RejectException(com.sun.identity.authentication.modules.radius.client.RejectException) ChallengeException(com.sun.identity.authentication.modules.radius.client.ChallengeException) StringTokenizer(java.util.StringTokenizer) PasswordCallback(javax.security.auth.callback.PasswordCallback) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException)

Example 32 with SocketException

use of java.net.SocketException in project voltdb by VoltDB.

the class RealVoltDB method collectLocalNetworkMetadata.

void collectLocalNetworkMetadata() {
    boolean threw = false;
    JSONStringer stringer = new JSONStringer();
    try {
        stringer.object();
        stringer.key("interfaces").array();
        if (m_config.m_externalInterface.equals("")) {
            LinkedList<NetworkInterface> interfaces = new LinkedList<>();
            try {
                Enumeration<NetworkInterface> intfEnum = NetworkInterface.getNetworkInterfaces();
                while (intfEnum.hasMoreElements()) {
                    NetworkInterface intf = intfEnum.nextElement();
                    if (intf.isLoopback() || !intf.isUp()) {
                        continue;
                    }
                    interfaces.offer(intf);
                }
            } catch (SocketException e) {
                throw new RuntimeException(e);
            }
            if (interfaces.isEmpty()) {
                stringer.value("localhost");
            } else {
                boolean addedIp = false;
                while (!interfaces.isEmpty()) {
                    NetworkInterface intf = interfaces.poll();
                    Enumeration<InetAddress> inetAddrs = intf.getInetAddresses();
                    Inet6Address inet6addr = null;
                    Inet4Address inet4addr = null;
                    while (inetAddrs.hasMoreElements()) {
                        InetAddress addr = inetAddrs.nextElement();
                        if (addr instanceof Inet6Address) {
                            inet6addr = (Inet6Address) addr;
                            if (inet6addr.isLinkLocalAddress()) {
                                inet6addr = null;
                            }
                        } else if (addr instanceof Inet4Address) {
                            inet4addr = (Inet4Address) addr;
                        }
                    }
                    if (inet4addr != null) {
                        stringer.value(inet4addr.getHostAddress());
                        addedIp = true;
                    }
                    if (inet6addr != null) {
                        stringer.value(inet6addr.getHostAddress());
                        addedIp = true;
                    }
                }
                if (!addedIp) {
                    stringer.value("localhost");
                }
            }
        } else {
            stringer.value(m_config.m_externalInterface);
        }
    } catch (Exception e) {
        threw = true;
        hostLog.warn("Error while collecting data about local network interfaces", e);
    }
    try {
        if (threw) {
            stringer = new JSONStringer();
            stringer.object();
            stringer.key("interfaces").array();
            stringer.value("localhost");
            stringer.endArray();
        } else {
            stringer.endArray();
        }
        stringer.keySymbolValuePair("clientPort", m_config.m_port);
        stringer.keySymbolValuePair("clientInterface", m_config.m_clientInterface);
        stringer.keySymbolValuePair("adminPort", m_config.m_adminPort);
        stringer.keySymbolValuePair("adminInterface", m_config.m_adminInterface);
        stringer.keySymbolValuePair("httpPort", m_config.m_httpPort);
        stringer.keySymbolValuePair("httpInterface", m_config.m_httpPortInterface);
        stringer.keySymbolValuePair("internalPort", m_config.m_internalPort);
        stringer.keySymbolValuePair("internalInterface", m_config.m_internalInterface);
        String[] zkInterface = m_config.m_zkInterface.split(":");
        stringer.keySymbolValuePair("zkPort", zkInterface[1]);
        stringer.keySymbolValuePair("zkInterface", zkInterface[0]);
        stringer.keySymbolValuePair("drPort", VoltDB.getReplicationPort(m_catalogContext.cluster.getDrproducerport()));
        stringer.keySymbolValuePair("drInterface", VoltDB.getDefaultReplicationInterface());
        stringer.keySymbolValuePair("publicInterface", m_config.m_publicInterface);
        stringer.endObject();
        JSONObject obj = new JSONObject(stringer.toString());
        // possibly atomic swap from null to realz
        m_localMetadata = obj.toString(4);
        hostLog.debug("System Metadata is: " + m_localMetadata);
    } catch (Exception e) {
        hostLog.warn("Failed to collect data about lcoal network interfaces", e);
    }
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) LinkedList(java.util.LinkedList) SocketException(java.net.SocketException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) JSONException(org.json_voltpatches.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeeperException(org.apache.zookeeper_voltpatches.KeeperException) SettingsException(org.voltdb.settings.SettingsException) JSONObject(org.json_voltpatches.JSONObject) JSONStringer(org.json_voltpatches.JSONStringer) InetAddress(java.net.InetAddress)

Example 33 with SocketException

use of java.net.SocketException in project java-chassis by ServiceComb.

the class TrustManagerExt method checkCNHost.

// ? : learn java default / apache CN check
private void checkCNHost(X509Certificate[] chain, String ip) throws CertificateException {
    if (option.isCheckCNHost()) {
        X509Certificate owner = CertificateUtil.findOwner(chain);
        Set<String> cns = CertificateUtil.getCN(owner);
        String ipTmp = ip == null ? custom.getHost() : ip;
        // 从本机来的请求, 只要CN与本机的任何一个IP地址匹配即可
        if ("127.0.0.1".equals(ipTmp)) {
            try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                if (interfaces != null) {
                    while (interfaces.hasMoreElements()) {
                        NetworkInterface nif = interfaces.nextElement();
                        Enumeration<InetAddress> ias = nif.getInetAddresses();
                        while (ias.hasMoreElements()) {
                            InetAddress ia = ias.nextElement();
                            String local = ia.getHostAddress();
                            if (cnValid(cns, local)) {
                                return;
                            }
                        }
                    }
                }
            } catch (SocketException e) {
                throw new CertificateException("Get local adrress fail.");
            }
        } else if (cnValid(cns, ipTmp)) {
            return;
        }
        LOG.error("CN does not match IP: e=" + cns.toString() + ",t=" + ip);
        throw new CertificateException("CN does not match IP: e=" + cns.toString() + ",t=" + ip);
    }
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) CertificateException(java.security.cert.CertificateException) InetAddress(java.net.InetAddress) X509Certificate(java.security.cert.X509Certificate)

Example 34 with SocketException

use of java.net.SocketException in project android_frameworks_base by ResurrectionRemix.

the class NetworkTest method testBindSocketOfLocalSocketThrows.

@SmallTest
public void testBindSocketOfLocalSocketThrows() throws Exception {
    final LocalSocket mLocalClient = new LocalSocket();
    mLocalClient.bind(new LocalSocketAddress("testClient"));
    assertTrue(mLocalClient.getFileDescriptor().valid());
    try {
        mNetwork.bindSocket(mLocalClient.getFileDescriptor());
        fail("SocketException not thrown");
    } catch (SocketException expected) {
    }
    final LocalServerSocket mLocalServer = new LocalServerSocket("testServer");
    mLocalClient.connect(mLocalServer.getLocalSocketAddress());
    assertTrue(mLocalClient.isConnected());
    try {
        mNetwork.bindSocket(mLocalClient.getFileDescriptor());
        fail("SocketException not thrown");
    } catch (SocketException expected) {
    }
}
Also used : SocketException(java.net.SocketException) LocalServerSocket(android.net.LocalServerSocket) LocalSocketAddress(android.net.LocalSocketAddress) LocalSocket(android.net.LocalSocket) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Example 35 with SocketException

use of java.net.SocketException in project android_frameworks_base by ResurrectionRemix.

the class Network method bindSocket.

/**
     * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the
     * socket represented by this file descriptor will be sent on this {@code Network},
     * irrespective of any process-wide network binding set by
     * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
     */
public void bindSocket(FileDescriptor fd) throws IOException {
    try {
        final SocketAddress peer = Os.getpeername(fd);
        final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress();
        if (!inetPeer.isAnyLocalAddress()) {
            // routing upon mark changes.
            throw new SocketException("Socket is connected");
        }
    } catch (ErrnoException e) {
        // getpeername() failed.
        if (e.errno != OsConstants.ENOTCONN) {
            throw e.rethrowAsSocketException();
        }
    } catch (ClassCastException e) {
        // Wasn't an InetSocketAddress.
        throw new SocketException("Only AF_INET/AF_INET6 sockets supported");
    }
    final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
    if (err != 0) {
        // bindSocketToNetwork returns negative errno.
        throw new ErrnoException("Binding socket to network " + netId, -err).rethrowAsSocketException();
    }
}
Also used : SocketException(java.net.SocketException) ErrnoException(android.system.ErrnoException) InetSocketAddress(java.net.InetSocketAddress) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress)

Aggregations

SocketException (java.net.SocketException)925 IOException (java.io.IOException)349 InetAddress (java.net.InetAddress)254 NetworkInterface (java.net.NetworkInterface)240 UnknownHostException (java.net.UnknownHostException)153 Socket (java.net.Socket)146 SocketTimeoutException (java.net.SocketTimeoutException)118 ServerSocket (java.net.ServerSocket)114 DatagramSocket (java.net.DatagramSocket)95 Test (org.junit.Test)87 InetSocketAddress (java.net.InetSocketAddress)84 ArrayList (java.util.ArrayList)70 Inet4Address (java.net.Inet4Address)51 DatagramPacket (java.net.DatagramPacket)49 ConnectException (java.net.ConnectException)48 InputStream (java.io.InputStream)41 InterruptedIOException (java.io.InterruptedIOException)41 BindException (java.net.BindException)36 EOFException (java.io.EOFException)33 OutputStream (java.io.OutputStream)32