Search in sources :

Example 56 with JSch

use of com.jcraft.jsch.JSch in project quickstarts by jboss-switchyard.

the class CamelFtpBindingTest method startUp.

@BeforeClass
public static void startUp() throws Exception {
    FtpServerFactory serverFactory = new FtpServerFactory();
    ListenerFactory listenerFactory = new ListenerFactory();
    listenerFactory.setPort(2222);
    serverFactory.addListener("default", listenerFactory.createListener());
    ListenerFactory sslListenerFactory = new ListenerFactory();
    sslListenerFactory.setPort(2221);
    SslConfigurationFactory ssl = new SslConfigurationFactory();
    ssl.setKeystoreFile(new File("src/test/resources/ftpserver.jks"));
    ssl.setKeystorePassword("password");
    sslListenerFactory.setSslConfiguration(ssl.createSslConfiguration());
    // Setting it to true will not read the file
    sslListenerFactory.setImplicitSsl(false);
    serverFactory.addListener("ftps", sslListenerFactory.createListener());
    PropertiesUserManagerFactory managerFactory = new PropertiesUserManagerFactory();
    managerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
    managerFactory.setFile(new File("src/test/resources/users.properties"));
    UserManager createUserManager = managerFactory.createUserManager();
    serverFactory.setUserManager(createUserManager);
    NativeFileSystemFactory fileSystemFactory = new NativeFileSystemFactory();
    fileSystemFactory.setCreateHome(true);
    serverFactory.setFileSystem(fileSystemFactory);
    File file = new File("target/ftp/ftps");
    file.mkdirs();
    file = new File("target/ftp/sftp");
    file.mkdirs();
    ftpServer = serverFactory.createServer();
    ftpServer.start();
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(2220);
    sshd.setKeyPairProvider(createTestKeyPairProvider("src/test/resources/hostkey.pem"));
    sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
    sshd.start();
    JSch sch = new JSch();
    Session session = sch.getSession("camel", "localhost", 2220);
    session.setUserInfo(new SimpleUserInfo("isMyFriend"));
    session.connect();
    ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
    c.connect();
    System.out.println("Home: " + c.getHome());
    c.chmod(777, ".");
    c.chmod(777, "target");
    c.chmod(777, "target/ftp");
    c.chmod(777, "target/ftp/sftp");
    c.disconnect();
    session.disconnect();
}
Also used : FtpServerFactory(org.apache.ftpserver.FtpServerFactory) NativeFileSystemFactory(org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory) NativeFileSystemFactory(org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory) ScpCommandFactory(org.apache.sshd.server.command.ScpCommandFactory) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) FtpServerFactory(org.apache.ftpserver.FtpServerFactory) NamedFactory(org.apache.sshd.common.NamedFactory) JSch(com.jcraft.jsch.JSch) ClearTextPasswordEncryptor(org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor) SshServer(org.apache.sshd.SshServer) ScpCommandFactory(org.apache.sshd.server.command.ScpCommandFactory) ChannelSftp(com.jcraft.jsch.ChannelSftp) Command(org.apache.sshd.server.Command) UserManager(org.apache.ftpserver.ftplet.UserManager) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) File(java.io.File) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory) ServerSession(org.apache.sshd.server.session.ServerSession) Session(com.jcraft.jsch.Session) BeforeClass(org.junit.BeforeClass)

Example 57 with JSch

use of com.jcraft.jsch.JSch in project dbeaver by serge-rider.

the class SSHUtils method isKeyEncrypted.

public static boolean isKeyEncrypted(String privKeyPath) {
    // Check whether this key is encrypted
    if (privKeyPath != null) {
        // Determine whether public key is encrypted
        try {
            JSch testSch = new JSch();
            testSch.addIdentity(privKeyPath);
            IdentityRepository ir = testSch.getIdentityRepository();
            List<Identity> identities = ir.getIdentities();
            for (Identity identity : identities) {
                if (identity.isEncrypted()) {
                    return true;
                }
            }
        } catch (JSchException e) {
            // Something went wrong
            log.debug("Can't check private key encryption: " + e.getMessage());
        }
    }
    return false;
}
Also used : JSchException(com.jcraft.jsch.JSchException) JSch(com.jcraft.jsch.JSch) Identity(com.jcraft.jsch.Identity) IdentityRepository(com.jcraft.jsch.IdentityRepository)

Example 58 with JSch

use of com.jcraft.jsch.JSch in project DataX by alibaba.

the class SftpHelperImpl method loginFtpServer.

@Override
public void loginFtpServer(String host, String username, String password, int port, int timeout) {
    JSch jsch = new JSch();
    try {
        this.session = jsch.getSession(username, host, port);
        if (this.session == null) {
            throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, "创建ftp连接this.session失败,无法通过sftp与服务器建立链接,请检查主机名和用户名是否正确.");
        }
        this.session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // config.put("PreferredAuthentications", "password");
        this.session.setConfig(config);
        this.session.setTimeout(timeout);
        this.session.connect();
        this.channelSftp = (ChannelSftp) this.session.openChannel("sftp");
        this.channelSftp.connect();
    } catch (JSchException e) {
        if (null != e.getCause()) {
            String cause = e.getCause().toString();
            String unknownHostException = "java.net.UnknownHostException: " + host;
            String illegalArgumentException = "java.lang.IllegalArgumentException: port out of range:" + port;
            String wrongPort = "java.net.ConnectException: Connection refused";
            if (unknownHostException.equals(cause)) {
                String message = String.format("请确认ftp服务器地址是否正确,无法连接到地址为: [%s] 的ftp服务器, errorMessage:%s", host, e.getMessage());
                LOG.error(message);
                throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message, e);
            } else if (illegalArgumentException.equals(cause) || wrongPort.equals(cause)) {
                String message = String.format("请确认连接ftp服务器端口是否正确,错误的端口: [%s], errorMessage:%s", port, e.getMessage());
                LOG.error(message);
                throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message, e);
            }
        } else {
            String message = String.format("与ftp服务器建立连接失败,请检查主机、用户名、密码是否正确, host:%s, port:%s, username:%s, errorMessage:%s", host, port, username, e.getMessage());
            LOG.error(message);
            throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message);
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties)

Example 59 with JSch

use of com.jcraft.jsch.JSch in project KeyBox by skavanagh.

the class AuthKeysKtrl method generateUserKey.

/**
 * generates public private key from passphrase
 *
 * @param username username to set in public key comment
 * @param keyname  keyname to set in public key comment
 * @return public key
 */
public String generateUserKey(String username, String keyname) throws ServletException {
    // set key type
    int type = KeyPair.RSA;
    if ("dsa".equals(SSHUtil.KEY_TYPE)) {
        type = KeyPair.DSA;
    } else if ("ecdsa".equals(SSHUtil.KEY_TYPE)) {
        type = KeyPair.ECDSA;
    }
    JSch jsch = new JSch();
    String pubKey;
    try {
        KeyPair keyPair = KeyPair.genKeyPair(jsch, type, SSHUtil.KEY_LENGTH);
        OutputStream os = new ByteArrayOutputStream();
        keyPair.writePrivateKey(os, publicKey.getPassphrase().getBytes());
        // set private key
        try {
            getRequest().getSession().setAttribute(PVT_KEY, EncryptionUtil.encrypt(os.toString()));
        } catch (GeneralSecurityException ex) {
            log.error(ex.toString(), ex);
            throw new ServletException(ex.toString(), ex);
        }
        os = new ByteArrayOutputStream();
        keyPair.writePublicKey(os, username + "@" + keyname);
        pubKey = os.toString();
        keyPair.dispose();
    } catch (JSchException ex) {
        log.error(ex.toString(), ex);
        throw new ServletException(ex.toString(), ex);
    }
    return pubKey;
}
Also used : ServletException(javax.servlet.ServletException) JSchException(com.jcraft.jsch.JSchException) KeyPair(com.jcraft.jsch.KeyPair) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) GeneralSecurityException(java.security.GeneralSecurityException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JSch(com.jcraft.jsch.JSch)

Example 60 with JSch

use of com.jcraft.jsch.JSch in project KeyBox by skavanagh.

the class SSHUtil method authAndAddPubKey.

/**
 * distributes authorized keys for host system
 *
 * @param hostSystem      object contains host system information
 * @param passphrase      ssh key passphrase
 * @param password        password to host system if needed
 * @return status of key distribution
 */
public static HostSystem authAndAddPubKey(HostSystem hostSystem, String passphrase, String password) {
    JSch jsch = new JSch();
    Session session = null;
    hostSystem.setStatusCd(HostSystem.SUCCESS_STATUS);
    try {
        ApplicationKey appKey = PrivateKeyDB.getApplicationKey();
        // check to see if passphrase has been provided
        if (passphrase == null || passphrase.trim().equals("")) {
            passphrase = appKey.getPassphrase();
            // check for null inorder to use key without passphrase
            if (passphrase == null) {
                passphrase = "";
            }
        }
        // add private key
        jsch.addIdentity(appKey.getId().toString(), appKey.getPrivateKey().trim().getBytes(), appKey.getPublicKey().getBytes(), passphrase.getBytes());
        // create session
        session = jsch.getSession(hostSystem.getUser(), hostSystem.getHost(), hostSystem.getPort());
        // set password if passed in
        if (password != null && !password.equals("")) {
            session.setPassword(password);
        }
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setServerAliveInterval(SERVER_ALIVE_INTERVAL);
        session.connect(SESSION_TIMEOUT);
        addPubKey(hostSystem, session, appKey.getPublicKey());
    } catch (JSchException | SQLException | GeneralSecurityException ex) {
        log.info(ex.toString(), ex);
        hostSystem.setErrorMsg(ex.getMessage());
        if (ex.getMessage().toLowerCase().contains("userauth fail")) {
            hostSystem.setStatusCd(HostSystem.PUBLIC_KEY_FAIL_STATUS);
        } else if (ex.getMessage().toLowerCase().contains("auth fail") || ex.getMessage().toLowerCase().contains("auth cancel")) {
            hostSystem.setStatusCd(HostSystem.AUTH_FAIL_STATUS);
        } else if (ex.getMessage().toLowerCase().contains("unknownhostexception")) {
            hostSystem.setErrorMsg("DNS Lookup Failed");
            hostSystem.setStatusCd(HostSystem.HOST_FAIL_STATUS);
        } else {
            hostSystem.setStatusCd(HostSystem.GENERIC_FAIL_STATUS);
        }
    }
    if (session != null) {
        session.disconnect();
    }
    return hostSystem;
}
Also used : JSchException(com.jcraft.jsch.JSchException) ApplicationKey(io.bastillion.manage.model.ApplicationKey) SQLException(java.sql.SQLException) GeneralSecurityException(java.security.GeneralSecurityException) JSch(com.jcraft.jsch.JSch) SchSession(io.bastillion.manage.model.SchSession) Session(com.jcraft.jsch.Session)

Aggregations

JSch (com.jcraft.jsch.JSch)130 Session (com.jcraft.jsch.Session)72 JSchException (com.jcraft.jsch.JSchException)51 IOException (java.io.IOException)50 Channel (com.jcraft.jsch.Channel)35 File (java.io.File)29 InputStream (java.io.InputStream)29 Properties (java.util.Properties)27 ChannelExec (com.jcraft.jsch.ChannelExec)26 ChannelSftp (com.jcraft.jsch.ChannelSftp)22 KeyPair (com.jcraft.jsch.KeyPair)19 BufferedReader (java.io.BufferedReader)16 UserInfo (com.jcraft.jsch.UserInfo)15 InputStreamReader (java.io.InputStreamReader)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 FileInputStream (java.io.FileInputStream)11 OutputStream (java.io.OutputStream)11 SftpException (com.jcraft.jsch.SftpException)10 FS (org.eclipse.jgit.util.FS)8 FileOutputStream (java.io.FileOutputStream)7