You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SshUnitTest.java 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. * Copyright 2014 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.tests;
  17. import java.io.ByteArrayInputStream;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.IOException;
  20. import java.io.OutputStreamWriter;
  21. import java.io.Writer;
  22. import java.net.SocketAddress;
  23. import java.security.GeneralSecurityException;
  24. import java.security.KeyPair;
  25. import java.security.KeyPairGenerator;
  26. import java.security.PublicKey;
  27. import java.util.EnumSet;
  28. import java.util.concurrent.atomic.AtomicBoolean;
  29. import org.apache.sshd.client.SshClient;
  30. import org.apache.sshd.client.channel.ClientChannel;
  31. import org.apache.sshd.client.channel.ClientChannelEvent;
  32. import org.apache.sshd.client.config.keys.ClientIdentityLoader;
  33. import org.apache.sshd.client.future.AuthFuture;
  34. import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
  35. import org.apache.sshd.client.session.ClientSession;
  36. import org.apache.sshd.common.config.keys.FilePasswordProvider;
  37. import org.apache.sshd.common.util.security.SecurityUtils;
  38. import org.eclipse.jgit.lib.Config;
  39. import org.eclipse.jgit.storage.file.FileBasedConfig;
  40. import org.eclipse.jgit.util.FS;
  41. import org.eclipse.jgit.util.SystemReader;
  42. import org.junit.After;
  43. import org.junit.AfterClass;
  44. import org.junit.Before;
  45. import org.junit.BeforeClass;
  46. import com.gitblit.Constants.AccessPermission;
  47. import com.gitblit.transport.ssh.IPublicKeyManager;
  48. import com.gitblit.transport.ssh.MemoryKeyManager;
  49. import com.gitblit.transport.ssh.SshKey;
  50. /**
  51. * Base class for SSH unit tests.
  52. */
  53. public abstract class SshUnitTest extends GitblitUnitTest {
  54. protected static final AtomicBoolean started = new AtomicBoolean(false);
  55. protected static KeyPairGenerator generator;
  56. protected KeyPair rwKeyPair;
  57. protected KeyPair roKeyPair;
  58. protected String username = "admin";
  59. protected String password = "admin";
  60. @BeforeClass
  61. public static void startGitblit() throws Exception {
  62. generator = SecurityUtils.getKeyPairGenerator("RSA");
  63. started.set(GitBlitSuite.startGitblit());
  64. final SystemReader dsr = SystemReader.getInstance();
  65. SystemReader.setInstance(new SystemReader()
  66. {
  67. final SystemReader defaultsr = dsr;
  68. @Override
  69. public String getHostname()
  70. {
  71. return defaultsr.getHostname();
  72. }
  73. @Override
  74. public String getenv(String variable)
  75. {
  76. if ("GIT_SSH".equalsIgnoreCase(variable)) {
  77. return null;
  78. }
  79. return defaultsr.getenv(variable);
  80. }
  81. @Override
  82. public String getProperty(String key)
  83. {
  84. return defaultsr.getProperty(key);
  85. }
  86. @Override
  87. public FileBasedConfig openUserConfig(Config parent, FS fs)
  88. {
  89. return defaultsr.openUserConfig(parent, fs);
  90. }
  91. @Override
  92. public FileBasedConfig openSystemConfig(Config parent, FS fs)
  93. {
  94. return defaultsr.openSystemConfig(parent, fs);
  95. }
  96. @Override
  97. public long getCurrentTime()
  98. {
  99. return defaultsr.getCurrentTime();
  100. }
  101. @Override
  102. public int getTimezone(long when)
  103. {
  104. return defaultsr.getTimezone(when);
  105. }
  106. });
  107. }
  108. @AfterClass
  109. public static void stopGitblit() throws Exception {
  110. if (started.get()) {
  111. GitBlitSuite.stopGitblit();
  112. }
  113. }
  114. protected MemoryKeyManager getKeyManager() {
  115. IPublicKeyManager mgr = gitblit().getPublicKeyManager();
  116. if (mgr instanceof MemoryKeyManager) {
  117. return (MemoryKeyManager) gitblit().getPublicKeyManager();
  118. } else {
  119. throw new RuntimeException("unexpected key manager type " + mgr.getClass().getName());
  120. }
  121. }
  122. @Before
  123. public void prepare() {
  124. rwKeyPair = generator.generateKeyPair();
  125. MemoryKeyManager keyMgr = getKeyManager();
  126. keyMgr.addKey(username, new SshKey(rwKeyPair.getPublic()));
  127. roKeyPair = generator.generateKeyPair();
  128. SshKey sshKey = new SshKey(roKeyPair.getPublic());
  129. sshKey.setPermission(AccessPermission.CLONE);
  130. keyMgr.addKey(username, sshKey);
  131. }
  132. @After
  133. public void tearDown() {
  134. MemoryKeyManager keyMgr = getKeyManager();
  135. keyMgr.removeAllKeys(username);
  136. }
  137. protected SshClient getClient() {
  138. SshClient client = SshClient.setUpDefaultClient();
  139. client.setClientIdentityLoader(new ClientIdentityLoader() { // Ignore the files under ~/.ssh
  140. @Override
  141. public boolean isValidLocation(String location) throws IOException {
  142. return true;
  143. }
  144. @Override
  145. public KeyPair loadClientIdentity(String location, FilePasswordProvider provider) throws IOException, GeneralSecurityException {
  146. return null;
  147. }
  148. });
  149. client.setServerKeyVerifier(new ServerKeyVerifier() {
  150. @Override
  151. public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress, PublicKey serverKey) {
  152. return true;
  153. }
  154. });
  155. client.start();
  156. return client;
  157. }
  158. protected String testSshCommand(String cmd) throws IOException, InterruptedException {
  159. return testSshCommand(cmd, null);
  160. }
  161. protected String testSshCommand(String cmd, String stdin) throws IOException, InterruptedException {
  162. SshClient client = getClient();
  163. ClientSession session = client.connect(username, "localhost", GitBlitSuite.sshPort).verify().getSession();
  164. session.addPublicKeyIdentity(rwKeyPair);
  165. AuthFuture authFuture = session.auth();
  166. assertTrue(authFuture.await());
  167. assertTrue(authFuture.isSuccess());
  168. ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_EXEC, cmd);
  169. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  170. if (stdin != null) {
  171. Writer w = new OutputStreamWriter(baos);
  172. w.write(stdin);
  173. w.close();
  174. }
  175. channel.setIn(new ByteArrayInputStream(baos.toByteArray()));
  176. ByteArrayOutputStream out = new ByteArrayOutputStream();
  177. ByteArrayOutputStream err = new ByteArrayOutputStream();
  178. channel.setOut(out);
  179. channel.setErr(err);
  180. channel.open();
  181. channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.EOF), 0);
  182. String result = out.toString().trim();
  183. channel.close(false);
  184. client.stop();
  185. return result;
  186. }
  187. }