org.apache.sshd.common.SshException Java Examples

The following examples show how to use org.apache.sshd.common.SshException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected void preClose() {
    if (!authFuture.isDone()) {
        authFuture.setException(new SshException("Session is closed"));
    }
    super.preClose();
}
 
Example #2
Source File: FlushyOutputStream.java    From Bukkit-SSHD with Apache License 2.0 5 votes vote down vote up
@Override
public void write(byte[] b, int off, int len) throws IOException {
    if (isClosed) return;
    try {
        base.write(b, off, len);
        base.flush();
    } catch (SshException e) {
        if (!e.getMessage().contains("channel already closed")) throw e;
    }
}
 
Example #3
Source File: AbstractSftpProviderTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a pipe thread that connects an input to an output
 *
 * @param name     The name of the thread (for debugging purposes)
 * @param in       The input stream
 * @param out      The output stream
 * @param callback An object whose method {@linkplain ExitCallback#onExit(int)} will be called when the pipe is
 *                 broken. The integer argument is 0 if everything went well.
 */
private static void connect(final String name, final InputStream in, final OutputStream out,
                            final ExitCallback callback) {
    final Thread thread = new Thread((Runnable) () -> {
        int code = 0;
        try {
            final byte buffer[] = new byte[1024];
            int len;
            while ((len = in.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
                out.flush();
            }
        } catch (final SshException ex1) {
            // Nothing to do, this occurs when the connection
            // is closed on the remote side
        } catch (final IOException ex2) {
            if (!ex2.getMessage().equals("Pipe closed")) {
                code = -1;
            }
        }
        if (callback != null) {
            callback.onExit(code);
        }
    }, name);
    thread.setDaemon(true);
    thread.start();
}
 
Example #4
Source File: ClientUserAuthServiceOld.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected void preClose() {
    if (!authFuture.isDone()) {
        authFuture.setException(new SshException("Session is closed"));
    }
    super.preClose();
}
 
Example #5
Source File: AsyncUserAuthService.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
    ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
    if (s.isAuthenticated()) {
        throw new SshException("Session already authenticated");
    }

    this.session = (ServerSession) s;
    maxAuthRequests = session.getIntProperty(ServerFactoryManager.MAX_AUTH_REQUESTS, DEFAULT_MAX_AUTH_REQUESTS);

    ServerFactoryManager manager = getFactoryManager();
    userAuthFactories = new ArrayList<>(manager.getUserAuthFactories());
    // Get authentication methods
    authMethods = new ArrayList<>();

    String mths = FactoryManagerUtils.getString(manager, ServerFactoryManager.AUTH_METHODS);
    if (GenericUtils.isEmpty(mths)) {
        for (NamedFactory<UserAuth> uaf : manager.getUserAuthFactories()) {
            authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
        }
    }
    else {
        for (String mthl : mths.split("\\s")) {
            authMethods.add(new ArrayList<>(Arrays.asList(mthl.split(","))));
        }
    }
    // Verify all required methods are supported
    for (List<String> l : authMethods) {
        for (String m : l) {
            NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
            if (factory == null) {
                throw new SshException("Configured method is not supported: " + m);
            }
        }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Authorized authentication methods: "+ NamedResource.Utils.getNames(userAuthFactories));
    }
}
 
Example #6
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
  ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
  if (s.isAuthenticated()) {
    throw new SshException("Session already authenticated");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<>(factories);
  // Get authentication methods
  authMethods = new ArrayList<>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // Verify all required methods are supported
  for (List<String> l : authMethods) {
    for (String m : l) {
      NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
      if (factory == null) {
        throw new SshException("Configured method is not supported: " + m);
      }
    }
  }

  if (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}
 
Example #7
Source File: AuthenticationTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test   // see SSHD-624
public void testMismatchedUserAuthPkOkData() throws Exception {
    final AtomicInteger challengeCounter = new AtomicInteger(0);
    sshd.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
            new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() {
                @Override
                public org.apache.sshd.server.auth.pubkey.UserAuthPublicKey create() {
                    return new org.apache.sshd.server.auth.pubkey.UserAuthPublicKey() {
                        @Override
                        protected void sendPublicKeyResponse(ServerSession session, String username, String alg, PublicKey key,
                                byte[] keyBlob, int offset, int blobLen, Buffer buffer) throws Exception {
                            int count = challengeCounter.incrementAndGet();
                            outputDebugMessage("sendPublicKeyChallenge(%s)[%s]: count=%d", session, alg, count);
                            if (count == 1) {
                                // send wrong key type
                                super.sendPublicKeyResponse(session, username, KeyPairProvider.SSH_DSS, key, keyBlob, offset, blobLen, buffer);
                            } else if (count == 2) {
                                // send another key
                                KeyPair otherPair = org.apache.sshd.util.test.Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
                                PublicKey otherKey = otherPair.getPublic();
                                Buffer buf = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_PK_OK, blobLen + alg.length() + Long.SIZE);
                                buf.putString(alg);
                                buf.putPublicKey(otherKey);
                                session.writePacket(buf);
                            } else {
                                super.sendPublicKeyResponse(session, username, alg, key, keyBlob, offset, blobLen, buffer);
                            }
                        }
                    };
                }

    }));

    try (SshClient client = setupTestClient()) {
        KeyPair clientIdentity = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
        client.start();

        try {
            for (int index = 1; index <= 4; index++) {
                try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
                    s.addPublicKeyIdentity(clientIdentity);
                    s.auth().verify(17L, TimeUnit.SECONDS);
                    assertEquals("Mismatched number of challenges", 3, challengeCounter.get());
                    break;
                } catch (SshException e) {   // expected
                    outputDebugMessage("%s on retry #%d: %s", e.getClass().getSimpleName(), index, e.getMessage());

                    Throwable t = e.getCause();
                    assertObjectInstanceOf("Unexpected failure cause at retry #" + index, InvalidKeySpecException.class, t);
                }
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #8
Source File: NewScpHelper.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public void receive(SshFile path, boolean recursive, boolean shouldBeDir, boolean preserve) throws IOException {
    if (shouldBeDir) {
        if (!path.doesExist()) {
            throw new SshException("Target directory " + path.toString() + " does not exists");
        }
        if (!path.isDirectory()) {
            throw new SshException("Target directory " + path.toString() + " is not a directory");
        }
    }
    ack();
    long[] time = null;
    for (;;) {
        String line;
        boolean isDir = false;
        int c = readAck(true);
        switch (c) {
            case -1:
                return;
            case 'D':
                isDir = true;
                //$FALL-THROUGH$
            case 'C':
                line = ((char) c) + readLine();
                log.debug("Received header: " + line);
                break;
            case 'T':
                line = ((char) c) + readLine();
                log.debug("Received header: " + line);
                time = parseTime(line);
                ack();
                continue;
            case 'E':
                line = ((char) c) + readLine();
                log.debug("Received header: " + line);
                ack();
                return;
            default:
                // a real ack that has been acted upon already
                continue;
        }

        if (recursive && isDir) {
            receiveDir(line, path, time, preserve);
            time = null;
        } else {
            receiveFile(line, path, time, preserve);
            time = null;
        }

        loggingHelper.doLogging(path);
    }
}
 
Example #9
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized SshdSocketAddress startLocalPortForwarding(SshdSocketAddress local, SshdSocketAddress remote)
                throws IOException {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #10
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void stopLocalPortForwarding(SshdSocketAddress local) throws IOException {
    throw new SshException("Tcpip forwarding request denied by server");

}
 
Example #11
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized SshdSocketAddress startRemotePortForwarding(SshdSocketAddress remote, SshdSocketAddress local)
                throws IOException {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #12
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void stopRemotePortForwarding(SshdSocketAddress remote) throws IOException {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #13
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized SshdSocketAddress localPortForwardingRequested(SshdSocketAddress local) throws IOException {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #14
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void localPortForwardingCancelled(SshdSocketAddress local) throws IOException {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #15
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public void sessionCreated(final IoSession session) throws Exception {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #16
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public void sessionClosed(IoSession session) throws Exception {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #17
Source File: DenyingTcpipForwarder.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(IoSession session, Readable message) throws Exception {
    throw new SshException("Tcpip forwarding request denied by server");
}
 
Example #18
Source File: AuthenticationTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test   // see SSHD-624
public void testMismatchedUserAuthPkOkData() throws Exception {
    final AtomicInteger challengeCounter = new AtomicInteger(0);
    sshd.setUserAuthFactories(Collections.<NamedFactory<org.apache.sshd.server.auth.UserAuth>>singletonList(
            new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() {
                @Override
                public org.apache.sshd.server.auth.pubkey.UserAuthPublicKey create() {
                    return new org.apache.sshd.server.auth.pubkey.UserAuthPublicKey() {
                        @Override
                        protected void sendPublicKeyResponse(ServerSession session, String username, String alg, PublicKey key,
                                byte[] keyBlob, int offset, int blobLen, Buffer buffer) throws Exception {
                            int count = challengeCounter.incrementAndGet();
                            outputDebugMessage("sendPublicKeyChallenge(%s)[%s]: count=%d", session, alg, count);
                            if (count == 1) {
                                // send wrong key type
                                super.sendPublicKeyResponse(session, username, KeyPairProvider.SSH_DSS, key, keyBlob, offset, blobLen, buffer);
                            } else if (count == 2) {
                                // send another key
                                KeyPair otherPair = org.apache.sshd.util.test.Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
                                PublicKey otherKey = otherPair.getPublic();
                                Buffer buf = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_PK_OK, blobLen + alg.length() + Long.SIZE);
                                buf.putString(alg);
                                buf.putPublicKey(otherKey);
                                session.writePacket(buf);
                            } else {
                                super.sendPublicKeyResponse(session, username, alg, key, keyBlob, offset, blobLen, buffer);
                            }
                        }
                    };
                }

    }));

    try (SshClient client = setupTestClient()) {
        KeyPair clientIdentity = Utils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024);
        client.start();

        try {
            for (int index = 1; index <= 4; index++) {
                try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
                    s.addPublicKeyIdentity(clientIdentity);
                    s.auth().verify(17L, TimeUnit.SECONDS);
                    assertEquals("Mismatched number of challenges", 3, challengeCounter.get());
                    break;
                } catch (SshException e) {   // expected
                    outputDebugMessage("%s on retry #%d: %s", e.getClass().getSimpleName(), index, e.getMessage());

                    Throwable t = e.getCause();
                    assertObjectInstanceOf("Unexpected failure cause at retry #" + index, InvalidKeySpecException.class, t);
                }
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #19
Source File: AsyncUserAuthService.java    From termd with Apache License 2.0 4 votes vote down vote up
public AsyncUserAuthService(Session s) throws SshException {
  ValidateUtils.checkTrue(s instanceof ServerSession, "Server side service used on client side");
  if (s.isAuthenticated()) {
    throw new SshException("Session already authenticated");
  }

  serverSession = (ServerSession) s;
  maxAuthRequests = PropertyResolverUtils.getIntProperty(s, ServerAuthenticationManager.MAX_AUTH_REQUESTS, ServerAuthenticationManager.DEFAULT_MAX_AUTH_REQUESTS);

  List<NamedFactory<UserAuth>> factories = ValidateUtils.checkNotNullAndNotEmpty(
      serverSession.getUserAuthFactories(), "No user auth factories for %s", s);
  userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(factories);
  // Get authentication methods
  authMethods = new ArrayList<List<String>>();

  String mths = PropertyResolverUtils.getString(s, ServerFactoryManager.AUTH_METHODS);
  if (GenericUtils.isEmpty(mths)) {
    for (NamedFactory<UserAuth> uaf : factories) {
      authMethods.add(new ArrayList<String>(Collections.singletonList(uaf.getName())));
    }
  } else {
    if (log.isDebugEnabled()) {
      log.debug("ServerUserAuthService({}) using configured methods={}", s, mths);
    }
    for (String mthl : mths.split("\\s")) {
      authMethods.add(new ArrayList<String>(Arrays.asList(GenericUtils.split(mthl, ','))));
    }
  }
  // Verify all required methods are supported
  for (List<String> l : authMethods) {
    for (String m : l) {
      NamedFactory<UserAuth> factory = NamedResource.Utils.findByName(m, String.CASE_INSENSITIVE_ORDER, userAuthFactories);
      if (factory == null) {
        throw new SshException("Configured method is not supported: " + m);
      }
    }
  }

  if (log.isDebugEnabled()) {
    log.debug("ServerUserAuthService({}) authorized authentication methods: {}",
        s, NamedResource.Utils.getNames(userAuthFactories));
  }
}