First part of onap rename
[appc.git] / appc-adapters / appc-ssh-adapter / appc-ssh-adapter-sshd / src / test / java / org / openecomp / appc / adapter / ssh / sshd / SshAdapterTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.ssh.sshd;
26
27 import org.apache.sshd.SshServer;
28 import org.apache.sshd.common.NamedFactory;
29 import org.apache.sshd.common.util.OsUtils;
30 import org.apache.sshd.server.Command;
31 import org.apache.sshd.server.CommandFactory;
32 import org.apache.sshd.server.PasswordAuthenticator;
33 import org.apache.sshd.server.PublickeyAuthenticator;
34 import org.apache.sshd.server.command.ScpCommandFactory;
35 import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
36 import org.apache.sshd.server.session.ServerSession;
37 import org.apache.sshd.server.sftp.SftpSubsystem;
38 import org.apache.sshd.server.shell.ProcessShellFactory;
39 import org.hamcrest.CoreMatchers;
40 import org.junit.*;
41 import org.junit.rules.ExpectedException;
42 import org.onap.appc.adapter.ssh.SshAdapter;
43 import org.onap.appc.adapter.ssh.SshConnection;
44 import org.onap.appc.adapter.ssh.SshException;
45 import org.onap.appc.adapter.ssh.sshd.SshAdapterSshd;
46
47 import java.io.ByteArrayOutputStream;
48 import java.io.IOException;
49 import java.io.OutputStream;
50 import java.net.BindException;
51 import java.security.PublicKey;
52 import java.util.Collections;
53 import java.util.EnumSet;
54
55 public class SshAdapterTest {
56
57     private static final boolean START_SERVER = true;
58     private static final String SSH_HOST = "localhost";
59     private static final int SSH_PORT = 2222;
60     private static final String SSH_USERNAME = "test";
61     private static final String SSH_PASSWORD = "test";
62     private static final String F_TEST_CMD = "ping -%c 4 %s";
63
64     private int sshPort = SSH_PORT;
65     private SshServer sshd;
66     private SshAdapter sshAdapter = new SshAdapterSshd();
67
68     @Rule
69     public ExpectedException thrown = ExpectedException.none();
70
71     @Test
72     public void testExecute() {
73         String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost");
74         SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD);
75         try {
76             System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
77             ByteArrayOutputStream stdout = new ByteArrayOutputStream();
78             ByteArrayOutputStream stderr = new ByteArrayOutputStream();
79             int status = execCmd(sshConnection, cmd, stdout, stderr, false);
80             Assert.assertEquals(stdout.toString() + ". " + stderr.toString(), 0, status);
81         } finally {
82             disconnect(sshConnection);
83         }
84     }
85
86     @Test
87     public void testExecuteWithPty() {
88         String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost");
89         SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD);
90         try {
91             System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
92             ByteArrayOutputStream stdout = new ByteArrayOutputStream();
93             int status = execCmd(sshConnection, cmd, stdout, null, true);
94             Assert.assertEquals(stdout.toString() + ". " + stdout.toString(), 0, status);
95         } finally {
96             disconnect(sshConnection);
97         }
98     }
99
100     @Test
101     public void testExecuteInvalidCommand() {
102         String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "nosuchhost");
103         SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD);
104         try {
105             ByteArrayOutputStream stdout = new ByteArrayOutputStream();
106             ByteArrayOutputStream stderr = new ByteArrayOutputStream();
107             int status = execCmd(sshConnection, cmd, stdout, stderr, false);
108             Assert.assertNotEquals(stdout.toString() + ". " + stderr.toString(), 0, status);
109         } finally {
110             disconnect(sshConnection);
111         }
112     }
113
114     @Test
115     public void testWrongUsername() {
116         thrown.expect(SshException.class);
117         thrown.expectMessage(CoreMatchers.containsString("Authentication failed"));
118         disconnect(connect("WrongUsername", SSH_PASSWORD));
119     }
120
121     @Test
122     public void testWrongPassword() {
123         thrown.expect(SshException.class);
124         thrown.expectMessage(CoreMatchers.containsString("Authentication failed"));
125         disconnect(connect(SSH_USERNAME, "WrongPassword"));
126     }
127
128     @Before
129     public void beforeTest() throws IOException {
130         if (START_SERVER) {
131             startServer();
132         }
133     }
134
135     @After
136     public void afterTest() throws InterruptedException {
137         stopServer();
138     }
139
140     private SshConnection connect(String username, String password) {
141         SshConnection sshConnection = sshAdapter.getConnection(SSH_HOST, sshPort, username, password);
142         sshConnection.connect();
143         System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
144         return sshConnection;
145     }
146
147     private void disconnect(SshConnection sshConnection) {
148         sshConnection.disconnect();
149         System.out.println("SSH client disconnected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
150     }
151
152     private int execCmd(SshConnection sshConnection, String cmd, OutputStream stdout, OutputStream stderr, boolean usePty) {
153         System.out.println("=> Running command [" + cmd + "] over SSH");
154         int status;
155         if (usePty) {
156             status = sshConnection.execCommandWithPty(cmd, stdout);
157         } else {
158             status = sshConnection.execCommand(cmd, stdout, stderr);
159         }
160         System.out.println("=> Command [" + cmd + "] status is [" + status + "], stdout is [" + String.valueOf(stdout) + "], stderr is [" + String.valueOf(stderr) + "]");
161         return status;
162     }
163
164     private void startServer() throws IOException {
165         sshd = SshServer.setUpDefaultServer();
166         sshd.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystem.Factory()));
167         sshd.setCommandFactory(new ScpCommandFactory(new CommandFactory() {
168
169             public Command createCommand(String command) {
170                 EnumSet<ProcessShellFactory.TtyOptions> ttyOptions;
171                 if (OsUtils.isUNIX()) {
172                     ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr);
173                 } else {
174                     ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr);
175                 }
176                 return new ProcessShellFactory(command.split(" "), ttyOptions).create();
177             }
178         }));
179         if (OsUtils.isUNIX()) {
180             sshd.setShellFactory(new ProcessShellFactory(new String[]{"/bin/sh", "-i", "-l"},
181                     EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr)));
182         } else {
183             sshd.setShellFactory(new ProcessShellFactory(new String[]{"cmd.exe "},
184                     EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr)));
185         }
186 //              if(SecurityUtils.isBouncyCastleRegistered()) {
187 //                      sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.pem"));
188 //              } else {
189         sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.ser"));
190 //              }
191         sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
192
193             @Override
194             public boolean authenticate(String username, String password, ServerSession session) {
195                 return (SSH_USERNAME.equals(username) && SSH_PASSWORD.equals(password));
196             }
197         });
198         sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
199
200             public boolean authenticate(String username, PublicKey key, ServerSession session) {
201                 return true;
202             }
203         });
204         sshd.getProperties().put(SshServer.WELCOME_BANNER, "Welcome to SSHD\n");
205         startServer0();
206         try {
207             Thread.sleep(1000);
208         } catch (InterruptedException e) {
209             // ignore
210         }
211     }
212
213     private void startServer0() throws IOException {
214         boolean serverStarted = false;
215         IOException exception = null;
216         while (!serverStarted && (sshPort < Integer.MAX_VALUE)) {
217             try {
218                 System.out.println("Starting SSH server on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
219                 sshd.setPort(sshPort);
220                 sshd.start();
221                 serverStarted = true;
222             } catch (BindException e) {
223                 System.err.println("Cannot start SSH server on port [" + sshPort + "]. " + e.getMessage());
224                 if (exception == null) {
225                     // store first thrown exception - will be thrown if cannot start the server
226                     exception = e;
227                 }
228                 sshPort++;
229             }
230         }
231         if (!serverStarted) {
232             throw exception;
233         }
234         System.out.println("SSH server started on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
235     }
236
237     private void stopServer() {
238         try {
239             if (sshd != null) {
240                 sshd.stop(true);
241                 System.out.println("SSH server stopped on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]");
242             }
243         } catch (InterruptedException e) {
244             System.err.println("=> Error stopping SSH server.");
245             e.printStackTrace();
246         } finally {
247             sshd = null;
248         }
249     }
250 }