2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.adapter.ssh.sshd;
26 import org.apache.sshd.SshServer;
27 import org.apache.sshd.common.NamedFactory;
28 import org.apache.sshd.common.util.OsUtils;
29 import org.apache.sshd.server.Command;
30 import org.apache.sshd.server.CommandFactory;
31 import org.apache.sshd.server.PasswordAuthenticator;
32 import org.apache.sshd.server.PublickeyAuthenticator;
33 import org.apache.sshd.server.command.ScpCommandFactory;
34 import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
35 import org.apache.sshd.server.session.ServerSession;
36 import org.apache.sshd.server.sftp.SftpSubsystem;
37 import org.apache.sshd.server.shell.ProcessShellFactory;
38 import org.hamcrest.CoreMatchers;
40 import org.junit.rules.ExpectedException;
41 import org.onap.appc.adapter.ssh.SshAdapter;
42 import org.onap.appc.adapter.ssh.SshConnection;
43 import org.onap.appc.adapter.ssh.SshException;
44 import org.onap.appc.adapter.ssh.sshd.SshAdapterSshd;
46 import java.io.ByteArrayOutputStream;
47 import java.io.IOException;
48 import java.io.OutputStream;
49 import java.net.BindException;
50 import java.security.PublicKey;
51 import java.util.Collections;
52 import java.util.EnumSet;
54 public class SshAdapterTest {
56 private static final boolean START_SERVER = true;
57 private static final String SSH_HOST = "localhost";
58 private static final int SSH_PORT = 2222;
59 private static final String SSH_USERNAME = "test";
60 private static final String SSH_PASSWORD = "test";
61 private static final String F_TEST_CMD = "ping -%c 4 %s";
63 private int sshPort = SSH_PORT;
64 private SshServer sshd;
65 private SshAdapter sshAdapter = new SshAdapterSshd();
68 public ExpectedException thrown = ExpectedException.none();
71 public void testExecute() {
72 String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost");
73 SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD);
75 System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
76 ByteArrayOutputStream stdout = new ByteArrayOutputStream();
77 ByteArrayOutputStream stderr = new ByteArrayOutputStream();
78 int status = execCmd(sshConnection, cmd, stdout, stderr, false);
79 Assert.assertEquals(stdout.toString() + ". " + stderr.toString(), 0, status);
81 disconnect(sshConnection);
86 public void testExecuteWithPty() {
87 String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost");
88 SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD);
90 System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
91 ByteArrayOutputStream stdout = new ByteArrayOutputStream();
92 int status = execCmd(sshConnection, cmd, stdout, null, true);
93 Assert.assertEquals(stdout.toString() + ". " + stdout.toString(), 0, status);
95 disconnect(sshConnection);
100 public void testExecuteInvalidCommand() {
101 String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "nosuchhost");
102 SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD);
104 ByteArrayOutputStream stdout = new ByteArrayOutputStream();
105 ByteArrayOutputStream stderr = new ByteArrayOutputStream();
106 int status = execCmd(sshConnection, cmd, stdout, stderr, false);
107 Assert.assertNotEquals(stdout.toString() + ". " + stderr.toString(), 0, status);
109 disconnect(sshConnection);
114 public void testWrongUsername() {
115 thrown.expect(SshException.class);
116 thrown.expectMessage(CoreMatchers.containsString("Authentication failed"));
117 disconnect(connect("WrongUsername", SSH_PASSWORD));
121 public void testWrongPassword() {
122 thrown.expect(SshException.class);
123 thrown.expectMessage(CoreMatchers.containsString("Authentication failed"));
124 disconnect(connect(SSH_USERNAME, "WrongPassword"));
128 public void beforeTest() throws IOException {
135 public void afterTest() throws InterruptedException {
139 private SshConnection connect(String username, String password) {
140 SshConnection sshConnection = sshAdapter.getConnection(SSH_HOST, sshPort, username, password);
141 sshConnection.connect();
142 System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
143 return sshConnection;
146 private void disconnect(SshConnection sshConnection) {
147 sshConnection.disconnect();
148 System.out.println("SSH client disconnected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
151 private int execCmd(SshConnection sshConnection, String cmd, OutputStream stdout, OutputStream stderr, boolean usePty) {
152 System.out.println("=> Running command [" + cmd + "] over SSH");
155 status = sshConnection.execCommandWithPty(cmd, stdout);
157 status = sshConnection.execCommand(cmd, stdout, stderr);
159 System.out.println("=> Command [" + cmd + "] status is [" + status + "], stdout is [" + String.valueOf(stdout) + "], stderr is [" + String.valueOf(stderr) + "]");
163 private void startServer() throws IOException {
164 sshd = SshServer.setUpDefaultServer();
165 sshd.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystem.Factory()));
166 sshd.setCommandFactory(new ScpCommandFactory(new CommandFactory() {
168 public Command createCommand(String command) {
169 EnumSet<ProcessShellFactory.TtyOptions> ttyOptions;
170 if (OsUtils.isUNIX()) {
171 ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr);
173 ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr);
175 return new ProcessShellFactory(command.split(" "), ttyOptions).create();
178 if (OsUtils.isUNIX()) {
179 sshd.setShellFactory(new ProcessShellFactory(new String[]{"/bin/sh", "-i", "-l"},
180 EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr)));
182 sshd.setShellFactory(new ProcessShellFactory(new String[]{"cmd.exe "},
183 EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr)));
185 // if(SecurityUtils.isBouncyCastleRegistered()) {
186 // sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.pem"));
188 sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.ser"));
190 sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
193 public boolean authenticate(String username, String password, ServerSession session) {
194 return (SSH_USERNAME.equals(username) && SSH_PASSWORD.equals(password));
197 sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
199 public boolean authenticate(String username, PublicKey key, ServerSession session) {
203 sshd.getProperties().put(SshServer.WELCOME_BANNER, "Welcome to SSHD\n");
207 } catch (InterruptedException e) {
212 private void startServer0() throws IOException {
213 boolean serverStarted = false;
214 IOException exception = null;
215 while (!serverStarted && (sshPort < Integer.MAX_VALUE)) {
217 System.out.println("Starting SSH server on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
218 sshd.setPort(sshPort);
220 serverStarted = true;
221 } catch (BindException e) {
222 System.err.println("Cannot start SSH server on port [" + sshPort + "]. " + e.getMessage());
223 if (exception == null) {
224 // store first thrown exception - will be thrown if cannot start the server
230 if (!serverStarted) {
233 System.out.println("SSH server started on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
236 private void stopServer() {
240 System.out.println("SSH server stopped on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
242 } catch (InterruptedException e) {
243 System.err.println("=> Error stopping SSH server.");