Java Examples for org.apache.sshd.common.Channel

The following java examples will help you to understand the usage of org.apache.sshd.common.Channel. These source code samples are taken from different open source projects.

Example 1
Project: mina-sshd-master  File: SshClient.java View source code
@Override
protected void checkConfig() {
    super.checkConfig();
    Objects.requireNonNull(getTcpipForwarderFactory(), "TcpipForwarderFactory not set");
    Objects.requireNonNull(getServerKeyVerifier(), "ServerKeyVerifier not set");
    Objects.requireNonNull(getHostConfigEntryResolver(), "HostConfigEntryResolver not set");
    Objects.requireNonNull(getClientIdentityLoader(), "ClientIdentityLoader not set");
    Objects.requireNonNull(getFilePasswordProvider(), "FilePasswordProvider not set");
    // if no client identities override use the default
    KeyPairProvider defaultIdentities = getKeyPairProvider();
    if (defaultIdentities == null) {
        setKeyPairProvider(new DefaultClientIdentitiesWatcher(this::getClientIdentityLoader, this::getFilePasswordProvider));
    }
    // Register the additional agent forwarding channel if needed
    SshAgentFactory agentFactory = getAgentFactory();
    if (agentFactory != null) {
        List<NamedFactory<Channel>> forwarders = ValidateUtils.checkNotNullAndNotEmpty(agentFactory.getChannelForwardingFactories(this), "No agent channel forwarding factories for %s", agentFactory);
        List<NamedFactory<Channel>> factories = getChannelFactories();
        if (GenericUtils.isEmpty(factories)) {
            factories = forwarders;
        } else {
            // create a copy in case un-modifiable original
            List<NamedFactory<Channel>> factories2 = new ArrayList<>(factories.size() + forwarders.size());
            factories2.addAll(factories);
            factories2.addAll(forwarders);
            factories = factories2;
        }
        setChannelFactories(factories);
    }
    if (GenericUtils.isEmpty(getServiceFactories())) {
        setServiceFactories(DEFAULT_SERVICE_FACTORIES);
    }
    if (GenericUtils.isEmpty(getUserAuthFactories())) {
        setUserAuthFactories(DEFAULT_USER_AUTH_FACTORIES);
    }
}
Example 2
Project: termd-master  File: KeepAliveTest.java View source code
@Test
public void testIdleClient() throws Exception {
    SshClient client = setupTestClient();
    client.start();
    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);
        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)));
        }
    } finally {
        client.stop();
    }
}
Example 3
Project: cloud-master  File: EmbeddedSshd.java View source code
public boolean start() throws IOException {
    if (sshd != null) {
        throw new IllegalStateException();
    }
    final boolean authUseKeys = true;
    // TODO: Use AuthorizedSshKeys helper
    final File authorizedKeys = configuration.lookupFile("sshd.authorized_keys", "~/.ssh/authorized_fathomcloud");
    if (!authUseKeys) {
        throw new IllegalArgumentException("Neither password nor publickey SSH-auth are enabled, so won't start SSH server");
    }
    sshd = SshServer.setUpDefaultServer();
    if (authUseKeys) {
        sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {

            @Override
            public boolean authenticate(String username, PublicKey key, ServerSession session) {
                try {
                    String opensshEncoded = OpenSshUtils.serialize(key);
                    log.info("SSH presented public key: " + opensshEncoded);
                    List<String> match = Lists.newArrayList(Splitter.on(CharMatcher.WHITESPACE).split(opensshEncoded));
                    if (!authorizedKeys.exists()) {
                        log.warn("SSH authorized key file does not exist: {}", authorizedKeys);
                    } else {
                        for (String line : Files.readLines(authorizedKeys, Charsets.UTF_8)) {
                            line = line.trim();
                            List<String> tokens = Lists.newArrayList(Splitter.on(CharMatcher.WHITESPACE).split(line));
                            if (tokens.size() < 2) {
                                continue;
                            }
                            if (!match.get(0).equals(tokens.get(0))) {
                                continue;
                            }
                            if (!match.get(1).equals(tokens.get(1))) {
                                continue;
                            }
                            return true;
                        }
                    }
                    return false;
                } catch (Exception e) {
                    log.error("Exception while verifying public key", e);
                    return false;
                }
            }
        });
    }
    // Log if anyone even suggests touching the filesystem
    sshd.setFileSystemFactory(new FileSystemFactory() {

        @Override
        public FileSystemView createFileSystemView(Session session) throws IOException {
            log.warn("Blocking SSHD filesystem access");
            throw new IllegalStateException("Blocking SSHD filesystem access");
        }
    });
    // Log if anyone even suggested forwarding a port
    sshd.setForwardingFilter(new ForwardingFilter() {

        @Override
        public boolean canListen(InetSocketAddress address, ServerSession session) {
            log.warn("Blocking SSHD port forwarding");
            return false;
        }

        @Override
        public boolean canForwardX11(ServerSession session) {
            log.warn("Blocking SSHD port forwarding");
            return false;
        }

        @Override
        public boolean canForwardAgent(ServerSession session) {
            log.warn("Blocking SSHD port forwarding");
            return false;
        }

        @Override
        public boolean canConnect(InetSocketAddress address, ServerSession session) {
            log.warn("Blocking SSHD port forwarding");
            return false;
        }
    });
    sshd.setAgentFactory(new SshAgentFactory() {

        @Override
        public NamedFactory<Channel> getChannelForwardingFactory() {
            log.warn("Blocking SSHD agent functionality");
            throw new IllegalStateException("Blocking SSHD agent functionality");
        }

        @Override
        public SshAgentServer createServer(Session session) throws IOException {
            log.warn("Blocking SSHD agent functionality");
            throw new IllegalStateException("Blocking SSHD agent functionality");
        }

        @Override
        public SshAgent createClient(Session session) throws IOException {
            log.warn("Blocking SSHD agent functionality");
            throw new IllegalStateException("Blocking SSHD agent functionality");
        }
    });
    sshd.setTcpipForwardNioSocketAcceptorFactory(new ForwardingAcceptorFactory() {

        @Override
        public NioSocketAcceptor createNioSocketAcceptor(Session session) {
            log.warn("Blocking SSHD Tcpip Forward functionality");
            throw new IllegalStateException("Blocking SSHD Tcpip Forward access");
        }
    });
    sshd.setX11ForwardNioSocketAcceptorFactory(new ForwardingAcceptorFactory() {

        @Override
        public NioSocketAcceptor createNioSocketAcceptor(Session session) {
            log.warn("Blocking SSHD X11 Forward functionality");
            throw new IllegalStateException("Blocking SSHD X11 Forward access");
        }
    });
    sshd.setShellFactory(new Factory<Command>() {

        @Override
        public Command create() {
            log.warn("Blocking SSHD shell functionality");
            throw new IllegalStateException("Blocking SSHD shell access");
        }
    });
    sshd.setPort(configuration.lookup("sshd.port", 2222));
    File hostkeyPath = configuration.lookupFile("sshd.hostkey", "hostkey.ser");
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostkeyPath.getAbsolutePath()));
    sshd.setCommandFactory(sshCommandFactory);
    List<NamedFactory<Command>> subsystemFactories = sshd.getSubsystemFactories();
    if (subsystemFactories != null) {
        throw new UnsupportedOperationException();
    }
    List<NamedFactory<Channel>> channelFactories = sshd.getChannelFactories();
    sshd.setChannelFactories(Lists.newArrayList(Iterables.filter(channelFactories, new Predicate<NamedFactory<Channel>>() {

        @Override
        public boolean apply(NamedFactory<Channel> command) {
            if (command instanceof ChannelSession.Factory) {
                log.info("Accepting Channel factory: " + command);
                return true;
            } else {
                return false;
            }
        }
    })));
    log.info("Starting SSH server");
    sshd.start();
    for (NamedFactory<UserAuth> authFactory : sshd.getUserAuthFactories()) {
        if (authFactory instanceof UserAuthPublicKey.Factory) {
            if (!authUseKeys) {
                throw new IllegalStateException();
            }
        } else {
            throw new IllegalStateException();
        }
    }
    return true;
}
Example 4
Project: podd-redesign-master  File: SSHService.java View source code
public static SshServer getTestServer() {
    final SshServer sshd = new SshServer();
    // DHG14 uses 2048 bits key which are not supported by the default JCE provider
    // if (SecurityUtils.isBouncyCastleRegistered()) {
    // sshd.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
    // new DHG14.Factory(),
    // new DHG1.Factory()));
    // sshd.setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
    // } else {
    sshd.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(new DHG1.Factory()));
    sshd.setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
    // }
    SSHService.setUpDefaultCiphers(sshd);
    // Compression is not enabled by default
    // sshd.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
    // new CompressionNone.Factory(),
    // new CompressionZlib.Factory(),
    // new CompressionDelayedZlib.Factory()));
    sshd.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(new CompressionNone.Factory()));
    sshd.setMacFactories(Arrays.<NamedFactory<Mac>>asList(new HMACMD5.Factory(), new HMACSHA1.Factory(), new HMACMD596.Factory(), new HMACSHA196.Factory()));
    sshd.setChannelFactories(Arrays.<NamedFactory<Channel>>asList(new ChannelSession.Factory(), new ChannelDirectTcpip.Factory()));
    sshd.setSignatureFactories(Arrays.<NamedFactory<Signature>>asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
    sshd.setFileSystemFactory(new NativeFileSystemFactory());
    final ForwardingAcceptorFactory faf = new DefaultForwardingAcceptorFactory();
    sshd.setTcpipForwardNioSocketAcceptorFactory(faf);
    sshd.setX11ForwardNioSocketAcceptorFactory(faf);
    return sshd;
}
Example 5
Project: sft-master  File: Server.java View source code
@SuppressWarnings("unchecked")
protected void setupFactories() {
    sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new CustomSftpSubsystemFactory()));
    sshd.setMacFactories(//
    Arrays.<//
    NamedFactory<Mac>>asList(BuiltinMacs//
    .hmacsha512, BuiltinMacs//
    .hmacsha256, BuiltinMacs.hmacsha1));
    sshd.setChannelFactories(Arrays.<NamedFactory<Channel>>asList(ChannelSessionFactory.INSTANCE));
}
Example 6
Project: Asynchronous-SSHD-master  File: ServerSession.java View source code
private void channelOpen(Buffer buffer) throws Exception {
    String type = buffer.getString();
    final int id = buffer.getInt();
    final int rwsize = buffer.getInt();
    final int rmpsize = buffer.getInt();
    LogUtils.info(log, "Received SSH_MSG_CHANNEL_OPEN {0}", type);
    if (closing) {
        Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0);
        buf.putInt(id);
        buf.putInt(SshConstants.SSH_OPEN_CONNECT_FAILED);
        buf.putString("SSH server is shutting down: " + type);
        buf.putString("");
        writePacket(buf);
        return;
    }
    if (!allowMoreSessions) {
        Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0);
        buf.putInt(id);
        buf.putInt(SshConstants.SSH_OPEN_CONNECT_FAILED);
        buf.putString("additional sessions disabled");
        buf.putString("");
        writePacket(buf);
        return;
    }
    final Channel channel = NamedFactory.Utils.create(getServerFactoryManager().getChannelFactories(), type);
    if (channel == null) {
        Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0);
        buf.putInt(id);
        buf.putInt(SshConstants.SSH_OPEN_UNKNOWN_CHANNEL_TYPE);
        buf.putString("Unsupported channel type: " + type);
        buf.putString("");
        writePacket(buf);
        return;
    }
    final int channelId = getNextChannelId();
    channels.put(channelId, channel);
    channel.init(this, channelId);
    channel.open(id, rwsize, rmpsize, buffer).addListener(new SshFutureListener<OpenFuture>() {

        public void operationComplete(OpenFuture future) {
            try {
                if (future.isOpened()) {
                    Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, 0);
                    buf.putInt(id);
                    buf.putInt(channelId);
                    buf.putInt(channel.getLocalWindow().getSize());
                    buf.putInt(channel.getLocalWindow().getPacketSize());
                    writePacket(buf);
                } else if (future.getException() != null) {
                    Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0);
                    buf.putInt(id);
                    if (future.getException() instanceof OpenChannelException) {
                        buf.putInt(((OpenChannelException) future.getException()).getReasonCode());
                        buf.putString(future.getException().getMessage());
                    } else {
                        buf.putInt(0);
                        buf.putString("Error opening channel: " + future.getException().getMessage());
                    }
                    buf.putString("");
                    writePacket(buf);
                }
            } catch (IOException e) {
                exceptionCaught(e);
            }
        }
    });
}
Example 7
Project: scumd-master  File: AbstractSession.java View source code
/**
     * Close this session.
     * This method will close all channels, then close the underlying MINA session.
     * The call will not block until the mina session is actually closed.
     */
public CloseFuture close(final boolean immediately) {
    class IoSessionCloser implements IoFutureListener {

        public void operationComplete(IoFuture future) {
            synchronized (lock) {
                log.debug("IoSession closed");
                closeFuture.setClosed();
                lock.notifyAll();
            }
        }
    }
    ;
    synchronized (lock) {
        if (!closing) {
            try {
                closing = true;
                log.info("Closing session");
                Channel[] channelToClose = channels.values().toArray(new Channel[0]);
                if (channelToClose.length > 0) {
                    final AtomicInteger latch = new AtomicInteger(channelToClose.length);
                    for (Channel channel : channelToClose) {
                        log.debug("Closing channel {}", channel.getId());
                        channel.close(immediately).addListener(new SshFutureListener() {

                            public void operationComplete(SshFuture sshFuture) {
                                if (latch.decrementAndGet() == 0) {
                                    log.debug("Closing IoSession");
                                    ioSession.close(true).addListener(new IoSessionCloser());
                                }
                            }
                        });
                    }
                } else {
                    log.debug("Closing IoSession");
                    ioSession.close(immediately).addListener(new IoSessionCloser());
                }
            } catch (Throwable t) {
                log.warn("Error closing session", t);
            }
        }
        return closeFuture;
    }
}
Example 8
Project: karaf-master  File: KarafAgentFactory.java View source code
@Override
public List<NamedFactory<Channel>> getChannelForwardingFactories(FactoryManager factoryManager) {
    return LocalAgentFactory.DEFAULT_FORWARDING_CHANNELS;
}
Example 9
Project: tools_gerrit-master  File: SshDaemon.java View source code
@SuppressWarnings("unchecked")
private void initChannels() {
    setChannelFactories(Arrays.<NamedFactory<Channel>>asList(//
    new ChannelSession.Factory(), //
    new ChannelDirectTcpip.Factory()));
}